From 91df62d46142e921b3eacdb52b0316c39ee236bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Fri, 20 Feb 2015 09:02:09 -0500 Subject: [PATCH] Update all new Tasks --- Conf/task.yaml | 145 +++++- .../Catalan-numbers-Pascals-triangle | 1 + Lang/ACL2/File-input-output | 1 + Lang/ALGOL-68/Amb | 1 + Lang/ALGOL-68/Calendar---for-REAL-programmers | 1 + Lang/ALGOL-68/Closures-Value-capture | 1 + Lang/ALGOL-68/Combinations-and-permutations | 1 + Lang/ALGOL-68/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/ALGOL-68/Fibonacci-word | 1 + Lang/ALGOL-68/File-input-output | 1 + Lang/ALGOL-68/Gaussian-elimination | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/ALGOL-68/Hello-world-Newbie | 1 + Lang/ALGOL-68/Maximum-triangle-path-sum | 1 + Lang/ALGOL-68/Move-to-front-algorithm | 1 + Lang/ALGOL-68/Nth | 1 + Lang/ALGOL-68/Odd-word-problem | 1 + Lang/ALGOL-68/Old-lady-swallowed-a-fly | 1 + Lang/ALGOL-68/Rep-string | 1 + Lang/ALGOL-68/String-append | 1 + Lang/ALGOL-68/String-matching | 1 + Lang/ALGOL-68/String-prepend | 1 + Lang/ALGOL-68/Zero-to-the-zero-power | 1 + Lang/ATS/Generate-lower-case-ASCII-alphabet | 1 + Lang/ATS/Sequence-of-primes-by-Trial-Division | 1 + Lang/AWK/Benfords-law | 1 + Lang/AWK/CSV-data-manipulation | 1 + Lang/AWK/Comma-quibbling | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/AWK/Draw-a-clock | 1 + Lang/AWK/File-input-output | 1 + Lang/AWK/Generate-lower-case-ASCII-alphabet | 1 + Lang/AWK/Hello-world-Newbie | 1 + Lang/AWK/Magic-squares-of-odd-order | 1 + Lang/AWK/Narcissistic-decimal-number | 1 + Lang/AWK/Nth | 1 + Lang/AWK/Old-lady-swallowed-a-fly | 1 + Lang/AWK/Phrase-reversals | 1 + Lang/AWK/Ranking-methods | 1 + Lang/AWK/Reverse-words-in-a-string | 1 + Lang/AWK/Runge-Kutta-method | 1 + Lang/AWK/String-append | 1 + Lang/AWK/String-matching | 1 + Lang/AWK/String-prepend | 1 + Lang/AWK/Sum-multiples-of-3-and-5 | 1 + Lang/AWK/The-Twelve-Days-of-Christmas | 1 + Lang/AWK/Unix-ls | 1 + Lang/AWK/Zero-to-the-zero-power | 1 + Lang/ActionScript/Draw-a-clock | 1 + .../ActionScript/The-Twelve-Days-of-Christmas | 1 + Lang/Ada/ABC-Problem | 1 + Lang/Ada/Almost-prime | 1 + Lang/Ada/Amb | 1 + Lang/Ada/Benfords-law | 1 + Lang/Ada/Calendar---for-REAL-programmers | 1 + Lang/Ada/Catalan-numbers-Pascals-triangle | 1 + Lang/Ada/Catamorphism | 1 + Lang/Ada/Chinese-remainder-theorem | 1 + Lang/Ada/Closures-Value-capture | 1 + Lang/Ada/Comma-quibbling | 1 + Lang/Ada/Conjugate-transpose | 1 + Lang/Ada/Convert-decimal-number-to-rational | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Ada/Extensible-prime-generator | 1 + Lang/Ada/Fibonacci-word | 1 + Lang/Ada/File-input-output | 1 + Lang/Ada/Flipping-bits-game | 1 + Lang/Ada/Fractran | 1 + Lang/Ada/Generate-lower-case-ASCII-alphabet | 1 + Lang/Ada/IBAN | 1 + Lang/Ada/Integer-overflow | 1 + Lang/Ada/Magic-squares-of-odd-order | 1 + Lang/Ada/Maximum-triangle-path-sum | 1 + Lang/Ada/Move-to-front-algorithm | 1 + Lang/Ada/Munching-squares | 1 + Lang/Ada/Narcissistic-decimal-number | 1 + Lang/Ada/Nth | 1 + Lang/Ada/Odd-word-problem | 1 + Lang/Ada/Old-lady-swallowed-a-fly | 1 + Lang/Ada/Pernicious-numbers | 1 + Lang/Ada/Phrase-reversals | 1 + Lang/Ada/Rep-string | 1 + Lang/Ada/Reverse-words-in-a-string | 1 + Lang/Ada/Runge-Kutta-method | 1 + Lang/Ada/Semiprime | 1 + Lang/Ada/Sequence-of-primes-by-Trial-Division | 1 + Lang/Ada/Solve-a-Holy-Knights-tour | 1 + Lang/Ada/Solve-the-no-connection-puzzle | 1 + Lang/Ada/Statistics-Basic | 1 + Lang/Ada/String-matching | 1 + Lang/Ada/The-Twelve-Days-of-Christmas | 1 + Lang/Ada/Ulam-spiral--for-primes- | 1 + Lang/Ada/Unix-ls | 1 + Lang/Ada/Zero-to-the-zero-power | 1 + Lang/Aime/Benfords-law | 1 + Lang/Aime/File-input-output | 1 + Lang/Aime/Reverse-words-in-a-string | 1 + Lang/Aime/String-matching | 1 + Lang/AppleScript/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Applesoft-BASIC/Nth | 1 + .../Applesoft-BASIC/Reverse-words-in-a-string | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/AutoHotkey/ABC-Problem | 1 + Lang/AutoHotkey/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/AutoHotkey/Almost-prime | 1 + Lang/AutoHotkey/Amb | 1 + Lang/AutoHotkey/Amicable-pairs | 1 + Lang/AutoHotkey/Benfords-law | 1 + Lang/AutoHotkey/CSV-data-manipulation | 1 + .../Calendar---for-REAL-programmers | 1 + .../Catalan-numbers-Pascals-triangle | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/AutoHotkey/Comma-quibbling | 1 + .../Convert-decimal-number-to-rational | 1 + Lang/AutoHotkey/Draw-a-clock | 1 + Lang/AutoHotkey/Extensible-prime-generator | 1 + Lang/AutoHotkey/Fibonacci-word | 1 + Lang/AutoHotkey/Fibonacci-word-fractal | 1 + Lang/AutoHotkey/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + Lang/AutoHotkey/Flipping-bits-game | 1 + Lang/AutoHotkey/Fractran | 1 + .../Generate-Chess960-starting-position | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/AutoHotkey/Hello-world-Newbie | 1 + Lang/AutoHotkey/IBAN | 1 + Lang/AutoHotkey/Integer-overflow | 1 + .../AutoHotkey/Longest-increasing-subsequence | 1 + Lang/AutoHotkey/Ludic-numbers | 1 + Lang/AutoHotkey/Machine-code | 1 + Lang/AutoHotkey/Magic-squares-of-odd-order | 1 + Lang/AutoHotkey/Narcissistic-decimal-number | 1 + Lang/AutoHotkey/Nth | 1 + Lang/AutoHotkey/Old-lady-swallowed-a-fly | 1 + Lang/AutoHotkey/Order-disjoint-list-items | 1 + Lang/AutoHotkey/Pernicious-numbers | 1 + Lang/AutoHotkey/Phrase-reversals | 1 + Lang/AutoHotkey/Quickselect-algorithm | 1 + Lang/AutoHotkey/Rep-string | 1 + Lang/AutoHotkey/Reverse-words-in-a-string | 1 + .../Rosetta-Code-Find-bare-lang-tags | 1 + Lang/AutoHotkey/Semiprime | 1 + Lang/AutoHotkey/Sparkline-in-unicode | 1 + Lang/AutoHotkey/String-append | 1 + Lang/AutoHotkey/String-matching | 1 + Lang/AutoHotkey/String-prepend | 1 + Lang/AutoHotkey/Sum-multiples-of-3-and-5 | 1 + Lang/AutoHotkey/The-Twelve-Days-of-Christmas | 1 + Lang/AutoHotkey/Zero-to-the-zero-power | 1 + Lang/AutoHotkey/Zhang-Suen-thinning-algorithm | 1 + Lang/AutoIt/String-matching | 1 + Lang/Axiom/Closures-Value-capture | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/BASIC/File-input-output | 1 + Lang/BASIC/Runge-Kutta-method | 1 + Lang/BASIC/String-append | 1 + Lang/BASIC/String-matching | 1 + Lang/BASIC/String-prepend | 1 + Lang/BBC-BASIC/ABC-Problem | 1 + .../BBC-BASIC/Calendar---for-REAL-programmers | 1 + Lang/BBC-BASIC/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/BBC-BASIC/IBAN | 1 + Lang/BBC-BASIC/Machine-code | 1 + Lang/BBC-BASIC/Nth | 1 + Lang/BBC-BASIC/Reverse-words-in-a-string | 1 + Lang/BBC-BASIC/String-matching | 1 + Lang/Babel/Closures-Value-capture | 1 + Lang/Babel/File-input-output | 1 + Lang/Babel/Nth | 1 + Lang/Babel/Old-lady-swallowed-a-fly | 1 + Lang/Batch-File/ABC-Problem | 1 + .../Catalan-numbers-Pascals-triangle | 1 + Lang/Batch-File/File-input-output | 1 + Lang/Befunge/File-input-output | 1 + Lang/Bracmat/ABC-Problem | 1 + Lang/Bracmat/AKS-test-for-primes | 1 + Lang/Bracmat/Amb | 1 + Lang/Bracmat/Catamorphism | 1 + Lang/Bracmat/Chinese-remainder-theorem | 1 + Lang/Bracmat/Closures-Value-capture | 1 + Lang/Bracmat/Combinations-and-permutations | 1 + .../Convert-decimal-number-to-rational | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Bracmat/File-input-output | 1 + Lang/Bracmat/Fractran | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Bracmat/Hash-join | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Bracmat/IBAN | 1 + Lang/Bracmat/Left-factorials | 1 + Lang/Bracmat/Maximum-triangle-path-sum | 1 + Lang/Bracmat/Odd-word-problem | 1 + Lang/Bracmat/Order-disjoint-list-items | 1 + Lang/Bracmat/Phrase-reversals | 1 + Lang/Bracmat/Rep-string | 1 + Lang/Bracmat/Reverse-words-in-a-string | 1 + Lang/Bracmat/Solve-a-Holy-Knights-tour | 1 + Lang/Bracmat/State-name-puzzle | 1 + Lang/Bracmat/String-matching | 1 + Lang/Bracmat/String-prepend | 1 + Lang/Bracmat/The-Twelve-Days-of-Christmas | 1 + Lang/Bracmat/Zero-to-the-zero-power | 1 + Lang/Burlesque/Munching-squares | 1 + Lang/C++/9-billion-names-of-God-the-integer | 1 + Lang/C++/ABC-Problem | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/C++/Benfords-law | 1 + Lang/C++/CSV-data-manipulation | 1 + Lang/C++/Casting-out-nines | 1 + Lang/C++/Catalan-numbers-Pascals-triangle | 1 + Lang/C++/Catamorphism | 1 + Lang/C++/Closures-Value-capture | 1 + Lang/C++/Comma-quibbling | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/C++/Draw-a-clock | 1 + Lang/C++/Fibonacci-word | 1 + Lang/C++/Fibonacci-word-fractal | 1 + Lang/C++/File-input-output | 1 + Lang/C++/Find-the-last-Sunday-of-each-month | 1 + Lang/C++/Flipping-bits-game | 1 + Lang/C++/Fractran | 1 + Lang/C++/Generate-Chess960-starting-position | 1 + Lang/C++/Generate-lower-case-ASCII-alphabet | 1 + Lang/C++/Hickerson-series-of-almost-integers | 1 + Lang/C++/IBAN | 1 + Lang/C++/Iterated-digits-squaring | 1 + Lang/C++/Longest-increasing-subsequence | 1 + Lang/C++/Ludic-numbers | 1 + Lang/C++/Magic-squares-of-odd-order | 1 + Lang/C++/Maximum-triangle-path-sum | 1 + Lang/C++/Move-to-front-algorithm | 1 + Lang/C++/Munching-squares | 1 + Lang/C++/Narcissistic-decimal-number | 1 + Lang/C++/Odd-word-problem | 1 + Lang/C++/Penneys-game | 1 + Lang/C++/Percolation-Mean-run-density | 1 + Lang/C++/Pernicious-numbers | 1 + Lang/C++/Phrase-reversals | 1 + Lang/C++/Quickselect-algorithm | 1 + Lang/C++/Rep-string | 1 + Lang/C++/Reverse-words-in-a-string | 1 + Lang/C++/Semiprime | 1 + Lang/C++/Solve-a-Holy-Knights-tour | 1 + Lang/C++/Solve-a-Hopido-puzzle | 1 + Lang/C++/Solve-a-Numbrix-puzzle | 1 + Lang/C++/Sparkline-in-unicode | 1 + Lang/C++/String-append | 1 + Lang/C++/String-matching | 1 + Lang/C++/String-prepend | 1 + Lang/C++/Sum-multiples-of-3-and-5 | 1 + Lang/C++/The-Twelve-Days-of-Christmas | 1 + Lang/C++/Zero-to-the-zero-power | 1 + Lang/C-sharp/ABC-Problem | 1 + Lang/C-sharp/Almost-prime | 1 + Lang/C-sharp/Amb | 1 + Lang/C-sharp/CSV-data-manipulation | 1 + Lang/C-sharp/Catamorphism | 1 + Lang/C-sharp/Currying | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/C-sharp/Hash-join | 1 + Lang/C-sharp/IBAN | 1 + Lang/C-sharp/Munching-squares | 1 + Lang/C-sharp/String-prepend | 1 + Lang/C-sharp/The-ISAAC-Cipher | 1 + Lang/C/9-billion-names-of-God-the-integer | 1 + Lang/C/ABC-Problem | 1 + Lang/C/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/C/Almost-prime | 1 + Lang/C/Amb | 1 + Lang/C/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/C/Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/C/Benfords-law | 1 + Lang/C/Bernoulli-numbers | 1 + Lang/C/Bitcoin-public-point-to-address | 1 + Lang/C/Catamorphism | 1 + Lang/C/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/C/Closures-Value-capture | 1 + Lang/C/Combinations-and-permutations | 1 + Lang/C/Comma-quibbling | 1 + Lang/C/Conjugate-transpose | 1 + Lang/C/Convert-decimal-number-to-rational | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/C/Draw-a-clock | 1 + Lang/C/Extensible-prime-generator | 1 + Lang/C/Fibonacci-word | 1 + Lang/C/File-input-output | 1 + Lang/C/Flipping-bits-game | 1 + Lang/C/Fractran | 1 + Lang/C/Gaussian-elimination | 1 + Lang/C/Generate-lower-case-ASCII-alphabet | 1 + Lang/C/Hickerson-series-of-almost-integers | 1 + Lang/C/IBAN | 1 + Lang/C/Integer-overflow | 1 + Lang/C/Iterated-digits-squaring | 1 + Lang/C/K-d-tree | 1 + Lang/C/Left-factorials | 1 + Lang/C/Longest-increasing-subsequence | 1 + Lang/C/Ludic-numbers | 1 + Lang/C/Machine-code | 1 + Lang/C/Magic-squares-of-odd-order | 1 + Lang/C/Maximum-triangle-path-sum | 1 + Lang/C/Move-to-front-algorithm | 1 + Lang/C/Munching-squares | 1 + Lang/C/Narcissistic-decimal-number | 1 + Lang/C/Natural-sorting | 1 + Lang/C/Nth | 1 + Lang/C/Odd-word-problem | 1 + Lang/C/Old-lady-swallowed-a-fly | 1 + Lang/C/Paraffins | 1 + Lang/C/Parse-an-IP-Address | 1 + Lang/C/Penneys-game | 1 + Lang/C/Percolation-Bond-percolation | 1 + Lang/C/Percolation-Mean-cluster-density | 1 + Lang/C/Percolation-Mean-run-density | 1 + Lang/C/Percolation-Site-percolation | 1 + Lang/C/Permutations-Rank-of-a-permutation | 1 + Lang/C/Pernicious-numbers | 1 + Lang/C/Phrase-reversals | 1 + Lang/C/Quickselect-algorithm | 1 + Lang/C/Rep-string | 1 + Lang/C/Reverse-words-in-a-string | 1 + Lang/C/Rosetta-Code-Find-bare-lang-tags | 1 + Lang/C/Runge-Kutta-method | 1 + Lang/C/Semiprime | 1 + Lang/C/State-name-puzzle | 1 + Lang/C/Statistics-Basic | 1 + Lang/C/Stern-Brocot-sequence | 1 + Lang/C/String-append | 1 + Lang/C/String-matching | 1 + Lang/C/String-prepend | 1 + Lang/C/Sum-multiples-of-3-and-5 | 1 + Lang/C/The-ISAAC-Cipher | 1 + Lang/C/The-Twelve-Days-of-Christmas | 1 + Lang/C/Total-circles-area | 1 + Lang/C/Ulam-spiral--for-primes- | 1 + Lang/C/Unix-ls | 1 + Lang/C/Zero-to-the-zero-power | 1 + Lang/COBOL/Comma-quibbling | 1 + Lang/COBOL/File-input-output | 1 + Lang/COBOL/Hello-world-Newbie | 1 + .../COBOL/Hickerson-series-of-almost-integers | 1 + Lang/COBOL/IBAN | 1 + Lang/COBOL/Quickselect-algorithm | 1 + Lang/COBOL/String-prepend | 1 + Lang/COBOL/Sum-multiples-of-3-and-5 | 1 + Lang/COBOL/The-Twelve-Days-of-Christmas | 1 + Lang/Cache-ObjectScript/IBAN | 1 + Lang/Clean/File-input-output | 1 + Lang/Clojure/ABC-Problem | 1 + Lang/Clojure/AKS-test-for-primes | 1 + Lang/Clojure/Amb | 1 + Lang/Clojure/CSV-data-manipulation | 1 + Lang/Clojure/Catamorphism | 1 + Lang/Clojure/Comma-quibbling | 1 + Lang/Clojure/Fibonacci-word | 1 + Lang/Clojure/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Clojure/Hash-join | 1 + Lang/Clojure/Hello-world-Newbie | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Clojure/IBAN | 1 + Lang/Clojure/Integer-overflow | 1 + Lang/Clojure/Longest-increasing-subsequence | 1 + Lang/Clojure/Ludic-numbers | 1 + Lang/Clojure/Make-directory-path | 1 + Lang/Clojure/Nth | 1 + Lang/Clojure/Odd-word-problem | 1 + Lang/Clojure/Reverse-words-in-a-string | 1 + Lang/Clojure/Stern-Brocot-sequence | 1 + Lang/Clojure/String-append | 1 + Lang/Clojure/String-matching | 1 + Lang/Clojure/String-prepend | 1 + Lang/Clojure/Sum-multiples-of-3-and-5 | 1 + Lang/Clojure/The-Twelve-Days-of-Christmas | 1 + Lang/Clojure/Unix-ls | 1 + Lang/CoffeeScript/ABC-Problem | 1 + Lang/CoffeeScript/AKS-test-for-primes | 1 + Lang/CoffeeScript/Benfords-law | 1 + Lang/CoffeeScript/Closures-Value-capture | 1 + Lang/CoffeeScript/Comma-quibbling | 1 + Lang/CoffeeScript/Odd-word-problem | 1 + Lang/CoffeeScript/Statistics-Basic | 1 + Lang/CoffeeScript/String-matching | 1 + Lang/ColdFusion/File-input-output | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/Common-Lisp/ABC-Problem | 1 + Lang/Common-Lisp/AKS-test-for-primes | 1 + Lang/Common-Lisp/Almost-prime | 1 + Lang/Common-Lisp/Amb | 1 + Lang/Common-Lisp/Benfords-law | 1 + Lang/Common-Lisp/Bernoulli-numbers | 1 + Lang/Common-Lisp/CSV-data-manipulation | 1 + Lang/Common-Lisp/Casting-out-nines | 1 + Lang/Common-Lisp/Catamorphism | 1 + Lang/Common-Lisp/Chinese-remainder-theorem | 1 + Lang/Common-Lisp/Closures-Value-capture | 1 + Lang/Common-Lisp/Comma-quibbling | 1 + Lang/Common-Lisp/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Common-Lisp/File-input-output | 1 + Lang/Common-Lisp/Fractran | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Common-Lisp/Hash-join | 1 + Lang/Common-Lisp/IBAN | 1 + .../Longest-increasing-subsequence | 1 + Lang/Common-Lisp/Machine-code | 1 + Lang/Common-Lisp/Magic-squares-of-odd-order | 1 + Lang/Common-Lisp/Maximum-triangle-path-sum | 1 + Lang/Common-Lisp/Move-to-front-algorithm | 1 + Lang/Common-Lisp/Narcissistic-decimal-number | 1 + Lang/Common-Lisp/Nth | 1 + Lang/Common-Lisp/Odd-word-problem | 1 + Lang/Common-Lisp/Pernicious-numbers | 1 + Lang/Common-Lisp/RSA-code | 1 + Lang/Common-Lisp/Reverse-words-in-a-string | 1 + Lang/Common-Lisp/Semiprime | 1 + Lang/Common-Lisp/String-append | 1 + Lang/Common-Lisp/String-matching | 1 + Lang/Common-Lisp/String-prepend | 1 + Lang/Common-Lisp/Sum-multiples-of-3-and-5 | 1 + Lang/Component-Pascal/String-matching | 1 + .../Component-Pascal/Sum-multiples-of-3-and-5 | 1 + Lang/D/9-billion-names-of-God-the-integer | 1 + Lang/D/ABC-Problem | 1 + Lang/D/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/D/Aliquot-sequence-classifications | 1 + Lang/D/Almost-prime | 1 + Lang/D/Amb | 1 + Lang/D/Amicable-pairs | 1 + Lang/D/Benfords-law | 1 + Lang/D/Bernoulli-numbers | 1 + Lang/D/Bitcoin-public-point-to-address | 1 + Lang/D/CSV-data-manipulation | 1 + Lang/D/Calendar---for-REAL-programmers | 1 + Lang/D/Casting-out-nines | 1 + Lang/D/Catalan-numbers-Pascals-triangle | 1 + Lang/D/Catamorphism | 1 + Lang/D/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/D/Closures-Value-capture | 1 + Lang/D/Combinations-and-permutations | 1 + Lang/D/Comma-quibbling | 1 + Lang/D/Conjugate-transpose | 1 + Lang/D/Convert-decimal-number-to-rational | 1 + Lang/D/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/D/Extensible-prime-generator | 1 + Lang/D/Fibonacci-word | 1 + Lang/D/Fibonacci-word-fractal | 1 + Lang/D/File-input-output | 1 + Lang/D/Find-the-last-Sunday-of-each-month | 1 + Lang/D/Flipping-bits-game | 1 + Lang/D/Fractran | 1 + Lang/D/Gaussian-elimination | 1 + Lang/D/Generate-Chess960-starting-position | 1 + Lang/D/Generate-lower-case-ASCII-alphabet | 1 + Lang/D/Hash-join | 1 + Lang/D/Hello-world-Newbie | 1 + Lang/D/Heronian-triangles | 1 + Lang/D/Hickerson-series-of-almost-integers | 1 + Lang/D/IBAN | 1 + Lang/D/Integer-overflow | 1 + Lang/D/Iterated-digits-squaring | 1 + Lang/D/K-d-tree | 1 + Lang/D/Left-factorials | 1 + Lang/D/Longest-increasing-subsequence | 1 + Lang/D/Ludic-numbers | 1 + Lang/D/Machine-code | 1 + Lang/D/Magic-squares-of-odd-order | 1 + Lang/D/Maximum-triangle-path-sum | 1 + Lang/D/Move-to-front-algorithm | 1 + Lang/D/Munching-squares | 1 + Lang/D/Narcissistic-decimal-number | 1 + Lang/D/Natural-sorting | 1 + Lang/D/Nth | 1 + Lang/D/Odd-word-problem | 1 + Lang/D/Old-lady-swallowed-a-fly | 1 + Lang/D/Order-disjoint-list-items | 1 + Lang/D/Paraffins | 1 + Lang/D/Penneys-game | 1 + Lang/D/Percolation-Bond-percolation | 1 + Lang/D/Percolation-Mean-cluster-density | 1 + Lang/D/Percolation-Mean-run-density | 1 + Lang/D/Percolation-Site-percolation | 1 + Lang/D/Permutations-Rank-of-a-permutation | 1 + Lang/D/Pernicious-numbers | 1 + Lang/D/Phrase-reversals | 1 + Lang/D/Quickselect-algorithm | 1 + Lang/D/RSA-code | 1 + Lang/D/Rep-string | 1 + Lang/D/Reverse-words-in-a-string | 1 + Lang/D/Runge-Kutta-method | 1 + Lang/D/Semiprime | 1 + Lang/D/Sequence-of-primes-by-Trial-Division | 1 + Lang/D/Solve-a-Holy-Knights-tour | 1 + Lang/D/Solve-a-Hopido-puzzle | 1 + Lang/D/Solve-a-Numbrix-puzzle | 1 + Lang/D/Solve-the-no-connection-puzzle | 1 + Lang/D/Sparkline-in-unicode | 1 + Lang/D/State-name-puzzle | 1 + Lang/D/Statistics-Basic | 1 + Lang/D/Stern-Brocot-sequence | 1 + Lang/D/String-append | 1 + Lang/D/String-matching | 1 + Lang/D/String-prepend | 1 + Lang/D/Sum-multiples-of-3-and-5 | 1 + Lang/D/The-ISAAC-Cipher | 1 + Lang/D/The-Twelve-Days-of-Christmas | 1 + Lang/D/Total-circles-area | 1 + Lang/D/Ulam-spiral--for-primes- | 1 + Lang/D/Unix-ls | 1 + Lang/D/Vogels-approximation-method | 1 + Lang/D/World-Cup-group-stage | 1 + Lang/D/Zero-to-the-zero-power | 1 + Lang/D/Zhang-Suen-thinning-algorithm | 1 + Lang/Dart/Runge-Kutta-method | 1 + Lang/Dart/Statistics-Basic | 1 + Lang/Deja-Vu/Catamorphism | 1 + Lang/Deja-Vu/Comma-quibbling | 1 + Lang/Deja-Vu/Hash-join | 1 + Lang/Deja-Vu/Longest-increasing-subsequence | 1 + Lang/Deja-Vu/String-prepend | 1 + Lang/Deja-Vu/Sum-multiples-of-3-and-5 | 1 + Lang/Delphi/ABC-Problem | 1 + Lang/Delphi/Closures-Value-capture | 1 + Lang/Delphi/File-input-output | 1 + .../Delphi/Generate-lower-case-ASCII-alphabet | 1 + Lang/Delphi/String-matching | 1 + Lang/Delphi/Sum-multiples-of-3-and-5 | 1 + Lang/Delphi/The-ISAAC-Cipher | 1 + Lang/E/Amb | 1 + Lang/E/File-input-output | 1 + Lang/E/String-matching | 1 + Lang/Eiffel/File-input-output | 1 + Lang/Eiffel/Ludic-numbers | 1 + Lang/Eiffel/Sum-multiples-of-3-and-5 | 1 + Lang/Ela/Amb | 1 + Lang/Elena/Amb | 1 + Lang/Elena/Calendar---for-REAL-programmers | 1 + Lang/Elena/String-matching | 1 + Lang/Elixir/Reverse-words-in-a-string | 1 + Lang/Elixir/Sparkline-in-unicode | 1 + Lang/Elixir/String-matching | 1 + Lang/Emacs-Lisp/Closures-Value-capture | 1 + .../Erlang/9-billion-names-of-God-the-integer | 1 + Lang/Erlang/ABC-Problem | 1 + Lang/Erlang/AKS-test-for-primes | 1 + Lang/Erlang/Benfords-law | 1 + Lang/Erlang/CSV-data-manipulation | 1 + Lang/Erlang/Chinese-remainder-theorem | 1 + Lang/Erlang/Closures-Value-capture | 1 + Lang/Erlang/Comma-quibbling | 1 + Lang/Erlang/Currying | 1 + Lang/Erlang/File-input-output | 1 + .../Erlang/Find-the-last-Sunday-of-each-month | 1 + Lang/Erlang/Hash-join | 1 + Lang/Erlang/Hello-world-Newbie | 1 + Lang/Erlang/Odd-word-problem | 1 + Lang/Erlang/String-matching | 1 + Lang/Erlang/Sum-multiples-of-3-and-5 | 1 + Lang/Erlang/World-Cup-group-stage | 1 + Lang/Euphoria/ABC-Problem | 1 + Lang/Euphoria/File-input-output | 1 + Lang/Euphoria/String-append | 1 + Lang/Euphoria/String-matching | 1 + Lang/F-Sharp/Runge-Kutta-method | 1 + Lang/FALSE/Odd-word-problem | 1 + Lang/FALSE/Sparkline-in-unicode | 1 + Lang/FBSL/ABC-Problem | 1 + Lang/FBSL/Find-the-last-Sunday-of-each-month | 1 + Lang/FBSL/String-matching | 1 + Lang/FBSL/Sum-multiples-of-3-and-5 | 1 + Lang/Factor/Amb | 1 + Lang/Factor/Closures-Value-capture | 1 + Lang/Factor/Conjugate-transpose | 1 + Lang/Factor/File-input-output | 1 + .../Factor/Generate-lower-case-ASCII-alphabet | 1 + Lang/Factor/Odd-word-problem | 1 + Lang/Factor/Old-lady-swallowed-a-fly | 1 + Lang/Factor/String-prepend | 1 + Lang/Factor/Zero-to-the-zero-power | 1 + Lang/Fantom/Closures-Value-capture | 1 + Lang/Fantom/String-matching | 1 + Lang/Forth/Benfords-law | 1 + Lang/Forth/CSV-data-manipulation | 1 + Lang/Forth/Chinese-remainder-theorem | 1 + Lang/Forth/Currying | 1 + Lang/Forth/File-input-output | 1 + Lang/Forth/Nth | 1 + Lang/Forth/Odd-word-problem | 1 + Lang/Forth/Old-lady-swallowed-a-fly | 1 + Lang/Forth/Semiprime | 1 + Lang/Forth/String-matching | 1 + Lang/Forth/Sum-multiples-of-3-and-5 | 1 + Lang/Forth/Unix-ls | 1 + Lang/Forth/Zero-to-the-zero-power | 1 + Lang/Fortran/ABC-Problem | 1 + Lang/Fortran/Benfords-law | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Fortran/Conjugate-transpose | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Fortran/Draw-a-clock | 1 + Lang/Fortran/File-input-output | 1 + Lang/Fortran/Flipping-bits-game | 1 + Lang/Fortran/Gaussian-elimination | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Fortran/Nth | 1 + Lang/Fortran/Percolation-Mean-run-density | 1 + Lang/Fortran/Percolation-Site-percolation | 1 + Lang/Fortran/Runge-Kutta-method | 1 + Lang/Fortran/Statistics-Basic | 1 + Lang/Fortran/Zero-to-the-zero-power | 1 + Lang/Frege/Old-lady-swallowed-a-fly | 1 + Lang/Frink/9-billion-names-of-God-the-integer | 1 + Lang/Frink/File-input-output | 1 + Lang/GAP/File-input-output | 1 + Lang/GML/File-input-output | 1 + Lang/GML/String-matching | 1 + Lang/GUISS/Calendar---for-REAL-programmers | 1 + Lang/GUISS/Draw-a-clock | 1 + Lang/GUISS/File-input-output | 1 + Lang/Gnuplot/Munching-squares | 1 + Lang/Go/ABC-Problem | 1 + Lang/Go/AKS-test-for-primes | 1 + Lang/Go/Almost-prime | 1 + Lang/Go/Amb | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Go/Benfords-law | 1 + Lang/Go/Bernoulli-numbers | 1 + Lang/Go/Bitcoin-public-point-to-address | 1 + Lang/Go/CSV-data-manipulation | 1 + Lang/Go/Casting-out-nines | 1 + Lang/Go/Catamorphism | 1 + Lang/Go/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Go/Closures-Value-capture | 1 + Lang/Go/Comma-quibbling | 1 + Lang/Go/Conjugate-transpose | 1 + Lang/Go/Convert-decimal-number-to-rational | 1 + Lang/Go/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Go/Draw-a-clock | 1 + Lang/Go/Extensible-prime-generator | 1 + Lang/Go/Fibonacci-word | 1 + Lang/Go/File-input-output | 1 + Lang/Go/Find-the-last-Sunday-of-each-month | 1 + Lang/Go/Flipping-bits-game | 1 + Lang/Go/Fractran | 1 + Lang/Go/Gaussian-elimination | 1 + Lang/Go/Generate-Chess960-starting-position | 1 + Lang/Go/Generate-lower-case-ASCII-alphabet | 1 + Lang/Go/Hash-join | 1 + Lang/Go/Hickerson-series-of-almost-integers | 1 + Lang/Go/IBAN | 1 + Lang/Go/Integer-overflow | 1 + Lang/Go/Iterated-digits-squaring | 1 + Lang/Go/K-d-tree | 1 + Lang/Go/Left-factorials | 1 + Lang/Go/Longest-increasing-subsequence | 1 + Lang/Go/Ludic-numbers | 1 + Lang/Go/Magic-squares-of-odd-order | 1 + Lang/Go/Make-directory-path | 1 + Lang/Go/Maximum-triangle-path-sum | 1 + Lang/Go/Move-to-front-algorithm | 1 + Lang/Go/Munching-squares | 1 + Lang/Go/Narcissistic-decimal-number | 1 + Lang/Go/Natural-sorting | 1 + Lang/Go/Nth | 1 + Lang/Go/Odd-word-problem | 1 + Lang/Go/Order-disjoint-list-items | 1 + Lang/Go/Paraffins | 1 + Lang/Go/Parse-an-IP-Address | 1 + Lang/Go/Percolation-Bond-percolation | 1 + Lang/Go/Percolation-Site-percolation | 1 + Lang/Go/Permutations-Rank-of-a-permutation | 1 + Lang/Go/Pernicious-numbers | 1 + Lang/Go/Phrase-reversals | 1 + Lang/Go/Quickselect-algorithm | 1 + Lang/Go/RSA-code | 1 + Lang/Go/Ranking-methods | 1 + Lang/Go/Rep-string | 1 + Lang/Go/Reverse-words-in-a-string | 1 + Lang/Go/Runge-Kutta-method | 1 + Lang/Go/Semiprime | 1 + Lang/Go/Sequence-of-primes-by-Trial-Division | 1 + Lang/Go/Solve-the-no-connection-puzzle | 1 + Lang/Go/Sparkline-in-unicode | 1 + Lang/Go/State-name-puzzle | 1 + Lang/Go/Statistics-Basic | 1 + Lang/Go/Stern-Brocot-sequence | 1 + Lang/Go/String-append | 1 + Lang/Go/String-matching | 1 + Lang/Go/String-prepend | 1 + Lang/Go/Sum-multiples-of-3-and-5 | 1 + Lang/Go/Textonyms | 1 + Lang/Go/The-ISAAC-Cipher | 1 + Lang/Go/The-Twelve-Days-of-Christmas | 1 + Lang/Go/Total-circles-area | 1 + Lang/Go/Unix-ls | 1 + Lang/Go/Zero-to-the-zero-power | 1 + Lang/Go/Zhang-Suen-thinning-algorithm | 1 + Lang/Groovy/ABC-Problem | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Groovy/CSV-data-manipulation | 1 + Lang/Groovy/Closures-Value-capture | 1 + Lang/Groovy/Comma-quibbling | 1 + Lang/Groovy/Currying | 1 + Lang/Groovy/File-input-output | 1 + .../Groovy/Find-the-last-Sunday-of-each-month | 1 + .../Groovy/Generate-lower-case-ASCII-alphabet | 1 + Lang/Groovy/Hash-join | 1 + Lang/Groovy/IBAN | 1 + Lang/Groovy/Phrase-reversals | 1 + Lang/Groovy/Reverse-words-in-a-string | 1 + Lang/Groovy/Sparkline-in-unicode | 1 + Lang/Groovy/String-matching | 1 + Lang/Groovy/Sum-multiples-of-3-and-5 | 1 + Lang/Groovy/The-Twelve-Days-of-Christmas | 1 + Lang/Groovy/Zero-to-the-zero-power | 1 + Lang/Groovy/Zhang-Suen-thinning-algorithm | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/Haskell/ABC-Problem | 1 + Lang/Haskell/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Haskell/Aliquot-sequence-classifications | 1 + Lang/Haskell/Almost-prime | 1 + Lang/Haskell/Amb | 1 + Lang/Haskell/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Haskell/Benfords-law | 1 + Lang/Haskell/Bernoulli-numbers | 1 + Lang/Haskell/CSV-data-manipulation | 1 + Lang/Haskell/Catamorphism | 1 + Lang/Haskell/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Haskell/Closures-Value-capture | 1 + Lang/Haskell/Comma-quibbling | 1 + .../Convert-decimal-number-to-rational | 1 + Lang/Haskell/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Haskell/Draw-a-clock | 1 + Lang/Haskell/Extensible-prime-generator | 1 + Lang/Haskell/Fibonacci-word | 1 + Lang/Haskell/File-input-output | 1 + Lang/Haskell/Flipping-bits-game | 1 + Lang/Haskell/Fractran | 1 + .../Generate-Chess960-starting-position | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Haskell/Hash-join | 1 + Lang/Haskell/Hello-world-Newbie | 1 + Lang/Haskell/Heronian-triangles | 1 + Lang/Haskell/IBAN | 1 + Lang/Haskell/Integer-overflow | 1 + Lang/Haskell/Iterated-digits-squaring | 1 + Lang/Haskell/K-d-tree | 1 + Lang/Haskell/Left-factorials | 1 + Lang/Haskell/Longest-increasing-subsequence | 1 + Lang/Haskell/Ludic-numbers | 1 + Lang/Haskell/Magic-squares-of-odd-order | 1 + Lang/Haskell/Maximum-triangle-path-sum | 1 + Lang/Haskell/Move-to-front-algorithm | 1 + Lang/Haskell/Munching-squares | 1 + Lang/Haskell/Narcissistic-decimal-number | 1 + Lang/Haskell/Nth | 1 + Lang/Haskell/Odd-word-problem | 1 + Lang/Haskell/Old-lady-swallowed-a-fly | 1 + Lang/Haskell/Paraffins | 1 + Lang/Haskell/Penneys-game | 1 + Lang/Haskell/Percolation-Mean-run-density | 1 + .../Permutations-Rank-of-a-permutation | 1 + Lang/Haskell/Pernicious-numbers | 1 + Lang/Haskell/Phrase-reversals | 1 + Lang/Haskell/Quickselect-algorithm | 1 + Lang/Haskell/Ranking-methods | 1 + Lang/Haskell/Rep-string | 1 + Lang/Haskell/Reverse-words-in-a-string | 1 + Lang/Haskell/Runge-Kutta-method | 1 + Lang/Haskell/Semiprime | 1 + .../Sequence-of-primes-by-Trial-Division | 1 + Lang/Haskell/Solve-a-Holy-Knights-tour | 1 + Lang/Haskell/Sparkline-in-unicode | 1 + Lang/Haskell/Stern-Brocot-sequence | 1 + Lang/Haskell/String-append | 1 + Lang/Haskell/String-matching | 1 + Lang/Haskell/String-prepend | 1 + Lang/Haskell/Sum-multiples-of-3-and-5 | 1 + Lang/Haskell/The-ISAAC-Cipher | 1 + Lang/Haskell/Total-circles-area | 1 + Lang/Haskell/Unix-ls | 1 + Lang/Haskell/Zero-to-the-zero-power | 1 + Lang/Haskell/Zhang-Suen-thinning-algorithm | 1 + Lang/Haxe/Amb | 1 + Lang/Haxe/The-ISAAC-Cipher | 1 + Lang/HicEst/File-input-output | 1 + Lang/IDL/File-input-output | 1 + Lang/Icon/ABC-Problem | 1 + Lang/Icon/Almost-prime | 1 + Lang/Icon/Amb | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Icon/Benfords-law | 1 + Lang/Icon/Bernoulli-numbers | 1 + Lang/Icon/CSV-data-manipulation | 1 + Lang/Icon/Calendar---for-REAL-programmers | 1 + Lang/Icon/Catalan-numbers-Pascals-triangle | 1 + Lang/Icon/Catamorphism | 1 + Lang/Icon/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Icon/Closures-Value-capture | 1 + Lang/Icon/Combinations-and-permutations | 1 + Lang/Icon/Comma-quibbling | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Icon/Fibonacci-word | 1 + Lang/Icon/Fibonacci-word-fractal | 1 + Lang/Icon/File-input-output | 1 + Lang/Icon/Find-the-last-Sunday-of-each-month | 1 + Lang/Icon/Fractran | 1 + Lang/Icon/Generate-lower-case-ASCII-alphabet | 1 + Lang/Icon/Left-factorials | 1 + Lang/Icon/Longest-increasing-subsequence | 1 + Lang/Icon/Ludic-numbers | 1 + Lang/Icon/Move-to-front-algorithm | 1 + Lang/Icon/Munching-squares | 1 + Lang/Icon/Narcissistic-decimal-number | 1 + Lang/Icon/Nth | 1 + Lang/Icon/Odd-word-problem | 1 + Lang/Icon/Old-lady-swallowed-a-fly | 1 + Lang/Icon/Order-disjoint-list-items | 1 + Lang/Icon/Parse-an-IP-Address | 1 + Lang/Icon/Percolation-Mean-run-density | 1 + Lang/Icon/Pernicious-numbers | 1 + Lang/Icon/Quickselect-algorithm | 1 + Lang/Icon/RSA-code | 1 + Lang/Icon/Rep-string | 1 + Lang/Icon/Reverse-words-in-a-string | 1 + Lang/Icon/Semiprime | 1 + Lang/Icon/State-name-puzzle | 1 + Lang/Icon/Statistics-Basic | 1 + Lang/Icon/String-append | 1 + Lang/Icon/String-prepend | 1 + Lang/Icon/Sum-multiples-of-3-and-5 | 1 + Lang/Icon/The-Twelve-Days-of-Christmas | 1 + Lang/Icon/Zero-to-the-zero-power | 1 + Lang/Io/Currying | 1 + Lang/Io/File-input-output | 1 + Lang/J/9-billion-names-of-God-the-integer | 1 + Lang/J/ABC-Problem | 1 + Lang/J/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/J/Aliquot-sequence-classifications | 1 + Lang/J/Almost-prime | 1 + Lang/J/Amb | 1 + Lang/J/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/J/Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/J/Benfords-law | 1 + Lang/J/Bernoulli-numbers | 1 + Lang/J/CSV-data-manipulation | 1 + Lang/J/Calendar---for-REAL-programmers | 1 + Lang/J/Casting-out-nines | 1 + Lang/J/Catalan-numbers-Pascals-triangle | 1 + Lang/J/Catamorphism | 1 + Lang/J/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/J/Closures-Value-capture | 1 + Lang/J/Combinations-and-permutations | 1 + Lang/J/Comma-quibbling | 1 + Lang/J/Conjugate-transpose | 1 + Lang/J/Convert-decimal-number-to-rational | 1 + Lang/J/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/J/Draw-a-clock | 1 + Lang/J/Extensible-prime-generator | 1 + Lang/J/Fibonacci-word | 1 + Lang/J/Fibonacci-word-fractal | 1 + Lang/J/File-input-output | 1 + Lang/J/Find-the-last-Sunday-of-each-month | 1 + Lang/J/Flipping-bits-game | 1 + Lang/J/Fractran | 1 + Lang/J/Gaussian-elimination | 1 + Lang/J/Generate-Chess960-starting-position | 1 + Lang/J/Generate-lower-case-ASCII-alphabet | 1 + Lang/J/Hash-join | 1 + Lang/J/Hello-world-Newbie | 1 + Lang/J/Heronian-triangles | 1 + Lang/J/Hickerson-series-of-almost-integers | 1 + Lang/J/IBAN | 1 + Lang/J/Integer-overflow | 1 + Lang/J/Iterated-digits-squaring | 1 + Lang/J/K-d-tree | 1 + Lang/J/Left-factorials | 1 + Lang/J/Longest-increasing-subsequence | 1 + Lang/J/Ludic-numbers | 1 + Lang/J/Magic-squares-of-odd-order | 1 + Lang/J/Maximum-triangle-path-sum | 1 + Lang/J/Move-to-front-algorithm | 1 + Lang/J/Munching-squares | 1 + Lang/J/Narcissistic-decimal-number | 1 + Lang/J/Natural-sorting | 1 + Lang/J/Nth | 1 + Lang/J/Odd-word-problem | 1 + Lang/J/Old-lady-swallowed-a-fly | 1 + Lang/J/Order-disjoint-list-items | 1 + Lang/J/Paraffins | 1 + Lang/J/Parse-an-IP-Address | 1 + Lang/J/Penneys-game | 1 + Lang/J/Percolation-Mean-cluster-density | 1 + Lang/J/Percolation-Mean-run-density | 1 + Lang/J/Percolation-Site-percolation | 1 + Lang/J/Permutations-Rank-of-a-permutation | 1 + Lang/J/Pernicious-numbers | 1 + Lang/J/Phrase-reversals | 1 + Lang/J/Quickselect-algorithm | 1 + Lang/J/RSA-code | 1 + Lang/J/Ranking-methods | 1 + Lang/J/Rep-string | 1 + Lang/J/Reverse-words-in-a-string | 1 + Lang/J/Runge-Kutta-method | 1 + Lang/J/Semiprime | 1 + Lang/J/Sequence-of-primes-by-Trial-Division | 1 + Lang/J/Solve-a-Holy-Knights-tour | 1 + Lang/J/Solve-the-no-connection-puzzle | 1 + Lang/J/Sparkline-in-unicode | 1 + Lang/J/State-name-puzzle | 1 + Lang/J/Statistics-Basic | 1 + Lang/J/Stern-Brocot-sequence | 1 + Lang/J/String-append | 1 + Lang/J/String-matching | 1 + Lang/J/String-prepend | 1 + Lang/J/Sum-multiples-of-3-and-5 | 1 + Lang/J/Textonyms | 1 + Lang/J/The-Twelve-Days-of-Christmas | 1 + Lang/J/Total-circles-area | 1 + Lang/J/Ulam-spiral--for-primes- | 1 + Lang/J/Unix-ls | 1 + Lang/J/World-Cup-group-stage | 1 + Lang/J/Zero-to-the-zero-power | 1 + Lang/J/Zhang-Suen-thinning-algorithm | 1 + Lang/Java/ABC-Problem | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Java/Benfords-law | 1 + Lang/Java/CSV-data-manipulation | 1 + Lang/Java/Catamorphism | 1 + Lang/Java/Closures-Value-capture | 1 + Lang/Java/Comma-quibbling | 1 + Lang/Java/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Java/Draw-a-clock | 1 + Lang/Java/Fibonacci-word | 1 + Lang/Java/File-input-output | 1 + Lang/Java/Find-the-last-Sunday-of-each-month | 1 + Lang/Java/Fractran | 1 + Lang/Java/Generate-Chess960-starting-position | 1 + Lang/Java/Generate-lower-case-ASCII-alphabet | 1 + Lang/Java/Heronian-triangles | 1 + Lang/Java/IBAN | 1 + Lang/Java/Integer-overflow | 1 + Lang/Java/Iterated-digits-squaring | 1 + Lang/Java/Left-factorials | 1 + Lang/Java/Longest-increasing-subsequence | 1 + Lang/Java/Ludic-numbers | 1 + Lang/Java/Magic-squares-of-odd-order | 1 + Lang/Java/Make-directory-path | 1 + Lang/Java/Maximum-triangle-path-sum | 1 + Lang/Java/Move-to-front-algorithm | 1 + Lang/Java/Munching-squares | 1 + Lang/Java/Narcissistic-decimal-number | 1 + Lang/Java/Nth | 1 + Lang/Java/Odd-word-problem | 1 + Lang/Java/Old-lady-swallowed-a-fly | 1 + Lang/Java/Order-disjoint-list-items | 1 + Lang/Java/Parse-an-IP-Address | 1 + Lang/Java/Penneys-game | 1 + Lang/Java/Permutations-Rank-of-a-permutation | 1 + Lang/Java/Pernicious-numbers | 1 + Lang/Java/Phrase-reversals | 1 + Lang/Java/Quickselect-algorithm | 1 + Lang/Java/Ranking-methods | 1 + Lang/Java/Rep-string | 1 + Lang/Java/Reverse-words-in-a-string | 1 + Lang/Java/Semiprime | 1 + Lang/Java/Sparkline-in-unicode | 1 + Lang/Java/State-name-puzzle | 1 + Lang/Java/Stern-Brocot-sequence | 1 + Lang/Java/String-append | 1 + Lang/Java/String-matching | 1 + Lang/Java/String-prepend | 1 + Lang/Java/Sum-multiples-of-3-and-5 | 1 + Lang/Java/The-ISAAC-Cipher | 1 + Lang/Java/The-Twelve-Days-of-Christmas | 1 + Lang/Java/Ulam-spiral--for-primes- | 1 + Lang/Java/Vogels-approximation-method | 1 + Lang/Java/World-Cup-group-stage | 1 + Lang/Java/Zero-to-the-zero-power | 1 + Lang/Java/Zhang-Suen-thinning-algorithm | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/JavaScript/ABC-Problem | 1 + Lang/JavaScript/AKS-test-for-primes | 1 + Lang/JavaScript/Amb | 1 + Lang/JavaScript/Catamorphism | 1 + Lang/JavaScript/Closures-Value-capture | 1 + Lang/JavaScript/Comma-quibbling | 1 + Lang/JavaScript/Currying | 1 + Lang/JavaScript/Draw-a-clock | 1 + Lang/JavaScript/File-input-output | 1 + Lang/JavaScript/Fractran | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/JavaScript/Heronian-triangles | 1 + .../JavaScript/Longest-increasing-subsequence | 1 + Lang/JavaScript/Make-directory-path | 1 + Lang/JavaScript/Move-to-front-algorithm | 1 + Lang/JavaScript/Runge-Kutta-method | 1 + Lang/JavaScript/String-append | 1 + Lang/JavaScript/String-matching | 1 + Lang/JavaScript/The-Twelve-Days-of-Christmas | 1 + Lang/JavaScript/Zero-to-the-zero-power | 1 + Lang/Julia/ABC-Problem | 1 + Lang/Julia/Almost-prime | 1 + Lang/Julia/Benfords-law | 1 + Lang/Julia/Casting-out-nines | 1 + Lang/Julia/Closures-Value-capture | 1 + Lang/Julia/Comma-quibbling | 1 + Lang/Julia/Conjugate-transpose | 1 + Lang/Julia/Convert-decimal-number-to-rational | 1 + Lang/Julia/File-input-output | 1 + Lang/Julia/Gaussian-elimination | 1 + Lang/Julia/Generate-lower-case-ASCII-alphabet | 1 + Lang/Julia/Iterated-digits-squaring | 1 + Lang/Julia/Left-factorials | 1 + Lang/Julia/Reverse-words-in-a-string | 1 + Lang/Julia/Runge-Kutta-method | 1 + Lang/Julia/Semiprime | 1 + Lang/Julia/String-append | 1 + Lang/Julia/String-matching | 1 + Lang/Julia/String-prepend | 1 + Lang/Julia/Sum-multiples-of-3-and-5 | 1 + Lang/Julia/Total-circles-area | 1 + Lang/K/File-input-output | 1 + Lang/K/String-matching | 1 + Lang/LOLCODE/Catamorphism | 1 + Lang/LOLCODE/The-Twelve-Days-of-Christmas | 1 + Lang/Lang5/File-input-output | 1 + Lang/Lang5/String-matching | 1 + Lang/Liberty-BASIC/Benfords-law | 1 + .../Convert-decimal-number-to-rational | 1 + Lang/Liberty-BASIC/Draw-a-clock | 1 + Lang/Liberty-BASIC/File-input-output | 1 + Lang/Liberty-BASIC/Munching-squares | 1 + Lang/Liberty-BASIC/Statistics-Basic | 1 + Lang/Liberty-BASIC/String-matching | 1 + Lang/Limbo/Sum-multiples-of-3-and-5 | 1 + Lang/Lisaac/File-input-output | 1 + Lang/Locomotive-Basic/Draw-a-clock | 1 + Lang/Locomotive-Basic/Hello-world-Newbie | 1 + Lang/Logo/ABC-Problem | 1 + Lang/Logo/Comma-quibbling | 1 + Lang/Logo/Fibonacci-word-fractal | 1 + Lang/Logo/File-input-output | 1 + Lang/Logo/Generate-lower-case-ASCII-alphabet | 1 + Lang/Logo/String-matching | 1 + Lang/Logo/The-Twelve-Days-of-Christmas | 1 + Lang/Logtalk/Catamorphism | 1 + Lang/Logtalk/Closures-Value-capture | 1 + Lang/Lua/Amb | 1 + Lang/Lua/Benfords-law | 1 + Lang/Lua/CSV-data-manipulation | 1 + Lang/Lua/Closures-Value-capture | 1 + Lang/Lua/File-input-output | 1 + Lang/Lua/Iterated-digits-squaring | 1 + Lang/Lua/Longest-increasing-subsequence | 1 + Lang/Lua/Reverse-words-in-a-string | 1 + Lang/Lua/String-matching | 1 + Lang/Lua/String-prepend | 1 + Lang/Lua/The-Twelve-Days-of-Christmas | 1 + Lang/MATLAB/ABC-Problem | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/MATLAB/CSV-data-manipulation | 1 + Lang/MATLAB/Catalan-numbers-Pascals-triangle | 1 + .../MATLAB/Convert-decimal-number-to-rational | 1 + Lang/MATLAB/Draw-a-clock | 1 + Lang/MATLAB/Flipping-bits-game | 1 + Lang/MATLAB/Gaussian-elimination | 1 + Lang/MATLAB/IBAN | 1 + Lang/MATLAB/Move-to-front-algorithm | 1 + Lang/MATLAB/Munching-squares | 1 + Lang/MATLAB/Narcissistic-decimal-number | 1 + Lang/MATLAB/Nth | 1 + Lang/MATLAB/Reverse-words-in-a-string | 1 + Lang/MATLAB/Runge-Kutta-method | 1 + Lang/MATLAB/Statistics-Basic | 1 + Lang/MATLAB/String-matching | 1 + Lang/MATLAB/Sum-multiples-of-3-and-5 | 1 + Lang/MATLAB/Total-circles-area | 1 + Lang/MAXScript/ABC-Problem | 1 + Lang/MAXScript/Comma-quibbling | 1 + Lang/MAXScript/File-input-output | 1 + Lang/Maple/AKS-test-for-primes | 1 + Lang/Maple/Bernoulli-numbers | 1 + Lang/Maple/CSV-data-manipulation | 1 + Lang/Maple/Catamorphism | 1 + Lang/Maple/Chinese-remainder-theorem | 1 + Lang/Maple/Closures-Value-capture | 1 + Lang/Maple/Comma-quibbling | 1 + Lang/Maple/Conjugate-transpose | 1 + Lang/Maple/Convert-decimal-number-to-rational | 1 + Lang/Maple/Rep-string | 1 + Lang/Maple/String-matching | 1 + Lang/Maple/Sum-multiples-of-3-and-5 | 1 + Lang/Maple/Zero-to-the-zero-power | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/Mathematica/ABC-Problem | 1 + Lang/Mathematica/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Mathematica/Almost-prime | 1 + Lang/Mathematica/Amb | 1 + Lang/Mathematica/Amicable-pairs | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Mathematica/Benfords-law | 1 + Lang/Mathematica/Bernoulli-numbers | 1 + Lang/Mathematica/CSV-data-manipulation | 1 + .../Catalan-numbers-Pascals-triangle | 1 + Lang/Mathematica/Catamorphism | 1 + Lang/Mathematica/Chinese-remainder-theorem | 1 + Lang/Mathematica/Closures-Value-capture | 1 + .../Mathematica/Combinations-and-permutations | 1 + Lang/Mathematica/Comma-quibbling | 1 + Lang/Mathematica/Conjugate-transpose | 1 + .../Convert-decimal-number-to-rational | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Mathematica/Draw-a-clock | 1 + Lang/Mathematica/Extensible-prime-generator | 1 + Lang/Mathematica/Fibonacci-word | 1 + Lang/Mathematica/Fibonacci-word-fractal | 1 + Lang/Mathematica/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + Lang/Mathematica/Fractran | 1 + Lang/Mathematica/Gaussian-elimination | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Mathematica/Hash-join | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Mathematica/IBAN | 1 + Lang/Mathematica/Iterated-digits-squaring | 1 + Lang/Mathematica/Left-factorials | 1 + .../Longest-increasing-subsequence | 1 + Lang/Mathematica/Ludic-numbers | 1 + Lang/Mathematica/Magic-squares-of-odd-order | 1 + Lang/Mathematica/Make-directory-path | 1 + Lang/Mathematica/Maximum-triangle-path-sum | 1 + Lang/Mathematica/Move-to-front-algorithm | 1 + Lang/Mathematica/Munching-squares | 1 + Lang/Mathematica/Nth | 1 + Lang/Mathematica/Paraffins | 1 + .../Permutations-Rank-of-a-permutation | 1 + Lang/Mathematica/Pernicious-numbers | 1 + Lang/Mathematica/Phrase-reversals | 1 + Lang/Mathematica/Rep-string | 1 + Lang/Mathematica/Reverse-words-in-a-string | 1 + Lang/Mathematica/Runge-Kutta-method | 1 + Lang/Mathematica/Semiprime | 1 + Lang/Mathematica/Sparkline-in-unicode | 1 + Lang/Mathematica/State-name-puzzle | 1 + Lang/Mathematica/Statistics-Basic | 1 + Lang/Mathematica/String-append | 1 + Lang/Mathematica/String-matching | 1 + Lang/Mathematica/String-prepend | 1 + Lang/Mathematica/Sum-multiples-of-3-and-5 | 1 + Lang/Mathematica/The-Twelve-Days-of-Christmas | 1 + Lang/Mathematica/Total-circles-area | 1 + Lang/Mathematica/Unix-ls | 1 + Lang/Mathematica/Zero-to-the-zero-power | 1 + .../Mathematica/Zhang-Suen-thinning-algorithm | 1 + Lang/Maxima/Catamorphism | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Maxima/Magic-squares-of-odd-order | 1 + Lang/Maxima/Runge-Kutta-method | 1 + Lang/Maxima/Sum-multiples-of-3-and-5 | 1 + Lang/Mercury/Amb | 1 + Lang/Mercury/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Mercury/String-prepend | 1 + Lang/Modula-3/File-input-output | 1 + Lang/Nemerle/Catamorphism | 1 + Lang/Nemerle/Closures-Value-capture | 1 + Lang/Nemerle/Currying | 1 + Lang/NetRexx/Amb | 1 + Lang/NetRexx/Benfords-law | 1 + Lang/NetRexx/CSV-data-manipulation | 1 + Lang/NetRexx/Comma-quibbling | 1 + .../Convert-decimal-number-to-rational | 1 + Lang/NetRexx/Draw-a-clock | 1 + Lang/NetRexx/File-input-output | 1 + Lang/NetRexx/Quickselect-algorithm | 1 + Lang/NetRexx/Rep-string | 1 + Lang/NetRexx/Sparkline-in-unicode | 1 + Lang/NetRexx/String-append | 1 + Lang/NetRexx/String-matching | 1 + Lang/NetRexx/String-prepend | 1 + Lang/NetRexx/Sum-multiples-of-3-and-5 | 1 + Lang/NetRexx/Zero-to-the-zero-power | 1 + Lang/NewLISP/String-append | 1 + Lang/NewLISP/String-matching | 1 + Lang/NewLISP/String-prepend | 1 + Lang/OCaml/9-billion-names-of-God-the-integer | 1 + Lang/OCaml/ABC-Problem | 1 + Lang/OCaml/Amb | 1 + Lang/OCaml/Catamorphism | 1 + Lang/OCaml/Chinese-remainder-theorem | 1 + Lang/OCaml/Closures-Value-capture | 1 + Lang/OCaml/Currying | 1 + Lang/OCaml/Draw-a-clock | 1 + Lang/OCaml/File-input-output | 1 + Lang/OCaml/Find-the-last-Sunday-of-each-month | 1 + Lang/OCaml/Gaussian-elimination | 1 + Lang/OCaml/Hash-join | 1 + Lang/OCaml/Hello-world-Newbie | 1 + Lang/OCaml/Longest-increasing-subsequence | 1 + Lang/OCaml/Munching-squares | 1 + Lang/OCaml/Odd-word-problem | 1 + Lang/OCaml/Old-lady-swallowed-a-fly | 1 + Lang/OCaml/Quickselect-algorithm | 1 + Lang/OCaml/Reverse-words-in-a-string | 1 + Lang/OCaml/Runge-Kutta-method | 1 + Lang/OCaml/String-append | 1 + Lang/OCaml/String-matching | 1 + Lang/OCaml/Unix-ls | 1 + Lang/Oberon-2/ABC-Problem | 1 + Lang/Oberon-2/Catamorphism | 1 + Lang/Oberon-2/Hash-join | 1 + Lang/Oberon-2/IBAN | 1 + Lang/Oberon-2/Iterated-digits-squaring | 1 + Lang/Objeck/Almost-prime | 1 + Lang/Objeck/Casting-out-nines | 1 + Lang/Objeck/File-input-output | 1 + .../Generate-Chess960-starting-position | 1 + Lang/Objeck/Reverse-words-in-a-string | 1 + Lang/Objeck/Semiprime | 1 + Lang/Objeck/String-append | 1 + Lang/Objeck/String-matching | 1 + Lang/Objeck/The-Twelve-Days-of-Christmas | 1 + Lang/Object-Pascal/File-input-output | 1 + Lang/Objective-C/Closures-Value-capture | 1 + Lang/Objective-C/File-input-output | 1 + .../Longest-increasing-subsequence | 1 + Lang/Objective-C/String-matching | 1 + Lang/Octave/File-input-output | 1 + Lang/Octave/Munching-squares | 1 + Lang/Octave/Runge-Kutta-method | 1 + Lang/OpenEdge-Progress/Amb | 1 + Lang/OpenEdge-Progress/File-input-output | 1 + Lang/OxygenBasic/String-matching | 1 + Lang/Oz/Amb | 1 + Lang/Oz/File-input-output | 1 + Lang/PARI-GP/AKS-test-for-primes | 1 + Lang/PARI-GP/Almost-prime | 1 + Lang/PARI-GP/Amb | 1 + Lang/PARI-GP/Amicable-pairs | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/PARI-GP/Benfords-law | 1 + Lang/PARI-GP/Bernoulli-numbers | 1 + Lang/PARI-GP/Casting-out-nines | 1 + Lang/PARI-GP/Catalan-numbers-Pascals-triangle | 1 + Lang/PARI-GP/Catamorphism | 1 + Lang/PARI-GP/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/PARI-GP/Closures-Value-capture | 1 + Lang/PARI-GP/Comma-quibbling | 1 + Lang/PARI-GP/Conjugate-transpose | 1 + .../Convert-decimal-number-to-rational | 1 + Lang/PARI-GP/Currying | 1 + Lang/PARI-GP/Fibonacci-word | 1 + Lang/PARI-GP/File-input-output | 1 + Lang/PARI-GP/Gaussian-elimination | 1 + Lang/PARI-GP/Hello-world-Newbie | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/PARI-GP/Left-factorials | 1 + Lang/PARI-GP/Machine-code | 1 + Lang/PARI-GP/Maximum-triangle-path-sum | 1 + Lang/PARI-GP/Nth | 1 + .../Permutations-Rank-of-a-permutation | 1 + Lang/PARI-GP/Pernicious-numbers | 1 + Lang/PARI-GP/Quickselect-algorithm | 1 + Lang/PARI-GP/Rep-string | 1 + Lang/PARI-GP/Runge-Kutta-method | 1 + Lang/PARI-GP/Semiprime | 1 + Lang/PARI-GP/Statistics-Basic | 1 + Lang/PARI-GP/String-append | 1 + Lang/PARI-GP/String-matching | 1 + Lang/PARI-GP/String-prepend | 1 + Lang/PARI-GP/Sum-multiples-of-3-and-5 | 1 + Lang/PARI-GP/Unix-ls | 1 + Lang/PARI-GP/Zero-to-the-zero-power | 1 + Lang/PHP/ABC-Problem | 1 + Lang/PHP/CSV-data-manipulation | 1 + Lang/PHP/Calendar---for-REAL-programmers | 1 + Lang/PHP/Closures-Value-capture | 1 + Lang/PHP/Comma-quibbling | 1 + Lang/PHP/File-input-output | 1 + Lang/PHP/Gaussian-elimination | 1 + Lang/PHP/Generate-lower-case-ASCII-alphabet | 1 + Lang/PHP/Hash-join | 1 + Lang/PHP/Longest-increasing-subsequence | 1 + Lang/PHP/Munching-squares | 1 + Lang/PHP/Nth | 1 + Lang/PHP/Odd-word-problem | 1 + Lang/PHP/Old-lady-swallowed-a-fly | 1 + Lang/PHP/Phrase-reversals | 1 + Lang/PHP/String-matching | 1 + Lang/PHP/The-Twelve-Days-of-Christmas | 1 + Lang/PHP/Zero-to-the-zero-power | 1 + Lang/PL-I/ABC-Problem | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/PL-I/Amb | 1 + Lang/PL-I/Amicable-pairs | 1 + Lang/PL-I/Benfords-law | 1 + Lang/PL-I/Bernoulli-numbers | 1 + Lang/PL-I/CSV-data-manipulation | 1 + Lang/PL-I/Calendar---for-REAL-programmers | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/PL-I/Comma-quibbling | 1 + Lang/PL-I/Conjugate-transpose | 1 + Lang/PL-I/Convert-decimal-number-to-rational | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/PL-I/Fibonacci-word | 1 + Lang/PL-I/File-input-output | 1 + Lang/PL-I/Flipping-bits-game | 1 + Lang/PL-I/Gaussian-elimination | 1 + Lang/PL-I/Generate-lower-case-ASCII-alphabet | 1 + Lang/PL-I/Hickerson-series-of-almost-integers | 1 + Lang/PL-I/Left-factorials | 1 + Lang/PL-I/Ludic-numbers | 1 + Lang/PL-I/Magic-squares-of-odd-order | 1 + Lang/PL-I/Move-to-front-algorithm | 1 + Lang/PL-I/Munching-squares | 1 + Lang/PL-I/Nth | 1 + Lang/PL-I/Odd-word-problem | 1 + Lang/PL-I/Quickselect-algorithm | 1 + Lang/PL-I/Rep-string | 1 + Lang/PL-I/Reverse-words-in-a-string | 1 + Lang/PL-I/Runge-Kutta-method | 1 + Lang/PL-I/Semiprime | 1 + Lang/PL-I/Statistics-Basic | 1 + Lang/PL-I/String-append | 1 + Lang/PL-I/String-matching | 1 + Lang/PL-I/String-prepend | 1 + Lang/PL-I/Sum-multiples-of-3-and-5 | 1 + Lang/PL-I/Zero-to-the-zero-power | 1 + Lang/PL-I/Zhang-Suen-thinning-algorithm | 1 + Lang/PL-pgSQL/Benfords-law | 1 + Lang/Pascal/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Pascal/Almost-prime | 1 + Lang/Pascal/Amicable-pairs | 1 + Lang/Pascal/Catalan-numbers-Pascals-triangle | 1 + Lang/Pascal/Catamorphism | 1 + Lang/Pascal/Extensible-prime-generator | 1 + Lang/Pascal/Fibonacci-word | 1 + Lang/Pascal/Iterated-digits-squaring | 1 + Lang/Pascal/Machine-code | 1 + Lang/Pascal/Maximum-triangle-path-sum | 1 + Lang/Pascal/Narcissistic-decimal-number | 1 + Lang/Pascal/Paraffins | 1 + Lang/Pascal/Pernicious-numbers | 1 + Lang/Pascal/Runge-Kutta-method | 1 + Lang/Pascal/Semiprime | 1 + Lang/Pascal/String-append | 1 + Lang/Pascal/String-prepend | 1 + Lang/Pascal/Sum-multiples-of-3-and-5 | 1 + Lang/Pascal/The-ISAAC-Cipher | 1 + .../Perl-6/9-billion-names-of-God-the-integer | 1 + Lang/Perl-6/ABC-Problem | 1 + Lang/Perl-6/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Perl-6/Aliquot-sequence-classifications | 1 + Lang/Perl-6/Almost-prime | 1 + Lang/Perl-6/Amb | 1 + Lang/Perl-6/Amicable-pairs | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Perl-6/Benfords-law | 1 + Lang/Perl-6/Bernoulli-numbers | 1 + Lang/Perl-6/Bitcoin-public-point-to-address | 1 + Lang/Perl-6/CSV-data-manipulation | 1 + Lang/Perl-6/Calendar---for-REAL-programmers | 1 + Lang/Perl-6/Casting-out-nines | 1 + Lang/Perl-6/Catalan-numbers-Pascals-triangle | 1 + Lang/Perl-6/Catamorphism | 1 + Lang/Perl-6/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Perl-6/Closures-Value-capture | 1 + Lang/Perl-6/Combinations-and-permutations | 1 + Lang/Perl-6/Comma-quibbling | 1 + .../Perl-6/Convert-decimal-number-to-rational | 1 + Lang/Perl-6/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Perl-6/Draw-a-clock | 1 + Lang/Perl-6/Extensible-prime-generator | 1 + Lang/Perl-6/Fibonacci-word | 1 + Lang/Perl-6/Fibonacci-word-fractal | 1 + Lang/Perl-6/File-input-output | 1 + .../Perl-6/Find-the-last-Sunday-of-each-month | 1 + Lang/Perl-6/Flipping-bits-game | 1 + Lang/Perl-6/Fractran | 1 + Lang/Perl-6/Gaussian-elimination | 1 + .../Generate-Chess960-starting-position | 1 + .../Perl-6/Generate-lower-case-ASCII-alphabet | 1 + Lang/Perl-6/Hash-join | 1 + Lang/Perl-6/Heronian-triangles | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Perl-6/IBAN | 1 + Lang/Perl-6/Iterated-digits-squaring | 1 + Lang/Perl-6/K-d-tree | 1 + Lang/Perl-6/Left-factorials | 1 + Lang/Perl-6/Longest-increasing-subsequence | 1 + Lang/Perl-6/Ludic-numbers | 1 + Lang/Perl-6/Magic-squares-of-odd-order | 1 + Lang/Perl-6/Make-directory-path | 1 + Lang/Perl-6/Maximum-triangle-path-sum | 1 + Lang/Perl-6/Move-to-front-algorithm | 1 + Lang/Perl-6/Munching-squares | 1 + Lang/Perl-6/Narcissistic-decimal-number | 1 + Lang/Perl-6/Natural-sorting | 1 + Lang/Perl-6/Nth | 1 + Lang/Perl-6/Odd-word-problem | 1 + Lang/Perl-6/Old-lady-swallowed-a-fly | 1 + Lang/Perl-6/Order-disjoint-list-items | 1 + Lang/Perl-6/Paraffins | 1 + Lang/Perl-6/Parse-an-IP-Address | 1 + Lang/Perl-6/Penneys-game | 1 + Lang/Perl-6/Percolation-Mean-run-density | 1 + Lang/Perl-6/Pernicious-numbers | 1 + Lang/Perl-6/Phrase-reversals | 1 + Lang/Perl-6/Quickselect-algorithm | 1 + Lang/Perl-6/RSA-code | 1 + Lang/Perl-6/Ranking-methods | 1 + Lang/Perl-6/Rep-string | 1 + Lang/Perl-6/Reverse-words-in-a-string | 1 + Lang/Perl-6/Runge-Kutta-method | 1 + Lang/Perl-6/Semiprime | 1 + .../Sequence-of-primes-by-Trial-Division | 1 + Lang/Perl-6/Solve-a-Holy-Knights-tour | 1 + Lang/Perl-6/Solve-a-Hopido-puzzle | 1 + Lang/Perl-6/Solve-a-Numbrix-puzzle | 1 + Lang/Perl-6/Solve-the-no-connection-puzzle | 1 + Lang/Perl-6/Sparkline-in-unicode | 1 + Lang/Perl-6/State-name-puzzle | 1 + Lang/Perl-6/Statistics-Basic | 1 + Lang/Perl-6/Stern-Brocot-sequence | 1 + Lang/Perl-6/String-append | 1 + Lang/Perl-6/String-matching | 1 + Lang/Perl-6/String-prepend | 1 + Lang/Perl-6/Sum-multiples-of-3-and-5 | 1 + Lang/Perl-6/Textonyms | 1 + Lang/Perl-6/The-Twelve-Days-of-Christmas | 1 + Lang/Perl-6/Total-circles-area | 1 + Lang/Perl-6/Ulam-spiral--for-primes- | 1 + Lang/Perl-6/Unix-ls | 1 + Lang/Perl-6/World-Cup-group-stage | 1 + Lang/Perl-6/Zero-to-the-zero-power | 1 + Lang/Perl-6/Zhang-Suen-thinning-algorithm | 1 + Lang/Perl/9-billion-names-of-God-the-integer | 1 + Lang/Perl/ABC-Problem | 1 + Lang/Perl/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Perl/Aliquot-sequence-classifications | 1 + Lang/Perl/Almost-prime | 1 + Lang/Perl/Amb | 1 + Lang/Perl/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Perl/Benfords-law | 1 + Lang/Perl/Bernoulli-numbers | 1 + Lang/Perl/Bitcoin-public-point-to-address | 1 + Lang/Perl/CSV-data-manipulation | 1 + Lang/Perl/Calendar---for-REAL-programmers | 1 + Lang/Perl/Casting-out-nines | 1 + Lang/Perl/Catalan-numbers-Pascals-triangle | 1 + Lang/Perl/Catamorphism | 1 + Lang/Perl/Chinese-remainder-theorem | 1 + Lang/Perl/Closures-Value-capture | 1 + Lang/Perl/Combinations-and-permutations | 1 + Lang/Perl/Comma-quibbling | 1 + Lang/Perl/Convert-decimal-number-to-rational | 1 + Lang/Perl/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Perl/Draw-a-clock | 1 + Lang/Perl/Extensible-prime-generator | 1 + Lang/Perl/Fibonacci-word | 1 + Lang/Perl/Fibonacci-word-fractal | 1 + Lang/Perl/File-input-output | 1 + Lang/Perl/Find-the-last-Sunday-of-each-month | 1 + Lang/Perl/Flipping-bits-game | 1 + Lang/Perl/Fractran | 1 + Lang/Perl/Gaussian-elimination | 1 + Lang/Perl/Generate-Chess960-starting-position | 1 + Lang/Perl/Generate-lower-case-ASCII-alphabet | 1 + Lang/Perl/Hash-join | 1 + Lang/Perl/Hello-world-Newbie | 1 + Lang/Perl/Heronian-triangles | 1 + Lang/Perl/Hickerson-series-of-almost-integers | 1 + Lang/Perl/IBAN | 1 + Lang/Perl/Integer-overflow | 1 + Lang/Perl/Iterated-digits-squaring | 1 + Lang/Perl/Left-factorials | 1 + Lang/Perl/Longest-increasing-subsequence | 1 + Lang/Perl/Ludic-numbers | 1 + Lang/Perl/Maximum-triangle-path-sum | 1 + Lang/Perl/Move-to-front-algorithm | 1 + Lang/Perl/Munching-squares | 1 + Lang/Perl/Narcissistic-decimal-number | 1 + Lang/Perl/Natural-sorting | 1 + Lang/Perl/Nth | 1 + Lang/Perl/Odd-word-problem | 1 + Lang/Perl/Old-lady-swallowed-a-fly | 1 + Lang/Perl/Order-disjoint-list-items | 1 + Lang/Perl/Paraffins | 1 + Lang/Perl/Parse-an-IP-Address | 1 + Lang/Perl/Percolation-Mean-run-density | 1 + Lang/Perl/Pernicious-numbers | 1 + Lang/Perl/Phrase-reversals | 1 + Lang/Perl/Quickselect-algorithm | 1 + Lang/Perl/Rep-string | 1 + Lang/Perl/Reverse-words-in-a-string | 1 + Lang/Perl/Rosetta-Code-Find-bare-lang-tags | 1 + Lang/Perl/Runge-Kutta-method | 1 + Lang/Perl/Semiprime | 1 + Lang/Perl/Sparkline-in-unicode | 1 + Lang/Perl/State-name-puzzle | 1 + Lang/Perl/Statistics-Basic | 1 + Lang/Perl/Stern-Brocot-sequence | 1 + Lang/Perl/String-append | 1 + Lang/Perl/String-matching | 1 + Lang/Perl/String-prepend | 1 + Lang/Perl/Sum-multiples-of-3-and-5 | 1 + Lang/Perl/Textonyms | 1 + Lang/Perl/The-ISAAC-Cipher | 1 + Lang/Perl/The-Twelve-Days-of-Christmas | 1 + Lang/Perl/Ulam-spiral--for-primes- | 1 + Lang/Perl/Zero-to-the-zero-power | 1 + .../9-billion-names-of-God-the-integer | 1 + Lang/PicoLisp/ABC-Problem | 1 + Lang/PicoLisp/AKS-test-for-primes | 1 + Lang/PicoLisp/Almost-prime | 1 + Lang/PicoLisp/Amb | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/PicoLisp/Bernoulli-numbers | 1 + Lang/PicoLisp/CSV-data-manipulation | 1 + Lang/PicoLisp/Calendar---for-REAL-programmers | 1 + Lang/PicoLisp/Casting-out-nines | 1 + .../PicoLisp/Catalan-numbers-Pascals-triangle | 1 + Lang/PicoLisp/Catamorphism | 1 + Lang/PicoLisp/Chinese-remainder-theorem | 1 + Lang/PicoLisp/Closures-Value-capture | 1 + Lang/PicoLisp/Comma-quibbling | 1 + Lang/PicoLisp/Draw-a-clock | 1 + Lang/PicoLisp/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + .../Generate-Chess960-starting-position | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/PicoLisp/IBAN | 1 + Lang/PicoLisp/Ludic-numbers | 1 + Lang/PicoLisp/Narcissistic-decimal-number | 1 + Lang/PicoLisp/Natural-sorting | 1 + Lang/PicoLisp/Nth | 1 + Lang/PicoLisp/Odd-word-problem | 1 + Lang/PicoLisp/Old-lady-swallowed-a-fly | 1 + Lang/PicoLisp/Parse-an-IP-Address | 1 + Lang/PicoLisp/RSA-code | 1 + Lang/PicoLisp/Semiprime | 1 + Lang/PicoLisp/State-name-puzzle | 1 + Lang/PicoLisp/Statistics-Basic | 1 + Lang/PicoLisp/String-append | 1 + Lang/PicoLisp/String-matching | 1 + Lang/PicoLisp/String-prepend | 1 + Lang/PicoLisp/Sum-multiples-of-3-and-5 | 1 + Lang/PicoLisp/The-ISAAC-Cipher | 1 + Lang/PicoLisp/The-Twelve-Days-of-Christmas | 1 + Lang/Pike/Closures-Value-capture | 1 + Lang/Pike/Paraffins | 1 + Lang/Pop11/File-input-output | 1 + Lang/PowerBASIC/ABC-Problem | 1 + Lang/PowerShell/File-input-output | 1 + Lang/PowerShell/Heronian-triangles | 1 + Lang/PowerShell/String-matching | 1 + Lang/PowerShell/Sum-multiples-of-3-and-5 | 1 + Lang/PowerShell/The-Twelve-Days-of-Christmas | 1 + Lang/PowerShell/Zero-to-the-zero-power | 1 + Lang/Prolog/ABC-Problem | 1 + Lang/Prolog/AKS-test-for-primes | 1 + Lang/Prolog/Almost-prime | 1 + Lang/Prolog/Amb | 1 + Lang/Prolog/Benfords-law | 1 + Lang/Prolog/CSV-data-manipulation | 1 + Lang/Prolog/Catamorphism | 1 + Lang/Prolog/Closures-Value-capture | 1 + Lang/Prolog/Comma-quibbling | 1 + .../Prolog/Generate-lower-case-ASCII-alphabet | 1 + Lang/Prolog/Longest-increasing-subsequence | 1 + Lang/Prolog/Maximum-triangle-path-sum | 1 + Lang/Prolog/Munching-squares | 1 + Lang/Prolog/Nth | 1 + Lang/Prolog/Odd-word-problem | 1 + Lang/Prolog/Rep-string | 1 + Lang/Prolog/Solve-the-no-connection-puzzle | 1 + Lang/Prolog/State-name-puzzle | 1 + Lang/Prolog/String-prepend | 1 + Lang/Prolog/Sum-multiples-of-3-and-5 | 1 + Lang/PureBasic/Amb | 1 + Lang/PureBasic/Draw-a-clock | 1 + Lang/PureBasic/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/PureBasic/Machine-code | 1 + Lang/PureBasic/Munching-squares | 1 + Lang/PureBasic/Odd-word-problem | 1 + Lang/PureBasic/Statistics-Basic | 1 + Lang/PureBasic/String-append | 1 + Lang/PureBasic/String-matching | 1 + Lang/PureBasic/String-prepend | 1 + .../Python/9-billion-names-of-God-the-integer | 1 + Lang/Python/ABC-Problem | 1 + Lang/Python/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Python/Aliquot-sequence-classifications | 1 + Lang/Python/Almost-prime | 1 + Lang/Python/Amb | 1 + Lang/Python/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Python/Benfords-law | 1 + Lang/Python/Bernoulli-numbers | 1 + Lang/Python/CSV-data-manipulation | 1 + Lang/Python/Casting-out-nines | 1 + Lang/Python/Catalan-numbers-Pascals-triangle | 1 + Lang/Python/Catamorphism | 1 + Lang/Python/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Python/Closures-Value-capture | 1 + Lang/Python/Combinations-and-permutations | 1 + Lang/Python/Comma-quibbling | 1 + Lang/Python/Conjugate-transpose | 1 + .../Python/Convert-decimal-number-to-rational | 1 + Lang/Python/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Python/Draw-a-clock | 1 + Lang/Python/Extensible-prime-generator | 1 + Lang/Python/Fibonacci-word | 1 + Lang/Python/Fibonacci-word-fractal | 1 + Lang/Python/File-input-output | 1 + .../Python/Find-the-last-Sunday-of-each-month | 1 + Lang/Python/Flipping-bits-game | 1 + Lang/Python/Fractran | 1 + Lang/Python/Gaussian-elimination | 1 + .../Generate-Chess960-starting-position | 1 + .../Python/Generate-lower-case-ASCII-alphabet | 1 + Lang/Python/Hash-join | 1 + Lang/Python/Hello-world-Newbie | 1 + Lang/Python/Heronian-triangles | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Python/IBAN | 1 + Lang/Python/Integer-overflow | 1 + Lang/Python/Iterated-digits-squaring | 1 + Lang/Python/K-d-tree | 1 + Lang/Python/Left-factorials | 1 + Lang/Python/Longest-increasing-subsequence | 1 + Lang/Python/Ludic-numbers | 1 + Lang/Python/Machine-code | 1 + Lang/Python/Magic-squares-of-odd-order | 1 + Lang/Python/Make-directory-path | 1 + Lang/Python/Maximum-triangle-path-sum | 1 + Lang/Python/Move-to-front-algorithm | 1 + Lang/Python/Munching-squares | 1 + Lang/Python/Narcissistic-decimal-number | 1 + Lang/Python/Natural-sorting | 1 + Lang/Python/Nth | 1 + Lang/Python/Odd-word-problem | 1 + Lang/Python/Old-lady-swallowed-a-fly | 1 + Lang/Python/Order-disjoint-list-items | 1 + Lang/Python/Paraffins | 1 + Lang/Python/Parse-an-IP-Address | 1 + Lang/Python/Penneys-game | 1 + Lang/Python/Percolation-Bond-percolation | 1 + Lang/Python/Percolation-Mean-cluster-density | 1 + Lang/Python/Percolation-Mean-run-density | 1 + Lang/Python/Percolation-Site-percolation | 1 + .../Python/Permutations-Rank-of-a-permutation | 1 + Lang/Python/Pernicious-numbers | 1 + Lang/Python/Phrase-reversals | 1 + Lang/Python/Quickselect-algorithm | 1 + Lang/Python/RSA-code | 1 + Lang/Python/Ranking-methods | 1 + Lang/Python/Rep-string | 1 + Lang/Python/Reverse-words-in-a-string | 1 + Lang/Python/Runge-Kutta-method | 1 + Lang/Python/Semiprime | 1 + Lang/Python/Solve-the-no-connection-puzzle | 1 + Lang/Python/Sparkline-in-unicode | 1 + Lang/Python/State-name-puzzle | 1 + Lang/Python/Statistics-Basic | 1 + Lang/Python/Stern-Brocot-sequence | 1 + Lang/Python/String-append | 1 + Lang/Python/String-matching | 1 + Lang/Python/String-prepend | 1 + Lang/Python/Sum-multiples-of-3-and-5 | 1 + Lang/Python/Textonyms | 1 + Lang/Python/The-ISAAC-Cipher | 1 + Lang/Python/The-Twelve-Days-of-Christmas | 1 + Lang/Python/Total-circles-area | 1 + Lang/Python/Ulam-spiral--for-primes- | 1 + Lang/Python/Unix-ls | 1 + Lang/Python/Vogels-approximation-method | 1 + Lang/Python/World-Cup-group-stage | 1 + Lang/Python/Zero-to-the-zero-power | 1 + Lang/Python/Zhang-Suen-thinning-algorithm | 1 + Lang/R/ABC-Problem | 1 + Lang/R/Amb | 1 + Lang/R/Benfords-law | 1 + Lang/R/CSV-data-manipulation | 1 + Lang/R/Chinese-remainder-theorem | 1 + Lang/R/Closures-Value-capture | 1 + Lang/R/Fibonacci-word | 1 + Lang/R/File-input-output | 1 + Lang/R/Nth | 1 + Lang/R/Sum-multiples-of-3-and-5 | 1 + Lang/REALbasic/File-input-output | 1 + Lang/REBOL/Comma-quibbling | 1 + Lang/REBOL/File-input-output | 1 + Lang/REBOL/Find-the-last-Sunday-of-each-month | 1 + Lang/REXX/9-billion-names-of-God-the-integer | 1 + Lang/REXX/ABC-Problem | 1 + Lang/REXX/AKS-test-for-primes | 1 + Lang/REXX/Aliquot-sequence-classifications | 1 + Lang/REXX/Almost-prime | 1 + Lang/REXX/Amb | 1 + Lang/REXX/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/REXX/Benfords-law | 1 + Lang/REXX/Bernoulli-numbers | 1 + Lang/REXX/CSV-data-manipulation | 1 + Lang/REXX/Calendar---for-REAL-programmers | 1 + Lang/REXX/Casting-out-nines | 1 + Lang/REXX/Catalan-numbers-Pascals-triangle | 1 + Lang/REXX/Catamorphism | 1 + Lang/REXX/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/REXX/Closures-Value-capture | 1 + Lang/REXX/Combinations-and-permutations | 1 + Lang/REXX/Comma-quibbling | 1 + Lang/REXX/Conjugate-transpose | 1 + Lang/REXX/Convert-decimal-number-to-rational | 1 + Lang/REXX/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/REXX/Draw-a-clock | 1 + Lang/REXX/Extensible-prime-generator | 1 + Lang/REXX/Fibonacci-word | 1 + Lang/REXX/Fibonacci-word-fractal | 1 + Lang/REXX/File-input-output | 1 + Lang/REXX/Find-the-last-Sunday-of-each-month | 1 + Lang/REXX/Flipping-bits-game | 1 + Lang/REXX/Fractran | 1 + Lang/REXX/Gaussian-elimination | 1 + Lang/REXX/Generate-Chess960-starting-position | 1 + Lang/REXX/Generate-lower-case-ASCII-alphabet | 1 + Lang/REXX/Hash-join | 1 + Lang/REXX/Hello-world-Newbie | 1 + Lang/REXX/Heronian-triangles | 1 + Lang/REXX/Hickerson-series-of-almost-integers | 1 + Lang/REXX/IBAN | 1 + Lang/REXX/Integer-overflow | 1 + Lang/REXX/Iterated-digits-squaring | 1 + Lang/REXX/Left-factorials | 1 + Lang/REXX/Ludic-numbers | 1 + Lang/REXX/Magic-squares-of-odd-order | 1 + Lang/REXX/Make-directory-path | 1 + Lang/REXX/Maximum-triangle-path-sum | 1 + Lang/REXX/Move-to-front-algorithm | 1 + Lang/REXX/Narcissistic-decimal-number | 1 + Lang/REXX/Nth | 1 + Lang/REXX/Odd-word-problem | 1 + Lang/REXX/Old-lady-swallowed-a-fly | 1 + Lang/REXX/Order-disjoint-list-items | 1 + Lang/REXX/Paraffins | 1 + Lang/REXX/Parse-an-IP-Address | 1 + Lang/REXX/Penneys-game | 1 + Lang/REXX/Permutations-Rank-of-a-permutation | 1 + Lang/REXX/Pernicious-numbers | 1 + Lang/REXX/Phrase-reversals | 1 + Lang/REXX/Quickselect-algorithm | 1 + Lang/REXX/Rep-string | 1 + Lang/REXX/Reverse-words-in-a-string | 1 + Lang/REXX/Runge-Kutta-method | 1 + Lang/REXX/Semiprime | 1 + .../REXX/Sequence-of-primes-by-Trial-Division | 1 + Lang/REXX/Solve-a-Holy-Knights-tour | 1 + Lang/REXX/Solve-a-Hopido-puzzle | 1 + Lang/REXX/Solve-a-Numbrix-puzzle | 1 + Lang/REXX/Solve-the-no-connection-puzzle | 1 + Lang/REXX/Sparkline-in-unicode | 1 + Lang/REXX/State-name-puzzle | 1 + Lang/REXX/Statistics-Basic | 1 + Lang/REXX/Stern-Brocot-sequence | 1 + Lang/REXX/String-append | 1 + Lang/REXX/String-matching | 1 + Lang/REXX/String-prepend | 1 + Lang/REXX/Sum-multiples-of-3-and-5 | 1 + Lang/REXX/Textonyms | 1 + Lang/REXX/The-ISAAC-Cipher | 1 + Lang/REXX/The-Twelve-Days-of-Christmas | 1 + Lang/REXX/Total-circles-area | 1 + Lang/REXX/Ulam-spiral--for-primes- | 1 + Lang/REXX/Unix-ls | 1 + Lang/REXX/Zero-to-the-zero-power | 1 + Lang/REXX/Zhang-Suen-thinning-algorithm | 1 + .../Racket/9-billion-names-of-God-the-integer | 1 + Lang/Racket/ABC-Problem | 1 + Lang/Racket/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Racket/Aliquot-sequence-classifications | 1 + Lang/Racket/Almost-prime | 1 + Lang/Racket/Amb | 1 + Lang/Racket/Amicable-pairs | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Racket/Benfords-law | 1 + Lang/Racket/Bernoulli-numbers | 1 + Lang/Racket/Bitcoin-public-point-to-address | 1 + Lang/Racket/CSV-data-manipulation | 1 + Lang/Racket/Calendar---for-REAL-programmers | 1 + Lang/Racket/Casting-out-nines | 1 + Lang/Racket/Catalan-numbers-Pascals-triangle | 1 + Lang/Racket/Catamorphism | 1 + Lang/Racket/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Racket/Closures-Value-capture | 1 + Lang/Racket/Combinations-and-permutations | 1 + Lang/Racket/Comma-quibbling | 1 + Lang/Racket/Conjugate-transpose | 1 + .../Racket/Convert-decimal-number-to-rational | 1 + Lang/Racket/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Racket/Draw-a-clock | 1 + Lang/Racket/Extensible-prime-generator | 1 + Lang/Racket/Fibonacci-word | 1 + Lang/Racket/Fibonacci-word-fractal | 1 + Lang/Racket/File-input-output | 1 + .../Racket/Find-the-last-Sunday-of-each-month | 1 + Lang/Racket/Flipping-bits-game | 1 + Lang/Racket/Fractran | 1 + Lang/Racket/Gaussian-elimination | 1 + .../Generate-Chess960-starting-position | 1 + .../Racket/Generate-lower-case-ASCII-alphabet | 1 + Lang/Racket/Hash-join | 1 + Lang/Racket/Heronian-triangles | 1 + .../Hickerson-series-of-almost-integers | 1 + Lang/Racket/IBAN | 1 + Lang/Racket/Iterated-digits-squaring | 1 + Lang/Racket/K-d-tree | 1 + Lang/Racket/Left-factorials | 1 + Lang/Racket/Longest-increasing-subsequence | 1 + Lang/Racket/Ludic-numbers | 1 + Lang/Racket/Magic-squares-of-odd-order | 1 + Lang/Racket/Make-directory-path | 1 + Lang/Racket/Maximum-triangle-path-sum | 1 + Lang/Racket/Move-to-front-algorithm | 1 + Lang/Racket/Munching-squares | 1 + Lang/Racket/Narcissistic-decimal-number | 1 + Lang/Racket/Natural-sorting | 1 + Lang/Racket/Nth | 1 + Lang/Racket/Odd-word-problem | 1 + Lang/Racket/Old-lady-swallowed-a-fly | 1 + Lang/Racket/Order-disjoint-list-items | 1 + Lang/Racket/Paraffins | 1 + Lang/Racket/Parse-an-IP-Address | 1 + Lang/Racket/Penneys-game | 1 + Lang/Racket/Percolation-Bond-percolation | 1 + Lang/Racket/Percolation-Mean-cluster-density | 1 + Lang/Racket/Percolation-Mean-run-density | 1 + Lang/Racket/Percolation-Site-percolation | 1 + .../Racket/Permutations-Rank-of-a-permutation | 1 + Lang/Racket/Pernicious-numbers | 1 + Lang/Racket/Phrase-reversals | 1 + Lang/Racket/Quickselect-algorithm | 1 + Lang/Racket/RSA-code | 1 + Lang/Racket/Ranking-methods | 1 + Lang/Racket/Rep-string | 1 + Lang/Racket/Reverse-words-in-a-string | 1 + Lang/Racket/Runge-Kutta-method | 1 + Lang/Racket/Semiprime | 1 + .../Sequence-of-primes-by-Trial-Division | 1 + Lang/Racket/Solve-a-Holy-Knights-tour | 1 + Lang/Racket/Solve-a-Hopido-puzzle | 1 + Lang/Racket/Solve-a-Numbrix-puzzle | 1 + Lang/Racket/Solve-the-no-connection-puzzle | 1 + Lang/Racket/Sparkline-in-unicode | 1 + Lang/Racket/State-name-puzzle | 1 + Lang/Racket/Statistics-Basic | 1 + Lang/Racket/Stern-Brocot-sequence | 1 + Lang/Racket/String-append | 1 + Lang/Racket/String-matching | 1 + Lang/Racket/String-prepend | 1 + Lang/Racket/Sum-multiples-of-3-and-5 | 1 + Lang/Racket/The-ISAAC-Cipher | 1 + Lang/Racket/The-Twelve-Days-of-Christmas | 1 + Lang/Racket/Ulam-spiral--for-primes- | 1 + Lang/Racket/Unix-ls | 1 + Lang/Racket/Vogels-approximation-method | 1 + Lang/Racket/World-Cup-group-stage | 1 + Lang/Racket/Zero-to-the-zero-power | 1 + Lang/Racket/Zhang-Suen-thinning-algorithm | 1 + Lang/RapidQ/ABC-Problem | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/RapidQ/File-input-output | 1 + Lang/Raven/File-input-output | 1 + Lang/Retro/File-input-output | 1 + Lang/Retro/String-matching | 1 + Lang/Ruby/9-billion-names-of-God-the-integer | 1 + Lang/Ruby/ABC-Problem | 1 + Lang/Ruby/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Ruby/Aliquot-sequence-classifications | 1 + Lang/Ruby/Almost-prime | 1 + Lang/Ruby/Amb | 1 + Lang/Ruby/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Ruby/Benfords-law | 1 + Lang/Ruby/Bernoulli-numbers | 1 + Lang/Ruby/Bitcoin-public-point-to-address | 1 + Lang/Ruby/CSV-data-manipulation | 1 + Lang/Ruby/Calendar---for-REAL-programmers | 1 + Lang/Ruby/Catalan-numbers-Pascals-triangle | 1 + Lang/Ruby/Catamorphism | 1 + Lang/Ruby/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Ruby/Closures-Value-capture | 1 + Lang/Ruby/Combinations-and-permutations | 1 + Lang/Ruby/Comma-quibbling | 1 + Lang/Ruby/Conjugate-transpose | 1 + Lang/Ruby/Convert-decimal-number-to-rational | 1 + Lang/Ruby/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Ruby/Draw-a-clock | 1 + Lang/Ruby/Extensible-prime-generator | 1 + Lang/Ruby/Fibonacci-word | 1 + Lang/Ruby/Fibonacci-word-fractal | 1 + Lang/Ruby/File-input-output | 1 + Lang/Ruby/Find-the-last-Sunday-of-each-month | 1 + Lang/Ruby/Flipping-bits-game | 1 + Lang/Ruby/Fractran | 1 + Lang/Ruby/Gaussian-elimination | 1 + Lang/Ruby/Generate-Chess960-starting-position | 1 + Lang/Ruby/Generate-lower-case-ASCII-alphabet | 1 + Lang/Ruby/Hash-join | 1 + Lang/Ruby/Heronian-triangles | 1 + Lang/Ruby/Hickerson-series-of-almost-integers | 1 + Lang/Ruby/IBAN | 1 + Lang/Ruby/Integer-overflow | 1 + Lang/Ruby/Iterated-digits-squaring | 1 + Lang/Ruby/Left-factorials | 1 + Lang/Ruby/Longest-increasing-subsequence | 1 + Lang/Ruby/Ludic-numbers | 1 + Lang/Ruby/Magic-squares-of-odd-order | 1 + Lang/Ruby/Make-directory-path | 1 + Lang/Ruby/Maximum-triangle-path-sum | 1 + Lang/Ruby/Move-to-front-algorithm | 1 + Lang/Ruby/Munching-squares | 1 + Lang/Ruby/Narcissistic-decimal-number | 1 + Lang/Ruby/Natural-sorting | 1 + Lang/Ruby/Nth | 1 + Lang/Ruby/Odd-word-problem | 1 + Lang/Ruby/Old-lady-swallowed-a-fly | 1 + Lang/Ruby/Order-disjoint-list-items | 1 + Lang/Ruby/Paraffins | 1 + Lang/Ruby/Parse-an-IP-Address | 1 + Lang/Ruby/Penneys-game | 1 + Lang/Ruby/Permutations-Rank-of-a-permutation | 1 + Lang/Ruby/Pernicious-numbers | 1 + Lang/Ruby/Phrase-reversals | 1 + Lang/Ruby/Quickselect-algorithm | 1 + Lang/Ruby/Ranking-methods | 1 + Lang/Ruby/Rep-string | 1 + Lang/Ruby/Reverse-words-in-a-string | 1 + Lang/Ruby/Runge-Kutta-method | 1 + Lang/Ruby/Semiprime | 1 + .../Ruby/Sequence-of-primes-by-Trial-Division | 1 + Lang/Ruby/Solve-a-Holy-Knights-tour | 1 + Lang/Ruby/Solve-a-Hopido-puzzle | 1 + Lang/Ruby/Solve-a-Numbrix-puzzle | 1 + Lang/Ruby/Solve-the-no-connection-puzzle | 1 + Lang/Ruby/Sparkline-in-unicode | 1 + Lang/Ruby/State-name-puzzle | 1 + Lang/Ruby/Statistics-Basic | 1 + Lang/Ruby/Stern-Brocot-sequence | 1 + Lang/Ruby/String-append | 1 + Lang/Ruby/String-matching | 1 + Lang/Ruby/String-prepend | 1 + Lang/Ruby/Sum-multiples-of-3-and-5 | 1 + Lang/Ruby/Textonyms | 1 + Lang/Ruby/The-Twelve-Days-of-Christmas | 1 + Lang/Ruby/Total-circles-area | 1 + Lang/Ruby/Unix-ls | 1 + Lang/Ruby/Vogels-approximation-method | 1 + Lang/Ruby/World-Cup-group-stage | 1 + Lang/Ruby/Zero-to-the-zero-power | 1 + Lang/Ruby/Zhang-Suen-thinning-algorithm | 1 + Lang/Run-BASIC/Benfords-law | 1 + Lang/Run-BASIC/CSV-data-manipulation | 1 + .../Catalan-numbers-Pascals-triangle | 1 + Lang/Run-BASIC/Catamorphism | 1 + Lang/Run-BASIC/Comma-quibbling | 1 + Lang/Run-BASIC/Draw-a-clock | 1 + Lang/Run-BASIC/File-input-output | 1 + Lang/Run-BASIC/Munching-squares | 1 + Lang/Run-BASIC/Odd-word-problem | 1 + Lang/Run-BASIC/Runge-Kutta-method | 1 + Lang/Run-BASIC/String-matching | 1 + Lang/Run-BASIC/Sum-multiples-of-3-and-5 | 1 + Lang/Rust/ABC-Problem | 1 + Lang/Rust/AKS-test-for-primes | 1 + Lang/Rust/Almost-prime | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Rust/Closures-Value-capture | 1 + Lang/Rust/Comma-quibbling | 1 + Lang/Rust/Currying | 1 + Lang/Rust/File-input-output | 1 + Lang/Rust/Hello-world-Newbie | 1 + Lang/Rust/Magic-squares-of-odd-order | 1 + Lang/Rust/Nth | 1 + Lang/Rust/The-Twelve-Days-of-Christmas | 1 + Lang/Rust/Unix-ls | 1 + Lang/Rust/Zero-to-the-zero-power | 1 + Lang/SETL/Amb | 1 + Lang/SNOBOL4/File-input-output | 1 + Lang/SQL/Benfords-law | 1 + Lang/SQL/Hash-join | 1 + Lang/Scala/9-billion-names-of-God-the-integer | 1 + Lang/Scala/ABC-Problem | 1 + Lang/Scala/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Scala/Aliquot-sequence-classifications | 1 + Lang/Scala/Almost-prime | 1 + Lang/Scala/Amb | 1 + Lang/Scala/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Scala/Benfords-law | 1 + Lang/Scala/CSV-data-manipulation | 1 + Lang/Scala/Closures-Value-capture | 1 + Lang/Scala/Comma-quibbling | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Scala/Draw-a-clock | 1 + Lang/Scala/Fibonacci-word | 1 + Lang/Scala/Fibonacci-word-fractal | 1 + Lang/Scala/File-input-output | 1 + Lang/Scala/Find-the-last-Sunday-of-each-month | 1 + Lang/Scala/Generate-lower-case-ASCII-alphabet | 1 + Lang/Scala/Hash-join | 1 + Lang/Scala/Hello-world-Newbie | 1 + Lang/Scala/IBAN | 1 + Lang/Scala/Integer-overflow | 1 + Lang/Scala/K-d-tree | 1 + Lang/Scala/Longest-increasing-subsequence | 1 + Lang/Scala/Make-directory-path | 1 + Lang/Scala/Maximum-triangle-path-sum | 1 + Lang/Scala/Munching-squares | 1 + Lang/Scala/Narcissistic-decimal-number | 1 + Lang/Scala/Natural-sorting | 1 + Lang/Scala/Nth | 1 + Lang/Scala/Odd-word-problem | 1 + Lang/Scala/Old-lady-swallowed-a-fly | 1 + Lang/Scala/Order-disjoint-list-items | 1 + Lang/Scala/Pernicious-numbers | 1 + Lang/Scala/Quickselect-algorithm | 1 + Lang/Scala/Ranking-methods | 1 + Lang/Scala/Rep-string | 1 + Lang/Scala/Reverse-words-in-a-string | 1 + Lang/Scala/Semiprime | 1 + .../Sequence-of-primes-by-Trial-Division | 1 + Lang/Scala/Sparkline-in-unicode | 1 + Lang/Scala/State-name-puzzle | 1 + Lang/Scala/Statistics-Basic | 1 + Lang/Scala/String-append | 1 + Lang/Scala/String-matching | 1 + Lang/Scala/String-prepend | 1 + Lang/Scala/Sum-multiples-of-3-and-5 | 1 + Lang/Scala/Zero-to-the-zero-power | 1 + Lang/Scheme/Amb | 1 + Lang/Scheme/Closures-Value-capture | 1 + Lang/Scheme/File-input-output | 1 + .../Scheme/Generate-lower-case-ASCII-alphabet | 1 + Lang/Scheme/Hash-join | 1 + Lang/Scheme/Longest-increasing-subsequence | 1 + Lang/Scheme/Odd-word-problem | 1 + Lang/Scheme/Reverse-words-in-a-string | 1 + Lang/Scheme/Sum-multiples-of-3-and-5 | 1 + Lang/Scheme/Zero-to-the-zero-power | 1 + Lang/Scilab/AKS-test-for-primes | 1 + Lang/Scilab/Catalan-numbers-Pascals-triangle | 1 + Lang/Seed7/ABC-Problem | 1 + Lang/Seed7/AKS-test-for-primes | 1 + Lang/Seed7/Amb | 1 + Lang/Seed7/CSV-data-manipulation | 1 + Lang/Seed7/Calendar---for-REAL-programmers | 1 + Lang/Seed7/Casting-out-nines | 1 + Lang/Seed7/Catalan-numbers-Pascals-triangle | 1 + Lang/Seed7/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Seed7/Comma-quibbling | 1 + Lang/Seed7/Convert-decimal-number-to-rational | 1 + Lang/Seed7/Draw-a-clock | 1 + Lang/Seed7/Extensible-prime-generator | 1 + Lang/Seed7/Fibonacci-word | 1 + Lang/Seed7/File-input-output | 1 + Lang/Seed7/Find-the-last-Sunday-of-each-month | 1 + Lang/Seed7/Fractran | 1 + .../Seed7/Generate-Chess960-starting-position | 1 + .../Seed7/Hickerson-series-of-almost-integers | 1 + Lang/Seed7/IBAN | 1 + Lang/Seed7/Integer-overflow | 1 + Lang/Seed7/Left-factorials | 1 + Lang/Seed7/Ludic-numbers | 1 + Lang/Seed7/Magic-squares-of-odd-order | 1 + Lang/Seed7/Nth | 1 + Lang/Seed7/Odd-word-problem | 1 + Lang/Seed7/Old-lady-swallowed-a-fly | 1 + Lang/Seed7/Paraffins | 1 + Lang/Seed7/RSA-code | 1 + Lang/Seed7/Rep-string | 1 + Lang/Seed7/Reverse-words-in-a-string | 1 + Lang/Seed7/Semiprime | 1 + Lang/Seed7/Sparkline-in-unicode | 1 + Lang/Seed7/String-append | 1 + Lang/Seed7/String-matching | 1 + Lang/Seed7/String-prepend | 1 + Lang/Seed7/Sum-multiples-of-3-and-5 | 1 + Lang/Seed7/The-Twelve-Days-of-Christmas | 1 + Lang/Seed7/Zero-to-the-zero-power | 1 + Lang/Slate/File-input-output | 1 + Lang/Smalltalk/ABC-Problem | 1 + Lang/Smalltalk/Closures-Value-capture | 1 + Lang/Smalltalk/File-input-output | 1 + Lang/Smalltalk/Reverse-words-in-a-string | 1 + Lang/Smalltalk/String-matching | 1 + Lang/Smalltalk/Zero-to-the-zero-power | 1 + Lang/Standard-ML/Catamorphism | 1 + Lang/Standard-ML/Comma-quibbling | 1 + Lang/Standard-ML/Currying | 1 + Lang/Standard-ML/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + .../Longest-increasing-subsequence | 1 + Lang/Standard-ML/Quickselect-algorithm | 1 + Lang/Standard-ML/Runge-Kutta-method | 1 + Lang/Standard-ML/String-matching | 1 + .../Catalan-numbers-Pascals-triangle | 1 + Lang/TI-83-BASIC/Hello-world-Newbie | 1 + Lang/TI-83-BASIC/Munching-squares | 1 + Lang/TUSCRIPT/ABC-Problem | 1 + Lang/TUSCRIPT/Amb | 1 + Lang/TUSCRIPT/CSV-data-manipulation | 1 + Lang/TUSCRIPT/Odd-word-problem | 1 + Lang/TUSCRIPT/String-matching | 1 + Lang/TXR/ABC-Problem | 1 + Lang/TXR/Amb | 1 + Lang/TXR/Hash-join | 1 + Lang/TXR/Old-lady-swallowed-a-fly | 1 + Lang/TXR/String-matching | 1 + Lang/Tcl/9-billion-names-of-God-the-integer | 1 + Lang/Tcl/ABC-Problem | 1 + Lang/Tcl/AKS-test-for-primes | 1 + Lang/Tcl/Almost-prime | 1 + Lang/Tcl/Amb | 1 + Lang/Tcl/Amicable-pairs | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Tcl/Benfords-law | 1 + Lang/Tcl/Bernoulli-numbers | 1 + Lang/Tcl/Bitcoin-public-point-to-address | 1 + Lang/Tcl/CSV-data-manipulation | 1 + Lang/Tcl/Calendar---for-REAL-programmers | 1 + Lang/Tcl/Casting-out-nines | 1 + Lang/Tcl/Catalan-numbers-Pascals-triangle | 1 + Lang/Tcl/Catamorphism | 1 + Lang/Tcl/Chinese-remainder-theorem | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Tcl/Closures-Value-capture | 1 + Lang/Tcl/Combinations-and-permutations | 1 + Lang/Tcl/Comma-quibbling | 1 + Lang/Tcl/Conjugate-transpose | 1 + Lang/Tcl/Convert-decimal-number-to-rational | 1 + Lang/Tcl/Currying | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Tcl/Draw-a-clock | 1 + Lang/Tcl/Extensible-prime-generator | 1 + Lang/Tcl/Fibonacci-word | 1 + Lang/Tcl/Fibonacci-word-fractal | 1 + Lang/Tcl/File-input-output | 1 + Lang/Tcl/Find-the-last-Sunday-of-each-month | 1 + Lang/Tcl/Flipping-bits-game | 1 + Lang/Tcl/Fractran | 1 + Lang/Tcl/Gaussian-elimination | 1 + Lang/Tcl/Generate-Chess960-starting-position | 1 + Lang/Tcl/Generate-lower-case-ASCII-alphabet | 1 + Lang/Tcl/Hash-join | 1 + Lang/Tcl/Hello-world-Newbie | 1 + Lang/Tcl/Hickerson-series-of-almost-integers | 1 + Lang/Tcl/IBAN | 1 + Lang/Tcl/Integer-overflow | 1 + Lang/Tcl/Iterated-digits-squaring | 1 + Lang/Tcl/K-d-tree | 1 + Lang/Tcl/Left-factorials | 1 + Lang/Tcl/Longest-increasing-subsequence | 1 + Lang/Tcl/Ludic-numbers | 1 + Lang/Tcl/Machine-code | 1 + Lang/Tcl/Magic-squares-of-odd-order | 1 + Lang/Tcl/Make-directory-path | 1 + Lang/Tcl/Maximum-triangle-path-sum | 1 + Lang/Tcl/Move-to-front-algorithm | 1 + Lang/Tcl/Munching-squares | 1 + Lang/Tcl/Narcissistic-decimal-number | 1 + Lang/Tcl/Natural-sorting | 1 + Lang/Tcl/Nth | 1 + Lang/Tcl/Odd-word-problem | 1 + Lang/Tcl/Old-lady-swallowed-a-fly | 1 + Lang/Tcl/Order-disjoint-list-items | 1 + Lang/Tcl/Paraffins | 1 + Lang/Tcl/Parse-an-IP-Address | 1 + Lang/Tcl/Penneys-game | 1 + Lang/Tcl/Percolation-Bond-percolation | 1 + Lang/Tcl/Percolation-Mean-cluster-density | 1 + Lang/Tcl/Percolation-Mean-run-density | 1 + Lang/Tcl/Percolation-Site-percolation | 1 + Lang/Tcl/Permutations-Rank-of-a-permutation | 1 + Lang/Tcl/Pernicious-numbers | 1 + Lang/Tcl/Phrase-reversals | 1 + Lang/Tcl/Quickselect-algorithm | 1 + Lang/Tcl/RSA-code | 1 + Lang/Tcl/Ranking-methods | 1 + Lang/Tcl/Rep-string | 1 + Lang/Tcl/Reverse-words-in-a-string | 1 + Lang/Tcl/Runge-Kutta-method | 1 + Lang/Tcl/Semiprime | 1 + Lang/Tcl/Sequence-of-primes-by-Trial-Division | 1 + Lang/Tcl/Solve-a-Holy-Knights-tour | 1 + Lang/Tcl/Solve-a-Hopido-puzzle | 1 + Lang/Tcl/Solve-the-no-connection-puzzle | 1 + Lang/Tcl/Sparkline-in-unicode | 1 + Lang/Tcl/State-name-puzzle | 1 + Lang/Tcl/Statistics-Basic | 1 + Lang/Tcl/String-append | 1 + Lang/Tcl/String-matching | 1 + Lang/Tcl/String-prepend | 1 + Lang/Tcl/Sum-multiples-of-3-and-5 | 1 + Lang/Tcl/The-ISAAC-Cipher | 1 + Lang/Tcl/The-Twelve-Days-of-Christmas | 1 + Lang/Tcl/Total-circles-area | 1 + Lang/Tcl/Unix-ls | 1 + Lang/Tcl/Vogels-approximation-method | 1 + Lang/Tcl/World-Cup-group-stage | 1 + Lang/Tcl/Zero-to-the-zero-power | 1 + Lang/Tcl/Zhang-Suen-thinning-algorithm | 1 + Lang/Toka/File-input-output | 1 + Lang/UNIX-Shell/ABC-Problem | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/UNIX-Shell/CSV-data-manipulation | 1 + Lang/UNIX-Shell/Comma-quibbling | 1 + Lang/UNIX-Shell/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/UNIX-Shell/IBAN | 1 + Lang/UNIX-Shell/Make-directory-path | 1 + Lang/UNIX-Shell/Narcissistic-decimal-number | 1 + Lang/UNIX-Shell/Penneys-game | 1 + Lang/UNIX-Shell/Phrase-reversals | 1 + Lang/UNIX-Shell/Rep-string | 1 + Lang/UNIX-Shell/Reverse-words-in-a-string | 1 + Lang/Ursala/File-input-output | 1 + Lang/VBA/String-append | 1 + Lang/VBA/String-prepend | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/VBScript/Amb | 1 + Lang/VBScript/Amicable-pairs | 1 + .../VBScript/Catalan-numbers-Pascals-triangle | 1 + Lang/VBScript/File-input-output | 1 + .../Find-the-last-Sunday-of-each-month | 1 + Lang/VBScript/Stern-Brocot-sequence | 1 + Lang/VBScript/Textonyms | 1 + .../CSV-data-manipulation | 1 + .../Calendar---for-REAL-programmers | 1 + Lang/Vedit-macro-language/File-input-output | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Visual-Basic-.NET/File-input-output | 1 + .../Catalan-numbers-Pascals-triangle | 1 + .../Calendar---for-REAL-programmers | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/XPL0/Comma-quibbling | 1 + Lang/XPL0/File-input-output | 1 + Lang/XPL0/Munching-squares | 1 + Lang/XPL0/Solve-the-no-connection-puzzle | 1 + Lang/XPL0/String-matching | 1 + Lang/XPL0/Sum-multiples-of-3-and-5 | 1 + Lang/ZX-Spectrum-Basic/Hello-world-Newbie | 1 + Meta/Task.yaml | 432 +++++++++++++++-- .../00DESCRIPTION | 28 ++ .../9-billion-names-of-god-the-integer.ahk | 58 +++ .../9-billion-names-of-god-the-integer-1.cpp | 8 + .../9-billion-names-of-god-the-integer-2.cpp | 10 + .../9-billion-names-of-god-the-integer-3.cpp | 24 + .../9-billion-names-of-god-the-integer-4.cpp | 11 + .../C/9-billion-names-of-god-the-integer.c | 40 ++ .../9-billion-names-of-god-the-integer.lisp | 15 + .../D/9-billion-names-of-god-the-integer-1.d | 27 ++ .../D/9-billion-names-of-god-the-integer-2.d | 51 ++ .../9-billion-names-of-god-the-integer.erl | 29 ++ .../9-billion-names-of-god-the-integer.frink | 54 +++ .../9-billion-names-of-god-the-integer-1.hs | 21 + .../9-billion-names-of-god-the-integer-2.hs | 25 + .../J/9-billion-names-of-god-the-integer-1.j | 1 + .../J/9-billion-names-of-god-the-integer-2.j | 1 + .../J/9-billion-names-of-god-the-integer-3.j | 11 + .../J/9-billion-names-of-god-the-integer-4.j | 11 + .../9-billion-names-of-god-the-integer.js | 57 +++ .../9-billion-names-of-god-the-integer-1.math | 1 + .../9-billion-names-of-god-the-integer-2.math | 1 + .../9-billion-names-of-god-the-integer-3.math | 1 + .../9-billion-names-of-god-the-integer.ocaml | 78 +++ .../9-billion-names-of-god-the-integer.pl6 | 29 ++ .../9-billion-names-of-god-the-integer-1.pl | 12 + .../9-billion-names-of-god-the-integer-2.pl | 40 ++ .../9-billion-names-of-god-the-integer.l | 52 ++ .../9-billion-names-of-god-the-integer-1.py | 19 + .../9-billion-names-of-god-the-integer-2.py | 18 + .../9-billion-names-of-god-the-integer-3.py | 38 ++ .../9-billion-names-of-God-the-integer/README | 1 + .../9-billion-names-of-god-the-integer.rexx | 52 ++ .../9-billion-names-of-god-the-integer.rkt | 23 + .../9-billion-names-of-god-the-integer-1.rb | 10 + .../9-billion-names-of-god-the-integer-2.rb | 30 ++ ...9-billion-names-of-god-the-integer-1.scala | 36 ++ ...9-billion-names-of-god-the-integer-2.scala | 49 ++ .../9-billion-names-of-god-the-integer.tcl | 30 ++ Task/ABC-Problem/00DESCRIPTION | 48 ++ Task/ABC-Problem/Ada/abc-problem.ada | 78 +++ Task/ABC-Problem/AutoHotkey/abc-problem-1.ahk | 24 + Task/ABC-Problem/AutoHotkey/abc-problem-2.ahk | 38 ++ Task/ABC-Problem/BBC-BASIC/abc-problem.bbc | 22 + Task/ABC-Problem/Batch-File/abc-problem.bat | 62 +++ Task/ABC-Problem/Bracmat/abc-problem.bracmat | 48 ++ Task/ABC-Problem/C++/abc-problem.cpp | 37 ++ Task/ABC-Problem/C-sharp/abc-problem.cs | 82 ++++ Task/ABC-Problem/C/abc-problem.c | 41 ++ Task/ABC-Problem/Clojure/abc-problem.clj | 21 + .../CoffeeScript/abc-problem.coffee | 15 + Task/ABC-Problem/Common-Lisp/abc-problem.lisp | 14 + Task/ABC-Problem/D/abc-problem-1.d | 22 + Task/ABC-Problem/D/abc-problem-2.d | 39 ++ Task/ABC-Problem/D/abc-problem-3.d | 38 ++ Task/ABC-Problem/D/abc-problem-4.d | 42 ++ Task/ABC-Problem/Delphi/abc-problem.delphi | 63 +++ Task/ABC-Problem/Erlang/abc-problem.erl | 16 + .../ABC-Problem/Euphoria/abc-problem.euphoria | 35 ++ Task/ABC-Problem/FBSL/abc-problem.fbsl | 44 ++ Task/ABC-Problem/Fortran/abc-problem.f | 70 +++ Task/ABC-Problem/Go/abc-problem.go | 39 ++ Task/ABC-Problem/Groovy/abc-problem-1.groovy | 12 + Task/ABC-Problem/Groovy/abc-problem-2.groovy | 6 + Task/ABC-Problem/Haskell/abc-problem.hs | 15 + Task/ABC-Problem/Icon/abc-problem.icon | 24 + Task/ABC-Problem/J/abc-problem-1.j | 11 + Task/ABC-Problem/J/abc-problem-2.j | 14 + Task/ABC-Problem/J/abc-problem-3.j | 3 + Task/ABC-Problem/J/abc-problem-4.j | 10 + Task/ABC-Problem/J/abc-problem-5.j | 14 + Task/ABC-Problem/Java/abc-problem.java | 44 ++ Task/ABC-Problem/JavaScript/abc-problem.js | 32 ++ Task/ABC-Problem/Julia/abc-problem.julia | 9 + Task/ABC-Problem/Logo/abc-problem.logo | 21 + Task/ABC-Problem/MATLAB/abc-problem.m | 26 + Task/ABC-Problem/MAXScript/abc-problem-1.max | 98 ++++ Task/ABC-Problem/MAXScript/abc-problem-2.max | 14 + Task/ABC-Problem/MAXScript/abc-problem-3.max | 30 ++ Task/ABC-Problem/MAXScript/abc-problem-4.max | 4 + Task/ABC-Problem/Mathematica/abc-problem.math | 12 + Task/ABC-Problem/OCaml/abc-problem.ocaml | 40 ++ .../ABC-Problem/Oberon-2/abc-problem.oberon-2 | 83 ++++ Task/ABC-Problem/PHP/abc-problem.php | 29 ++ Task/ABC-Problem/PL-I/abc-problem-1.pli | 25 + Task/ABC-Problem/PL-I/abc-problem-2.pli | 121 +++++ Task/ABC-Problem/Perl-6/abc-problem.pl6 | 21 + Task/ABC-Problem/Perl/abc-problem-1.pl | 26 + Task/ABC-Problem/Perl/abc-problem-2.pl | 13 + Task/ABC-Problem/PicoLisp/abc-problem.l | 33 ++ .../PowerBASIC/abc-problem.powerbasic | 155 ++++++ Task/ABC-Problem/Prolog/abc-problem.pro | 22 + Task/ABC-Problem/Python/abc-problem-1.py | 63 +++ Task/ABC-Problem/Python/abc-problem-2.py | 25 + Task/ABC-Problem/Python/abc-problem-3.py | 16 + Task/ABC-Problem/R/abc-problem-1.r | 43 ++ Task/ABC-Problem/R/abc-problem-2.r | 21 + Task/ABC-Problem/README | 1 + Task/ABC-Problem/REXX/abc-problem-1.rexx | 24 + Task/ABC-Problem/REXX/abc-problem-2.rexx | 103 ++++ Task/ABC-Problem/Racket/abc-problem.rkt | 43 ++ Task/ABC-Problem/RapidQ/abc-problem.rapidq | 26 + Task/ABC-Problem/Ruby/abc-problem.rb | 7 + Task/ABC-Problem/Rust/abc-problem.rust | 33 ++ Task/ABC-Problem/Scala/abc-problem.scala | 50 ++ Task/ABC-Problem/Seed7/abc-problem.seed7 | 34 ++ Task/ABC-Problem/Smalltalk/abc-problem.st | 21 + Task/ABC-Problem/TUSCRIPT/abc-problem.tu | 18 + Task/ABC-Problem/TXR/abc-problem.txr | 47 ++ Task/ABC-Problem/Tcl/abc-problem.tcl | 21 + Task/ABC-Problem/UNIX-Shell/abc-problem.sh | 39 ++ Task/AKS-test-for-primes/00DESCRIPTION | 30 ++ Task/AKS-test-for-primes/00META.yaml | 2 + .../AutoHotkey/aks-test-for-primes.ahk | 53 ++ .../Bracmat/aks-test-for-primes-1.bracmat | 27 ++ .../Bracmat/aks-test-for-primes-2.bracmat | 9 + .../C/aks-test-for-primes.c | 51 ++ .../Clojure/aks-test-for-primes.clj | 18 + .../CoffeeScript/aks-test-for-primes.coffee | 39 ++ .../Common-Lisp/aks-test-for-primes.lisp | 36 ++ .../D/aks-test-for-primes.d | 29 ++ .../Erlang/aks-test-for-primes.erl | 39 ++ .../Go/aks-test-for-primes.go | 65 +++ .../Haskell/aks-test-for-primes.hs | 20 + .../J/aks-test-for-primes-1.j | 2 + .../J/aks-test-for-primes-2.j | 10 + .../JavaScript/aks-test-for-primes.js | 79 +++ .../Maple/aks-test-for-primes-1.maple | 22 + .../Maple/aks-test-for-primes-2.maple | 1 + .../Maple/aks-test-for-primes-3.maple | 1 + .../Maple/aks-test-for-primes-4.maple | 1 + .../Maple/aks-test-for-primes-5.maple | 2 + .../Maple/aks-test-for-primes-6.maple | 2 + .../Mathematica/aks-test-for-primes.math | 7 + .../PARI-GP/aks-test-for-primes.pari | 5 + .../Pascal/aks-test-for-primes.pascal | 108 +++++ .../Perl-6/aks-test-for-primes-1.pl6 | 3 + .../Perl-6/aks-test-for-primes-2.pl6 | 21 + .../Perl-6/aks-test-for-primes-3.pl6 | 1 + .../Perl/aks-test-for-primes.pl | 29 ++ .../PicoLisp/aks-test-for-primes.l | 20 + .../Prolog/aks-test-for-primes-1.pro | 4 + .../Prolog/aks-test-for-primes-2.pro | 43 ++ .../Prolog/aks-test-for-primes-3.pro | 22 + .../Prolog/aks-test-for-primes-4.pro | 11 + .../Prolog/aks-test-for-primes-5.pro | 1 + .../Prolog/aks-test-for-primes-6.pro | 11 + .../Python/aks-test-for-primes-1.py | 20 + .../Python/aks-test-for-primes-2.py | 15 + Task/AKS-test-for-primes/README | 1 + .../REXX/aks-test-for-primes-1.rexx | 49 ++ .../REXX/aks-test-for-primes-2.rexx | 42 ++ .../Racket/aks-test-for-primes.rkt | 61 +++ .../Ruby/aks-test-for-primes-1.rb | 18 + .../Ruby/aks-test-for-primes-2.rb | 26 + .../Rust/aks-test-for-primes-1.rust | 38 ++ .../Rust/aks-test-for-primes-2.rust | 12 + .../Scala/aks-test-for-primes.scala | 30 ++ .../Scilab/aks-test-for-primes.scilab | 67 +++ .../Seed7/aks-test-for-primes.seed7 | 60 +++ .../Tcl/aks-test-for-primes.tcl | 51 ++ .../00DESCRIPTION | 17 + ...ent-and-perfect-number-classifications.ahk | 52 ++ ...cient-and-perfect-number-classifications.c | 41 ++ ...cient-and-perfect-number-classifications.d | 18 + ...ient-and-perfect-number-classifications.hs | 13 + ...ent-and-perfect-number-classifications-1.j | 2 + ...ent-and-perfect-number-classifications-2.j | 2 + ...ent-and-perfect-number-classifications-3.j | 2 + ...ent-and-perfect-number-classifications-4.j | 2 + ...ent-and-perfect-number-classifications-5.j | 2 + ...nt-and-perfect-number-classifications.math | 7 + ...ent-and-perfect-number-classifications.pli | 56 +++ ...-and-perfect-number-classifications.pascal | 11 + ...ent-and-perfect-number-classifications.pl6 | 8 + ...nt-and-perfect-number-classifications-1.pl | 2 + ...nt-and-perfect-number-classifications-2.pl | 4 + ...nt-and-perfect-number-classifications-1.py | 15 + ...nt-and-perfect-number-classifications-2.py | 26 + .../README | 1 + ...ent-and-perfect-number-classifications.rkt | 26 + ...ient-and-perfect-number-classifications.rb | 3 + ...t-and-perfect-number-classifications.scala | 6 + ...ient-and-perfect-number-classifications.vb | 23 + .../00DESCRIPTION | 29 ++ .../D/aliquot-sequence-classifications.d | 51 ++ .../aliquot-sequence-classifications.hs | 41 ++ .../J/aliquot-sequence-classifications-1.j | 5 + .../J/aliquot-sequence-classifications-2.j | 27 ++ .../aliquot-sequence-classifications.pl6 | 34 ++ .../Perl/aliquot-sequence-classifications.pl | 36 ++ .../aliquot-sequence-classifications.py | 41 ++ Task/Aliquot-sequence-classifications/README | 1 + .../aliquot-sequence-classifications.rexx | 62 +++ .../aliquot-sequence-classifications.rkt | 53 ++ .../Ruby/aliquot-sequence-classifications.rb | 29 ++ .../aliquot-sequence-classifications.scala | 20 + Task/Almost-prime/00DESCRIPTION | 8 + Task/Almost-prime/00META.yaml | 2 + Task/Almost-prime/Ada/almost-prime.ada | 25 + Task/Almost-prime/AutoHotkey/almost-prime.ahk | 27 ++ Task/Almost-prime/C-sharp/almost-prime.cs | 55 +++ Task/Almost-prime/C/almost-prime.c | 30 ++ .../Common-Lisp/almost-prime.lisp | 13 + Task/Almost-prime/D/almost-prime.d | 36 ++ Task/Almost-prime/Go/almost-prime.go | 36 ++ Task/Almost-prime/Haskell/almost-prime.hs | 18 + Task/Almost-prime/Icon/almost-prime.icon | 10 + Task/Almost-prime/J/almost-prime.j | 6 + Task/Almost-prime/Julia/almost-prime.julia | 10 + .../Mathematica/almost-prime.math | 14 + Task/Almost-prime/Objeck/almost-prime.objeck | 27 ++ Task/Almost-prime/PARI-GP/almost-prime.pari | 2 + Task/Almost-prime/Pascal/almost-prime.pascal | 26 + Task/Almost-prime/Perl-6/almost-prime-1.pl6 | 11 + Task/Almost-prime/Perl-6/almost-prime-2.pl6 | 5 + Task/Almost-prime/Perl/almost-prime-1.pl | 7 + Task/Almost-prime/Perl/almost-prime-2.pl | 64 +++ Task/Almost-prime/PicoLisp/almost-prime.l | 27 ++ Task/Almost-prime/Prolog/almost-prime-1.pro | 20 + Task/Almost-prime/Prolog/almost-prime-2.pro | 40 ++ Task/Almost-prime/Prolog/almost-prime-3.pro | 28 ++ Task/Almost-prime/Python/almost-prime.py | 19 + Task/Almost-prime/README | 1 + Task/Almost-prime/REXX/almost-prime-1.rexx | 33 ++ Task/Almost-prime/REXX/almost-prime-2.rexx | 35 ++ Task/Almost-prime/Racket/almost-prime.rkt | 25 + Task/Almost-prime/Ruby/almost-prime-1.rb | 12 + Task/Almost-prime/Ruby/almost-prime-2.rb | 4 + Task/Almost-prime/Rust/almost-prime.rust | 39 ++ Task/Almost-prime/Scala/almost-prime.scala | 16 + Task/Almost-prime/Tcl/almost-prime.tcl | 31 ++ Task/Amb/00DESCRIPTION | 17 + Task/Amb/ALGOL-68/amb.alg | 38 ++ Task/Amb/Ada/amb.ada | 70 +++ Task/Amb/AutoHotkey/amb.ahk | 16 + Task/Amb/Bracmat/amb.bracmat | 23 + Task/Amb/C-sharp/amb-1.cs | 152 ++++++ Task/Amb/C-sharp/amb-2.cs | 30 ++ Task/Amb/C/amb.c | 41 ++ Task/Amb/Clojure/amb.clj | 12 + Task/Amb/Common-Lisp/amb-1.lisp | 35 ++ Task/Amb/Common-Lisp/amb-2.lisp | 50 ++ Task/Amb/D/amb.d | 47 ++ Task/Amb/E/amb-1.e | 81 ++++ Task/Amb/E/amb-2.e | 18 + Task/Amb/Ela/amb-1.ela | 15 + Task/Amb/Ela/amb-2.ela | 6 + Task/Amb/Elena/amb.elena | 125 +++++ Task/Amb/Factor/amb.factor | 20 + Task/Amb/Go/amb-1.go | 49 ++ Task/Amb/Go/amb-2.go | 39 ++ Task/Amb/Haskell/amb.hs | 15 + Task/Amb/Haxe/amb.haxe | 73 +++ Task/Amb/Icon/amb.icon | 18 + Task/Amb/J/amb-1.j | 5 + Task/Amb/J/amb-2.j | 4 + Task/Amb/J/amb-3.j | 10 + Task/Amb/JavaScript/amb.js | 53 ++ Task/Amb/Lua/amb-1.lua | 21 + Task/Amb/Lua/amb-2.lua | 8 + Task/Amb/Mathematica/amb-1.math | 3 + Task/Amb/Mathematica/amb-2.math | 1 + Task/Amb/Mathematica/amb-3.math | 1 + Task/Amb/Mercury/amb-1.mercury | 25 + Task/Amb/Mercury/amb-2.mercury | 6 + Task/Amb/NetRexx/amb.netrexx | 71 +++ Task/Amb/OCaml/amb-1.ocaml | 36 ++ Task/Amb/OCaml/amb-2.ocaml | 51 ++ Task/Amb/OpenEdge-Progress/amb.openedge | 36 ++ Task/Amb/Oz/amb.oz | 27 ++ Task/Amb/PARI-GP/amb.pari | 16 + Task/Amb/PL-I/amb.pli | 86 ++++ Task/Amb/Perl-6/amb-1.pl6 | 18 + Task/Amb/Perl-6/amb-2.pl6 | 18 + Task/Amb/Perl/amb-1.pl | 35 ++ Task/Amb/Perl/amb-2.pl | 40 ++ Task/Amb/PicoLisp/amb.l | 18 + Task/Amb/Prolog/amb.pro | 17 + Task/Amb/PureBasic/amb.purebasic | 44 ++ Task/Amb/Python/amb.py | 100 ++++ Task/Amb/R/amb-1.r | 23 + Task/Amb/R/amb-2.r | 14 + Task/Amb/README | 1 + Task/Amb/REXX/amb-1.rexx | 22 + Task/Amb/REXX/amb-2.rexx | 85 ++++ Task/Amb/Racket/amb.rkt | 30 ++ Task/Amb/Ruby/amb.rb | 47 ++ Task/Amb/SETL/amb-1.setl | 15 + Task/Amb/SETL/amb-2.setl | 26 + Task/Amb/Scala/amb.scala | 20 + Task/Amb/Scheme/amb.ss | 34 ++ Task/Amb/Seed7/amb.seed7 | 51 ++ Task/Amb/TUSCRIPT/amb.tu | 22 + Task/Amb/TXR/amb-1.txr | 24 + Task/Amb/TXR/amb-2.txr | 24 + Task/Amb/Tcl/amb-1.tcl | 24 + Task/Amb/Tcl/amb-2.tcl | 41 ++ Task/Amb/VBScript/amb-1.vb | 11 + Task/Amb/VBScript/amb-2.vb | 17 + Task/Amicable-pairs/00DESCRIPTION | 11 + .../AutoHotkey/amicable-pairs.ahk | 53 ++ Task/Amicable-pairs/C/amicable-pairs.c | 41 ++ Task/Amicable-pairs/D/amicable-pairs.d | 14 + Task/Amicable-pairs/Haskell/amicable-pairs.hs | 10 + Task/Amicable-pairs/J/amicable-pairs-1.j | 2 + Task/Amicable-pairs/J/amicable-pairs-2.j | 9 + .../Mathematica/amicable-pairs.math | 5 + .../PARI-GP/amicable-pairs.pari | 1 + Task/Amicable-pairs/PL-I/amicable-pairs.pli | 60 +++ .../Pascal/amicable-pairs-1.pascal | 232 +++++++++ .../Pascal/amicable-pairs-2.pascal | 210 ++++++++ Task/Amicable-pairs/Perl-6/amicable-pairs.pl6 | 11 + Task/Amicable-pairs/Perl/amicable-pairs.pl | 5 + Task/Amicable-pairs/Python/amicable-pairs.py | 12 + Task/Amicable-pairs/README | 1 + .../Amicable-pairs/REXX/amicable-pairs-1.rexx | 39 ++ .../Amicable-pairs/REXX/amicable-pairs-2.rexx | 28 ++ Task/Amicable-pairs/Racket/amicable-pairs.rkt | 31 ++ Task/Amicable-pairs/Ruby/amicable-pairs.rb | 5 + .../Amicable-pairs/Scala/amicable-pairs.scala | 5 + Task/Amicable-pairs/Tcl/amicable-pairs.tcl | 41 ++ .../Amicable-pairs/VBScript/amicable-pairs.vb | 36 ++ .../00DESCRIPTION | 58 +++ .../00META.yaml | 0 ...ppend-a-record-to-the-end-of-a-text-file.c | 53 ++ ...pend-a-record-to-the-end-of-a-text-file.go | 101 ++++ ...-record-to-the-end-of-a-text-file-1.groovy | 68 +++ ...-record-to-the-end-of-a-text-file-2.groovy | 21 + ...nd-a-record-to-the-end-of-a-text-file-1.hs | 29 ++ ...nd-a-record-to-the-end-of-a-text-file-2.hs | 14 + ...nd-a-record-to-the-end-of-a-text-file.icon | 13 + ...ppend-a-record-to-the-end-of-a-text-file.j | 43 ++ ...nd-a-record-to-the-end-of-a-text-file.java | 119 +++++ ...ppend-a-record-to-the-end-of-a-text-file.m | 58 +++ ...pend-a-record-to-the-end-of-a-text-file.pl | 106 ++++ ...ppend-a-record-to-the-end-of-a-text-file.l | 27 ++ ...pend-a-record-to-the-end-of-a-text-file.py | 48 ++ .../README | 1 + ...nd-a-record-to-the-end-of-a-text-file.rexx | 48 ++ ...-record-to-the-end-of-a-text-file-1.rapidq | 28 ++ ...-record-to-the-end-of-a-text-file-2.rapidq | 145 ++++++ ...pend-a-record-to-the-end-of-a-text-file.rb | 36 ++ ...d-a-record-to-the-end-of-a-text-file.scala | 56 +++ ...end-a-record-to-the-end-of-a-text-file.tcl | 85 ++++ ...pend-a-record-to-the-end-of-a-text-file.sh | 49 ++ .../00DESCRIPTION | 17 + ...arithmetic-geometric-mean-calculate-pi.cpp | 35 ++ .../arithmetic-geometric-mean-calculate-pi.c | 42 ++ .../arithmetic-geometric-mean-calculate-pi.hs | 33 ++ .../arithmetic-geometric-mean-calculate-pi.j | 25 + ...rithmetic-geometric-mean-calculate-pi.math | 8 + ...rithmetic-geometric-mean-calculate-pi.pari | 2 + ...arithmetic-geometric-mean-calculate-pi.pl6 | 24 + ...rithmetic-geometric-mean-calculate-pi-1.pl | 23 + ...rithmetic-geometric-mean-calculate-pi-2.pl | 17 + .../arithmetic-geometric-mean-calculate-pi.l | 21 + .../arithmetic-geometric-mean-calculate-pi.py | 13 + .../README | 1 + ...thmetic-geometric-mean-calculate-pi-1.rexx | 21 + ...thmetic-geometric-mean-calculate-pi-2.rexx | 24 + ...thmetic-geometric-mean-calculate-pi-3.rexx | 48 ++ ...arithmetic-geometric-mean-calculate-pi.rkt | 23 + .../arithmetic-geometric-mean-calculate-pi.rb | 20 + ...arithmetic-geometric-mean-calculate-pi.tcl | 23 + Task/Benfords-law/00DESCRIPTION | 18 + Task/Benfords-law/AWK/benfords-law.awk | 27 ++ Task/Benfords-law/Ada/benfords-law-1.ada | 49 ++ Task/Benfords-law/Ada/benfords-law-2.ada | 1 + Task/Benfords-law/Aime/benfords-law.aime | 95 ++++ Task/Benfords-law/AutoHotkey/benfords-law.ahk | 43 ++ Task/Benfords-law/C++/benfords-law.cpp | 62 +++ Task/Benfords-law/C/benfords-law.c | 64 +++ .../CoffeeScript/benfords-law.coffee | 21 + .../Common-Lisp/benfords-law.lisp | 43 ++ Task/Benfords-law/D/benfords-law-1.d | 24 + Task/Benfords-law/D/benfords-law-2.d | 18 + Task/Benfords-law/Erlang/benfords-law.erl | 25 + Task/Benfords-law/Forth/benfords-law.fth | 44 ++ Task/Benfords-law/Fortran/benfords-law-1.f | 9 + Task/Benfords-law/Fortran/benfords-law-2.f | 69 +++ Task/Benfords-law/Go/benfords-law.go | 31 ++ Task/Benfords-law/Haskell/benfords-law.hs | 17 + Task/Benfords-law/Icon/benfords-law.icon | 34 ++ Task/Benfords-law/J/benfords-law.j | 36 ++ Task/Benfords-law/Java/benfords-law.java | 41 ++ Task/Benfords-law/Julia/benfords-law.julia | 5 + .../Liberty-BASIC/benfords-law.liberty | 35 ++ Task/Benfords-law/Lua/benfords-law.lua | 20 + .../Mathematica/benfords-law.math | 3 + .../Benfords-law/NetRexx/benfords-law.netrexx | 41 ++ Task/Benfords-law/PARI-GP/benfords-law.pari | 9 + Task/Benfords-law/PL-I/benfords-law.pli | 39 ++ Task/Benfords-law/PL-pgSQL/benfords-law.sql | 34 ++ Task/Benfords-law/Perl-6/benfords-law.pl6 | 14 + Task/Benfords-law/Perl/benfords-law.pl | 25 + Task/Benfords-law/Prolog/benfords-law.pro | 44 ++ Task/Benfords-law/Python/benfords-law.py | 39 ++ Task/Benfords-law/R/benfords-law.r | 31 ++ Task/Benfords-law/README | 1 + Task/Benfords-law/REXX/benfords-law.rexx | 33 ++ Task/Benfords-law/Racket/benfords-law.rkt | 36 ++ Task/Benfords-law/Ruby/benfords-law.rb | 37 ++ Task/Benfords-law/Run-BASIC/benfords-law.run | 30 ++ Task/Benfords-law/SQL/benfords-law.sql | 43 ++ Task/Benfords-law/Scala/benfords-law.scala | 29 ++ Task/Benfords-law/Tcl/benfords-law-1.tcl | 19 + Task/Benfords-law/Tcl/benfords-law-2.tcl | 7 + Task/Bernoulli-numbers/00DESCRIPTION | 23 + Task/Bernoulli-numbers/00META.yaml | 2 + Task/Bernoulli-numbers/C/bernoulli-numbers.c | 51 ++ .../Common-Lisp/bernoulli-numbers.lisp | 43 ++ Task/Bernoulli-numbers/D/bernoulli-numbers.d | 18 + .../Bernoulli-numbers/Go/bernoulli-numbers.go | 33 ++ .../Haskell/bernoulli-numbers.hs | 17 + .../Icon/bernoulli-numbers.icon | 20 + .../Bernoulli-numbers/J/bernoulli-numbers-1.j | 3 + .../Bernoulli-numbers/J/bernoulli-numbers-2.j | 34 ++ .../Maple/bernoulli-numbers.maple | 11 + .../Mathematica/bernoulli-numbers-1.math | 11 + .../Mathematica/bernoulli-numbers-2.math | 2 + .../PARI-GP/bernoulli-numbers.pari | 1 + .../PL-I/bernoulli-numbers.pli | 33 ++ .../Perl-6/bernoulli-numbers-1.pl6 | 17 + .../Perl-6/bernoulli-numbers-2.pl6 | 18 + .../Perl-6/bernoulli-numbers-3.pl6 | 7 + .../Perl/bernoulli-numbers-1.pl | 24 + .../Perl/bernoulli-numbers-2.pl | 6 + .../Perl/bernoulli-numbers-3.pl | 6 + .../PicoLisp/bernoulli-numbers.l | 74 +++ .../Python/bernoulli-numbers-1.py | 15 + .../Python/bernoulli-numbers-2.py | 14 + Task/Bernoulli-numbers/README | 1 + .../REXX/bernoulli-numbers.rexx | 53 ++ .../Racket/bernoulli-numbers.rkt | 84 ++++ .../Ruby/bernoulli-numbers.rb | 13 + .../Tcl/bernoulli-numbers.tcl | 26 + .../00DESCRIPTION | 22 + .../C/bitcoin-public-point-to-address.c | 75 +++ .../D/bitcoin-public-point-to-address.d | 58 +++ .../Go/bitcoin-public-point-to-address.go | 101 ++++ .../bitcoin-public-point-to-address.pl6 | 26 + .../Perl/bitcoin-public-point-to-address.pl | 30 ++ Task/Bitcoin-public-point-to-address/README | 1 + .../bitcoin-public-point-to-address.rkt | 120 +++++ .../Ruby/bitcoin-public-point-to-address.rb | 21 + .../Tcl/bitcoin-public-point-to-address-1.tcl | 29 ++ .../Tcl/bitcoin-public-point-to-address-2.tcl | 3 + Task/CSV-data-manipulation/00DESCRIPTION | 19 + .../AWK/csv-data-manipulation.awk | 13 + .../AutoHotkey/csv-data-manipulation.ahk | 7 + .../C++/csv-data-manipulation.cpp | 129 +++++ .../C-sharp/csv-data-manipulation.cs | 108 +++++ .../Clojure/csv-data-manipulation.clj | 14 + .../Common-Lisp/csv-data-manipulation.lisp | 35 ++ .../D/csv-data-manipulation.d | 10 + .../Erlang/csv-data-manipulation.erl | 36 ++ .../Forth/csv-data-manipulation.fth | 49 ++ .../Go/csv-data-manipulation.go | 79 +++ .../Groovy/csv-data-manipulation.groovy | 8 + .../Haskell/csv-data-manipulation.hs | 34 ++ .../Icon/csv-data-manipulation.icon | 11 + .../J/csv-data-manipulation-1.j | 3 + .../J/csv-data-manipulation-2.j | 4 + .../J/csv-data-manipulation-3.j | 5 + .../J/csv-data-manipulation-4.j | 2 + .../Java/csv-data-manipulation-1.java | 104 ++++ .../Java/csv-data-manipulation-2.java | 125 +++++ .../Lua/csv-data-manipulation.lua | 31 ++ .../MATLAB/csv-data-manipulation.m | 13 + .../Maple/csv-data-manipulation-1.maple | 3 + .../Maple/csv-data-manipulation-2.maple | 24 + .../Mathematica/csv-data-manipulation.math | 9 + .../NetRexx/csv-data-manipulation.netrexx | 122 +++++ .../PHP/csv-data-manipulation.php | 36 ++ .../PL-I/csv-data-manipulation.pli | 65 +++ .../Perl-6/csv-data-manipulation-1.pl6 | 10 + .../Perl-6/csv-data-manipulation-2.pl6 | 5 + .../Perl/csv-data-manipulation-1.pl | 38 ++ .../Perl/csv-data-manipulation-2.pl | 25 + .../PicoLisp/csv-data-manipulation.l | 4 + .../Prolog/csv-data-manipulation.pro | 22 + .../Python/csv-data-manipulation.py | 11 + .../R/csv-data-manipulation-1.r | 10 + .../R/csv-data-manipulation-2.r | 1 + Task/CSV-data-manipulation/README | 1 + .../REXX/csv-data-manipulation.rexx | 24 + .../Racket/csv-data-manipulation-1.rkt | 17 + .../Racket/csv-data-manipulation-2.rkt | 8 + .../Ruby/csv-data-manipulation.rb | 12 + .../Run-BASIC/csv-data-manipulation.run | 34 ++ .../Scala/csv-data-manipulation.scala | 28 ++ .../Seed7/csv-data-manipulation.seed7 | 17 + .../TUSCRIPT/csv-data-manipulation.tu | 18 + .../Tcl/csv-data-manipulation.tcl | 29 ++ .../UNIX-Shell/csv-data-manipulation.sh | 20 + .../csv-data-manipulation.vedit | 11 + .../00DESCRIPTION | 26 + .../00META.yaml | 2 + .../calendar---for-real-programmers.alg | 108 +++++ .../Ada/calendar---for-real-programmers.ada | 21 + .../calendar---for-real-programmers-1.ahk | 39 ++ .../calendar---for-real-programmers-2.ahk | 16 + .../calendar---for-real-programmers.bbc | 47 ++ .../D/calendar---for-real-programmers.d | 1 + .../calendar---for-real-programmers.elena | 139 ++++++ .../calendar---for-real-programmers.guiss | 1 + .../calendar---for-real-programmers-1.icon | 48 ++ .../calendar---for-real-programmers-2.icon | 25 + .../J/calendar---for-real-programmers-1.j | 10 + .../J/calendar---for-real-programmers-2.j | 22 + .../PHP/calendar---for-real-programmers.php | 20 + .../PL-I/calendar---for-real-programmers.pli | 52 ++ .../calendar---for-real-programmers.pl6 | 4 + .../Perl/calendar---for-real-programmers-1.pl | 44 ++ .../Perl/calendar---for-real-programmers-2.pl | 1 + .../calendar---for-real-programmers.l | 14 + Task/Calendar---for-REAL-programmers/README | 1 + .../REXX/calendar---for-real-programmers.rexx | 170 +++++++ .../calendar---for-real-programmers.rkt | 35 ++ .../Ruby/calendar---for-real-programmers-1.rb | 26 + .../Ruby/calendar---for-real-programmers-2.rb | 84 ++++ .../calendar---for-real-programmers.seed7 | 13 + .../Tcl/calendar---for-real-programmers.tcl | 48 ++ .../calendar---for-real-programmers.vedit | 65 +++ .../calendar---for-real-programmers.x86 | 187 +++++++ Task/Casting-out-nines/00DESCRIPTION | 20 + Task/Casting-out-nines/00META.yaml | 3 + .../C++/casting-out-nines-1.cpp | 20 + .../C++/casting-out-nines-2.cpp | 44 ++ .../C++/casting-out-nines-3.cpp | 5 + .../C++/casting-out-nines-4.cpp | 5 + .../C++/casting-out-nines-5.cpp | 5 + .../Common-Lisp/casting-out-nines.lisp | 15 + Task/Casting-out-nines/D/casting-out-nines.d | 27 ++ .../Casting-out-nines/Go/casting-out-nines.go | 168 +++++++ .../Casting-out-nines/J/casting-out-nines-1.j | 3 + .../Casting-out-nines/J/casting-out-nines-2.j | 2 + .../Casting-out-nines/J/casting-out-nines-3.j | 3 + .../Casting-out-nines/J/casting-out-nines-4.j | 4 + .../Casting-out-nines/J/casting-out-nines-5.j | 2 + .../Casting-out-nines/J/casting-out-nines-6.j | 3 + .../Julia/casting-out-nines.julia | 3 + .../Objeck/casting-out-nines.objeck | 20 + .../PARI-GP/casting-out-nines.pari | 11 + .../Perl-6/casting-out-nines.pl6 | 16 + .../Perl/casting-out-nines.pl | 33 ++ .../PicoLisp/casting-out-nines.l | 36 ++ .../Python/casting-out-nines.py | 19 + Task/Casting-out-nines/README | 1 + .../REXX/casting-out-nines.rexx | 43 ++ .../Racket/casting-out-nines.rkt | 11 + .../Seed7/casting-out-nines.seed7 | 37 ++ .../Tcl/casting-out-nines.tcl | 39 ++ .../00DESCRIPTION | 4 + .../catalan-numbers-pascals-triangle.360 | 91 ++++ .../Ada/catalan-numbers-pascals-triangle.ada | 14 + .../catalan-numbers-pascals-triangle.ahk | 30 ++ .../catalan-numbers-pascals-triangle.bat | 22 + .../C++/catalan-numbers-pascals-triangle.cpp | 16 + .../D/catalan-numbers-pascals-triangle.d | 16 + .../catalan-numbers-pascals-triangle.icon | 6 + .../J/catalan-numbers-pascals-triangle-1.j | 1 + .../J/catalan-numbers-pascals-triangle-2.j | 2 + .../J/catalan-numbers-pascals-triangle-3.j | 17 + .../MATLAB/catalan-numbers-pascals-triangle.m | 2 + .../catalan-numbers-pascals-triangle.math | 16 + .../catalan-numbers-pascals-triangle.pari | 1 + .../catalan-numbers-pascals-triangle.pascal | 35 ++ .../catalan-numbers-pascals-triangle.pl6 | 9 + .../catalan-numbers-pascals-triangle-1.pl | 8 + .../catalan-numbers-pascals-triangle-2.pl | 2 + .../catalan-numbers-pascals-triangle.l | 14 + .../catalan-numbers-pascals-triangle-1.py | 12 + .../catalan-numbers-pascals-triangle-2.py | 9 + Task/Catalan-numbers-Pascals-triangle/README | 1 + .../catalan-numbers-pascals-triangle-1.rexx | 10 + .../catalan-numbers-pascals-triangle-2.rexx | 14 + .../catalan-numbers-pascals-triangle-3.rexx | 13 + .../catalan-numbers-pascals-triangle-4.rexx | 15 + .../catalan-numbers-pascals-triangle.rkt | 11 + .../Ruby/catalan-numbers-pascals-triangle.rb | 11 + .../catalan-numbers-pascals-triangle.run | 9 + .../catalan-numbers-pascals-triangle.scilab | 13 + .../catalan-numbers-pascals-triangle.seed7 | 21 + .../catalan-numbers-pascals-triangle.ti-83 | 14 + .../Tcl/catalan-numbers-pascals-triangle.tcl | 13 + .../catalan-numbers-pascals-triangle.vb | 20 + .../catalan-numbers-pascals-triangle.vb | 16 + Task/Catamorphism/00DESCRIPTION | 7 + Task/Catamorphism/Ada/catamorphism.ada | 29 ++ .../Catamorphism/Bracmat/catamorphism.bracmat | 18 + Task/Catamorphism/C++/catamorphism.cpp | 14 + Task/Catamorphism/C-sharp/catamorphism.cs | 9 + Task/Catamorphism/C/catamorphism.c | 24 + Task/Catamorphism/Clojure/catamorphism.clj | 6 + .../Common-Lisp/catamorphism.lisp | 18 + Task/Catamorphism/D/catamorphism.d | 13 + Task/Catamorphism/Deja-Vu/catamorphism.djv | 8 + Task/Catamorphism/Go/catamorphism.go | 25 + Task/Catamorphism/Haskell/catamorphism.hs | 5 + Task/Catamorphism/Icon/catamorphism.icon | 9 + Task/Catamorphism/J/catamorphism-1.j | 1 + Task/Catamorphism/J/catamorphism-2.j | 6 + Task/Catamorphism/Java/catamorphism.java | 9 + Task/Catamorphism/JavaScript/catamorphism.js | 17 + Task/Catamorphism/LOLCODE/catamorphism.lol | 27 ++ .../Catamorphism/Logtalk/catamorphism.logtalk | 14 + Task/Catamorphism/Maple/catamorphism-1.maple | 8 + Task/Catamorphism/Maple/catamorphism-2.maple | 2 + .../Mathematica/catamorphism.math | 1 + .../Catamorphism/Maxima/catamorphism-1.maxima | 2 + .../Catamorphism/Maxima/catamorphism-2.maxima | 2 + .../Catamorphism/Nemerle/catamorphism.nemerle | 2 + Task/Catamorphism/OCaml/catamorphism.ocaml | 6 + .../Oberon-2/catamorphism.oberon-2 | 72 +++ Task/Catamorphism/PARI-GP/catamorphism-1.pari | 6 + Task/Catamorphism/PARI-GP/catamorphism-2.pari | 1 + Task/Catamorphism/Pascal/catamorphism.pascal | 53 ++ Task/Catamorphism/Perl-6/catamorphism-1.pl6 | 7 + Task/Catamorphism/Perl-6/catamorphism-2.pl6 | 6 + Task/Catamorphism/Perl/catamorphism.pl | 8 + Task/Catamorphism/PicoLisp/catamorphism.l | 11 + Task/Catamorphism/Prolog/catamorphism.pro | 14 + Task/Catamorphism/Python/catamorphism-1.py | 18 + Task/Catamorphism/Python/catamorphism-2.py | 12 + Task/Catamorphism/README | 1 + Task/Catamorphism/REXX/catamorphism.rexx | 36 ++ Task/Catamorphism/Racket/catamorphism.rkt | 8 + Task/Catamorphism/Ruby/catamorphism-1.rb | 4 + Task/Catamorphism/Ruby/catamorphism-2.rb | 11 + Task/Catamorphism/Run-BASIC/catamorphism.run | 28 ++ Task/Catamorphism/Standard-ML/catamorphism.ml | 6 + Task/Catamorphism/Tcl/catamorphism-1.tcl | 7 + Task/Catamorphism/Tcl/catamorphism-2.tcl | 5 + Task/Catamorphism/Tcl/catamorphism-3.tcl | 3 + .../Character-matching/D/character-matching.d | 16 - .../Elena/character-matching.elena | 22 - .../Perl/character-matching.pl | 8 - Task/Character-matching/README | 1 - .../REXX/character-matching.rexx | 36 -- Task/Chinese-remainder-theorem/00DESCRIPTION | 30 ++ .../Ada/chinese-remainder-theorem.ada | 20 + .../Bracmat/chinese-remainder-theorem.bracmat | 38 ++ .../C/chinese-remainder-theorem.c | 39 ++ .../chinese-remainder-theorem.lisp | 9 + .../D/chinese-remainder-theorem.d | 40 ++ .../Erlang/chinese-remainder-theorem.erl | 41 ++ .../Forth/chinese-remainder-theorem.fth | 38 ++ .../Go/chinese-remainder-theorem.go | 39 ++ .../Haskell/chinese-remainder-theorem.hs | 22 + .../Icon/chinese-remainder-theorem.icon | 24 + .../J/chinese-remainder-theorem-1.j | 1 + .../J/chinese-remainder-theorem-2.j | 4 + .../Maple/chinese-remainder-theorem.maple | 2 + .../chinese-remainder-theorem.math | 2 + .../OCaml/chinese-remainder-theorem.ocaml | 40 ++ .../PARI-GP/chinese-remainder-theorem-1.pari | 8 + .../PARI-GP/chinese-remainder-theorem-2.pari | 1 + .../PARI-GP/chinese-remainder-theorem-3.pari | 3 + .../Perl-6/chinese-remainder-theorem.pl6 | 25 + .../Perl/chinese-remainder-theorem-1.pl | 2 + .../Perl/chinese-remainder-theorem-2.pl | 3 + .../Perl/chinese-remainder-theorem-3.pl | 2 + .../PicoLisp/chinese-remainder-theorem.l | 29 ++ .../Python/chinese-remainder-theorem.py | 23 + .../R/chinese-remainder-theorem.r | 44 ++ Task/Chinese-remainder-theorem/README | 1 + .../REXX/chinese-remainder-theorem-1.rexx | 24 + .../REXX/chinese-remainder-theorem-2.rexx | 26 + .../Racket/chinese-remainder-theorem.rkt | 5 + .../Ruby/chinese-remainder-theorem.rb | 8 + .../Seed7/chinese-remainder-theorem.seed7 | 24 + .../Tcl/chinese-remainder-theorem.tcl | 18 + .../00DESCRIPTION | 19 + ...s-of-given-radius-through-two-points-1.ahk | 17 + ...s-of-given-radius-through-two-points-2.ahk | 14 + ...s-of-given-radius-through-two-points.basic | 37 ++ ...rcles-of-given-radius-through-two-points.c | 63 +++ ...rcles-of-given-radius-through-two-points.d | 62 +++ ...rcles-of-given-radius-through-two-points.f | 104 ++++ ...cles-of-given-radius-through-two-points.go | 74 +++ ...cles-of-given-radius-through-two-points.hs | 36 ++ ...es-of-given-radius-through-two-points.icon | 22 + ...rcles-of-given-radius-through-two-points.j | 38 ++ ...f-given-radius-through-two-points-1.maxima | 43 ++ ...f-given-radius-through-two-points-2.maxima | 13 + ...es-of-given-radius-through-two-points.pari | 10 + ...les-of-given-radius-through-two-points.pli | 42 ++ ...s-of-given-radius-through-two-points-1.pl6 | 21 + ...s-of-given-radius-through-two-points-2.pl6 | 14 + ...cles-of-given-radius-through-two-points.py | 45 ++ .../README | 1 + ...es-of-given-radius-through-two-points.rexx | 31 ++ ...s-of-given-radius-through-two-points-1.rkt | 24 + ...s-of-given-radius-through-two-points-2.rkt | 15 + ...cles-of-given-radius-through-two-points.rb | 37 ++ ...es-of-given-radius-through-two-points.rust | 58 +++ ...s-of-given-radius-through-two-points.seed7 | 70 +++ ...s-of-given-radius-through-two-points-1.tcl | 32 ++ ...s-of-given-radius-through-two-points-2.tcl | 16 + ...es-of-given-radius-through-two-points.xpl0 | 25 + Task/Closures-Value-capture/00DESCRIPTION | 11 + .../ALGOL-68/closures-value-capture.alg | 11 + .../Ada/closures-value-capture.ada | 30 ++ .../Axiom/closures-value-capture-1.axiom | 5 + .../Axiom/closures-value-capture-2.axiom | 1 + .../Axiom/closures-value-capture-3.axiom | 2 + .../Babel/closures-value-capture-1.pb | 10 + .../Babel/closures-value-capture-2.pb | 10 + .../Bracmat/closures-value-capture.bracmat | 8 + .../C++/closures-value-capture.cpp | 12 + .../C/closures-value-capture-1.c | 41 ++ .../C/closures-value-capture-2.c | 9 + .../C/closures-value-capture-3.c | 33 ++ .../closures-value-capture.coffee | 5 + .../Common-Lisp/closures-value-capture.lisp | 9 + .../D/closures-value-capture-1.d | 10 + .../D/closures-value-capture-2.d | 5 + .../Delphi/closures-value-capture.delphi | 19 + .../Emacs-Lisp/closures-value-capture.l | 6 + .../Erlang/closures-value-capture.erl | 13 + .../Factor/closures-value-capture-1.factor | 14 + .../Factor/closures-value-capture-2.factor | 12 + .../Fantom/closures-value-capture.fantom | 17 + .../Go/closures-value-capture.go | 15 + .../Groovy/closures-value-capture-1.groovy | 1 + .../Groovy/closures-value-capture-2.groovy | 4 + .../Haskell/closures-value-capture-1.hs | 1 + .../Haskell/closures-value-capture-2.hs | 1 + .../Haskell/closures-value-capture-3.hs | 1 + .../Haskell/closures-value-capture-4.hs | 8 + .../Icon/closures-value-capture.icon | 15 + .../J/closures-value-capture-1.j | 3 + .../J/closures-value-capture-2.j | 2 + .../J/closures-value-capture-3.j | 4 + .../J/closures-value-capture-4.j | 4 + .../J/closures-value-capture-5.j | 4 + .../J/closures-value-capture-6.j | 9 + .../Java/closures-value-capture-1.java | 15 + .../Java/closures-value-capture-2.java | 17 + .../JavaScript/closures-value-capture-1.js | 7 + .../JavaScript/closures-value-capture-2.js | 9 + .../Julia/closures-value-capture.julia | 1 + .../Logtalk/closures-value-capture-1.logtalk | 15 + .../Logtalk/closures-value-capture-2.logtalk | 12 + .../Lua/closures-value-capture.lua | 6 + .../Maple/closures-value-capture.maple | 5 + .../Mathematica/closures-value-capture.math | 5 + .../Nemerle/closures-value-capture.nemerle | 13 + .../OCaml/closures-value-capture.ocaml | 7 + .../Objective-C/closures-value-capture.m | 7 + .../PARI-GP/closures-value-capture.pari | 1 + .../PHP/closures-value-capture-1.php | 7 + .../PHP/closures-value-capture-2.php | 7 + .../Perl-6/closures-value-capture-1.pl6 | 5 + .../Perl-6/closures-value-capture-2.pl6 | 1 + .../Perl/closures-value-capture.pl | 2 + .../PicoLisp/closures-value-capture.l | 4 + .../Pike/closures-value-capture.pike | 13 + .../Prolog/closures-value-capture.pro | 14 + .../Python/closures-value-capture-1.py | 4 + .../Python/closures-value-capture-2.py | 4 + .../Python/closures-value-capture-3.py | 2 + .../Python/closures-value-capture-4.py | 4 + .../Python/closures-value-capture-5.py | 2 + .../Python/closures-value-capture-6.py | 2 + .../Python/closures-value-capture-7.py | 2 + .../R/closures-value-capture-1.r | 9 + .../R/closures-value-capture-2.r | 2 + .../R/closures-value-capture-3.r | 18 + Task/Closures-Value-capture/README | 1 + .../REXX/closures-value-capture.rexx | 14 + .../Racket/closures-value-capture-1.rkt | 3 + .../Racket/closures-value-capture-2.rkt | 1 + .../Ruby/closures-value-capture-1.rb | 6 + .../Ruby/closures-value-capture-2.rb | 5 + .../Rust/closures-value-capture.rust | 4 + .../Scala/closures-value-capture.scala | 3 + .../Scheme/closures-value-capture-1.ss | 11 + .../Scheme/closures-value-capture-2.ss | 2 + .../Smalltalk/closures-value-capture.st | 2 + .../Tcl/closures-value-capture.tcl | 36 ++ .../00DESCRIPTION | 15 + .../Combinations-and-permutations/00META.yaml | 2 + .../combinations-and-permutations-1.alg | 91 ++++ .../combinations-and-permutations-2.alg | 50 ++ .../combinations-and-permutations.bracmat | 56 +++ .../C/combinations-and-permutations.c | 27 ++ .../D/combinations-and-permutations.d | 26 + .../Icon/combinations-and-permutations.icon | 25 + .../J/combinations-and-permutations-1.j | 2 + .../J/combinations-and-permutations-2.j | 47 ++ .../combinations-and-permutations-1.math | 8 + .../combinations-and-permutations-2.math | 1 + .../Perl-6/combinations-and-permutations.pl6 | 45 ++ .../Perl/combinations-and-permutations.pl | 50 ++ .../Python/combinations-and-permutations.py | 29 ++ Task/Combinations-and-permutations/README | 1 + .../REXX/combinations-and-permutations.rexx | 46 ++ .../Racket/combinations-and-permutations.rkt | 7 + .../Ruby/combinations-and-permutations.rb | 38 ++ .../Tcl/combinations-and-permutations-1.tcl | 25 + .../Tcl/combinations-and-permutations-2.tcl | 26 + Task/Comma-quibbling/00DESCRIPTION | 15 + Task/Comma-quibbling/AWK/comma-quibbling.awk | 13 + Task/Comma-quibbling/Ada/comma-quibbling.ada | 17 + .../AutoHotkey/comma-quibbling.ahk | 18 + Task/Comma-quibbling/C++/comma-quibbling.cpp | 26 + Task/Comma-quibbling/C/comma-quibbling.c | 53 ++ .../COBOL/comma-quibbling.cobol | 75 +++ .../Clojure/comma-quibbling.clj | 18 + .../CoffeeScript/comma-quibbling.coffee | 9 + .../Common-Lisp/comma-quibbling.lisp | 7 + Task/Comma-quibbling/D/comma-quibbling-1.d | 17 + Task/Comma-quibbling/D/comma-quibbling-2.d | 10 + .../Deja-Vu/comma-quibbling.djv | 15 + .../Erlang/comma-quibbling.erl | 17 + Task/Comma-quibbling/Go/comma-quibbling.go | 30 ++ .../Groovy/comma-quibbling-1.groovy | 1 + .../Groovy/comma-quibbling-2.groovy | 4 + .../Haskell/comma-quibbling.hs | 9 + .../Comma-quibbling/Icon/comma-quibbling.icon | 9 + Task/Comma-quibbling/J/comma-quibbling-1.j | 3 + Task/Comma-quibbling/J/comma-quibbling-2.j | 6 + Task/Comma-quibbling/J/comma-quibbling-3.j | 2 + .../Comma-quibbling/Java/comma-quibbling.java | 21 + .../JavaScript/comma-quibbling.js | 13 + .../Julia/comma-quibbling.julia | 4 + .../Comma-quibbling/Logo/comma-quibbling.logo | 26 + .../MAXScript/comma-quibbling-1.max | 23 + .../MAXScript/comma-quibbling-2.max | 8 + .../Maple/comma-quibbling-1.maple | 12 + .../Maple/comma-quibbling-2.maple | 11 + .../Mathematica/comma-quibbling.math | 4 + .../NetRexx/comma-quibbling.netrexx | 25 + .../PARI-GP/comma-quibbling.pari | 11 + Task/Comma-quibbling/PHP/comma-quibbling.php | 29 ++ Task/Comma-quibbling/PL-I/comma-quibbling.pli | 46 ++ .../Perl-6/comma-quibbling.pl6 | 6 + .../Comma-quibbling/Perl/comma-quibbling-1.pl | 8 + .../Comma-quibbling/Perl/comma-quibbling-2.pl | 8 + .../PicoLisp/comma-quibbling.l | 8 + .../Prolog/comma-quibbling-1.pro | 18 + .../Prolog/comma-quibbling-2.pro | 6 + .../Python/comma-quibbling-1.py | 12 + .../Python/comma-quibbling-2.py | 5 + .../Python/comma-quibbling-3.py | 15 + Task/Comma-quibbling/README | 1 + .../REBOL/comma-quibbling-1.rebol | 18 + .../REBOL/comma-quibbling-2.rebol | 24 + .../REXX/comma-quibbling-1.rexx | 15 + .../REXX/comma-quibbling-2.rexx | 21 + .../REXX/comma-quibbling-3.rexx | 24 + .../Racket/comma-quibbling.rkt | 11 + Task/Comma-quibbling/Ruby/comma-quibbling.rb | 8 + .../Run-BASIC/comma-quibbling.run | 18 + .../Comma-quibbling/Rust/comma-quibbling.rust | 16 + .../Scala/comma-quibbling.scala | 13 + .../Seed7/comma-quibbling.seed7 | 21 + .../Standard-ML/comma-quibbling.ml | 14 + Task/Comma-quibbling/Tcl/comma-quibbling.tcl | 7 + .../UNIX-Shell/comma-quibbling.sh | 15 + .../Comma-quibbling/XPL0/comma-quibbling.xpl0 | 17 + Task/Conjugate-transpose/00DESCRIPTION | 15 + Task/Conjugate-transpose/00META.yaml | 3 + .../Ada/conjugate-transpose.ada | 47 ++ .../C/conjugate-transpose.c | 184 +++++++ .../D/conjugate-transpose-1.d | 107 ++++ .../D/conjugate-transpose-2.d | 90 ++++ .../Factor/conjugate-transpose.factor | 14 + .../Fortran/conjugate-transpose.f | 64 +++ .../Go/conjugate-transpose.go | 112 +++++ .../J/conjugate-transpose-1.j | 1 + .../J/conjugate-transpose-2.j | 13 + .../J/conjugate-transpose-3.j | 16 + .../Julia/conjugate-transpose-1.julia | 1 + .../Julia/conjugate-transpose-2.julia | 1 + .../Julia/conjugate-transpose-3.julia | 2 + .../Maple/conjugate-transpose.maple | 10 + .../Mathematica/conjugate-transpose.math | 17 + .../PARI-GP/conjugate-transpose.pari | 4 + .../PL-I/conjugate-transpose.pli | 49 ++ .../Python/conjugate-transpose.py | 72 +++ Task/Conjugate-transpose/README | 1 + .../REXX/conjugate-transpose.rexx | 88 ++++ .../Racket/conjugate-transpose-1.rkt | 16 + .../Racket/conjugate-transpose-2.rkt | 6 + .../Racket/conjugate-transpose-3.rkt | 4 + .../Ruby/conjugate-transpose.rb | 25 + .../Tcl/conjugate-transpose-1.tcl | 57 +++ .../Tcl/conjugate-transpose-2.tcl | 52 ++ .../00DESCRIPTION | 16 + .../convert-decimal-number-to-rational-1.ada | 6 + .../convert-decimal-number-to-rational-2.ada | 29 ++ .../convert-decimal-number-to-rational-3.ada | 25 + .../convert-decimal-number-to-rational.ahk | 86 ++++ ...convert-decimal-number-to-rational.bracmat | 72 +++ .../C/convert-decimal-number-to-rational-1.c | 73 +++ .../C/convert-decimal-number-to-rational-2.c | 17 + .../D/convert-decimal-number-to-rational.d | 40 ++ .../Go/convert-decimal-number-to-rational.go | 16 + .../convert-decimal-number-to-rational.hs | 6 + .../J/convert-decimal-number-to-rational-1.j | 2 + .../J/convert-decimal-number-to-rational-2.j | 12 + .../J/convert-decimal-number-to-rational-3.j | 2 + .../J/convert-decimal-number-to-rational-4.j | 6 + .../convert-decimal-number-to-rational.julia | 3 + ...convert-decimal-number-to-rational.liberty | 75 +++ .../convert-decimal-number-to-rational.m | 3 + .../convert-decimal-number-to-rational.maple | 4 + .../convert-decimal-number-to-rational.math | 2 + ...convert-decimal-number-to-rational.netrexx | 61 +++ .../convert-decimal-number-to-rational.pari | 5 + .../convert-decimal-number-to-rational.pli | 54 +++ .../convert-decimal-number-to-rational-1.pl6 | 1 + .../convert-decimal-number-to-rational-2.pl6 | 18 + .../convert-decimal-number-to-rational.pl | 129 +++++ .../convert-decimal-number-to-rational.py | 12 + .../Convert-decimal-number-to-rational/README | 1 + .../convert-decimal-number-to-rational-1.rexx | 27 ++ .../convert-decimal-number-to-rational-2.rexx | 69 +++ .../convert-decimal-number-to-rational-3.rexx | 62 +++ .../convert-decimal-number-to-rational.rkt | 7 + .../convert-decimal-number-to-rational-1.rb | 5 + .../convert-decimal-number-to-rational-2.rb | 5 + .../convert-decimal-number-to-rational.seed7 | 19 + .../convert-decimal-number-to-rational.tcl | 22 + Task/Currying/00DESCRIPTION | 5 + Task/Currying/ALGOL-68/currying.alg | 10 + Task/Currying/C-sharp/currying.cs | 9 + Task/Currying/Common-Lisp/currying-1.lisp | 3 + Task/Currying/Common-Lisp/currying-2.lisp | 3 + Task/Currying/D/currying.d | 11 + Task/Currying/Erlang/currying.erl | 62 +++ Task/Currying/Forth/currying.fth | 6 + Task/Currying/Go/currying.go | 37 ++ Task/Currying/Groovy/currying-1.groovy | 7 + Task/Currying/Groovy/currying-2.groovy | 5 + Task/Currying/Haskell/currying-1.hs | 1 + Task/Currying/Haskell/currying-2.hs | 1 + Task/Currying/Haskell/currying-3.hs | 1 + Task/Currying/Haskell/currying-4.hs | 1 + Task/Currying/Haskell/currying-5.hs | 1 + Task/Currying/Haskell/currying-6.hs | 13 + Task/Currying/Io/currying.io | 12 + Task/Currying/J/currying.j | 7 + Task/Currying/Java/currying.java | 38 ++ Task/Currying/JavaScript/currying.js | 10 + Task/Currying/Nemerle/currying.nemerle | 20 + Task/Currying/OCaml/currying-1.ocaml | 4 + Task/Currying/OCaml/currying-2.ocaml | 2 + Task/Currying/PARI-GP/currying.pari | 2 + Task/Currying/Perl-6/currying.pl6 | 2 + Task/Currying/Perl/currying.pl | 15 + Task/Currying/Python/currying-1.py | 4 + Task/Currying/Python/currying-2.py | 5 + Task/Currying/README | 1 + Task/Currying/REXX/currying-1.rexx | 7 + Task/Currying/REXX/currying-2.rexx | 12 + Task/Currying/Racket/currying-1.rkt | 2 + Task/Currying/Racket/currying-2.rkt | 6 + Task/Currying/Ruby/currying.rb | 13 + Task/Currying/Rust/currying.rust | 9 + Task/Currying/Standard-ML/currying-1.ml | 4 + Task/Currying/Standard-ML/currying-2.ml | 2 + Task/Currying/Tcl/currying.tcl | 2 + .../00DESCRIPTION | 27 ++ .../00META.yaml | 2 + ...gital-root-multiplicative-digital-root.alg | 102 ++++ ...gital-root-multiplicative-digital-root.awk | 76 +++ ...gital-root-multiplicative-digital-root.ada | 47 ++ ...l-root-multiplicative-digital-root.bracmat | 46 ++ ...gital-root-multiplicative-digital-root.cpp | 59 +++ ...digital-root-multiplicative-digital-root.c | 58 +++ ...ital-root-multiplicative-digital-root.lisp | 25 + ...gital-root-multiplicative-digital-root-1.d | 27 ++ ...gital-root-multiplicative-digital-root-2.d | 34 ++ ...gital-root-multiplicative-digital-root-3.d | 36 ++ ...digital-root-multiplicative-digital-root.f | 90 ++++ ...igital-root-multiplicative-digital-root.go | 55 +++ ...igital-root-multiplicative-digital-root.hs | 41 ++ ...ital-root-multiplicative-digital-root.icon | 24 + ...gital-root-multiplicative-digital-root-1.j | 2 + ...gital-root-multiplicative-digital-root-2.j | 2 + ...gital-root-multiplicative-digital-root-3.j | 2 + ...gital-root-multiplicative-digital-root-4.j | 8 + ...gital-root-multiplicative-digital-root-5.j | 11 + ...ital-root-multiplicative-digital-root.java | 51 ++ ...ital-root-multiplicative-digital-root.math | 9 + ...tal-root-multiplicative-digital-root-1.pli | 24 + ...tal-root-multiplicative-digital-root-2.pli | 56 +++ ...gital-root-multiplicative-digital-root.pl6 | 13 + ...igital-root-multiplicative-digital-root.pl | 28 ++ ...ital-root-multiplicative-digital-root-1.py | 25 + ...ital-root-multiplicative-digital-root-2.py | 10 + .../README | 1 + ...al-root-multiplicative-digital-root-1.rexx | 28 ++ ...al-root-multiplicative-digital-root-2.rexx | 72 +++ ...gital-root-multiplicative-digital-root.rkt | 23 + ...igital-root-multiplicative-digital-root.rb | 19 + ...tal-root-multiplicative-digital-root.scala | 27 ++ ...tal-root-multiplicative-digital-root-1.tcl | 9 + ...tal-root-multiplicative-digital-root-2.tcl | 16 + Task/Draw-a-clock/00DESCRIPTION | 7 + Task/Draw-a-clock/AWK/draw-a-clock.awk | 50 ++ .../Draw-a-clock/ActionScript/draw-a-clock.as | 138 ++++++ Task/Draw-a-clock/AutoHotkey/draw-a-clock.ahk | 145 ++++++ Task/Draw-a-clock/C++/draw-a-clock.cpp | 330 +++++++++++++ Task/Draw-a-clock/C/draw-a-clock.c | 93 ++++ Task/Draw-a-clock/Fortran/draw-a-clock.f | 116 +++++ Task/Draw-a-clock/GUISS/draw-a-clock.guiss | 1 + Task/Draw-a-clock/Go/draw-a-clock-1.go | 88 ++++ Task/Draw-a-clock/Go/draw-a-clock-2.go | 101 ++++ Task/Draw-a-clock/Haskell/draw-a-clock.hs | 114 +++++ Task/Draw-a-clock/J/draw-a-clock-1.j | 20 + Task/Draw-a-clock/J/draw-a-clock-2.j | 7 + Task/Draw-a-clock/Java/draw-a-clock.java | 79 +++ Task/Draw-a-clock/JavaScript/draw-a-clock.js | 47 ++ .../Liberty-BASIC/draw-a-clock.liberty | 39 ++ .../Locomotive-Basic/draw-a-clock.locomotive | 46 ++ Task/Draw-a-clock/MATLAB/draw-a-clock.m | 6 + .../Mathematica/draw-a-clock.math | 14 + .../Draw-a-clock/NetRexx/draw-a-clock.netrexx | 102 ++++ Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml | 65 +++ Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml | 66 +++ Task/Draw-a-clock/Perl-6/draw-a-clock.pl6 | 17 + Task/Draw-a-clock/Perl/draw-a-clock.pl | 29 ++ Task/Draw-a-clock/PicoLisp/draw-a-clock.l | 48 ++ .../PureBasic/draw-a-clock.purebasic | 51 ++ Task/Draw-a-clock/Python/draw-a-clock.py | 31 ++ Task/Draw-a-clock/README | 1 + Task/Draw-a-clock/REXX/draw-a-clock.rexx | 59 +++ Task/Draw-a-clock/Racket/draw-a-clock.rkt | 55 +++ Task/Draw-a-clock/Ruby/draw-a-clock-1.rb | 41 ++ Task/Draw-a-clock/Ruby/draw-a-clock-2.rb | 45 ++ Task/Draw-a-clock/Run-BASIC/draw-a-clock.run | 95 ++++ Task/Draw-a-clock/Scala/draw-a-clock-1.scala | 53 ++ Task/Draw-a-clock/Scala/draw-a-clock-2.scala | 50 ++ Task/Draw-a-clock/Seed7/draw-a-clock.seed7 | 71 +++ Task/Draw-a-clock/Tcl/draw-a-clock.tcl | 33 ++ Task/Extensible-prime-generator/00DESCRIPTION | 21 + .../Ada/extensible-prime-generator.ada | 71 +++ .../AutoHotkey/extensible-prime-generator.ahk | 46 ++ .../C/extensible-prime-generator.c | 98 ++++ .../D/extensible-prime-generator-1.d | 12 + .../D/extensible-prime-generator-2.d | 111 +++++ .../Go/extensible-prime-generator-1.go | 86 ++++ .../Go/extensible-prime-generator-2.go | 27 ++ .../Haskell/extensible-prime-generator-1.hs | 26 + .../Haskell/extensible-prime-generator-2.hs | 1 + .../Haskell/extensible-prime-generator-3.hs | 38 ++ .../J/extensible-prime-generator.j | 8 + .../extensible-prime-generator.math | 8 + .../Pascal/extensible-prime-generator.pascal | 459 ++++++++++++++++++ .../Perl-6/extensible-prime-generator.pl6 | 10 + .../Perl/extensible-prime-generator-1.pl | 9 + .../Perl/extensible-prime-generator-2.pl | 12 + .../Perl/extensible-prime-generator-3.pl | 13 + .../Perl/extensible-prime-generator-4.pl | 5 + .../Python/extensible-prime-generator-1.py | 1 + .../Python/extensible-prime-generator-2.py | 16 + Task/Extensible-prime-generator/README | 1 + .../REXX/extensible-prime-generator.rexx | 46 ++ .../Racket/extensible-prime-generator.rkt | 33 ++ .../Ruby/extensible-prime-generator.rb | 6 + .../Seed7/extensible-prime-generator.seed7 | 64 +++ .../Tcl/extensible-prime-generator.tcl | 54 +++ Task/Fibonacci-word-fractal/00DESCRIPTION | 10 + .../AutoHotkey/fibonacci-word-fractal.ahk | 75 +++ .../C++/fibonacci-word-fractal.cpp | 168 +++++++ .../D/fibonacci-word-fractal.d | 22 + .../Icon/fibonacci-word-fractal.icon | 57 +++ .../J/fibonacci-word-fractal-1.j | 2 + .../J/fibonacci-word-fractal-2.j | 1 + .../Logo/fibonacci-word-fractal.logo | 29 ++ .../Mathematica/fibonacci-word-fractal.math | 16 + .../Perl-6/fibonacci-word-fractal.pl6 | 56 +++ .../Perl/fibonacci-word-fractal.pl | 36 ++ .../Python/fibonacci-word-fractal.py | 58 +++ Task/Fibonacci-word-fractal/README | 1 + .../REXX/fibonacci-word-fractal.rexx | 36 ++ .../Racket/fibonacci-word-fractal.rkt | 21 + .../Ruby/fibonacci-word-fractal.rb | 32 ++ .../Scala/fibonacci-word-fractal.scala | 47 ++ .../Tcl/fibonacci-word-fractal.tcl | 44 ++ Task/Fibonacci-word/00DESCRIPTION | 12 + .../ALGOL-68/fibonacci-word.alg | 118 +++++ Task/Fibonacci-word/Ada/fibonacci-word.ada | 56 +++ .../AutoHotkey/fibonacci-word.ahk | 28 ++ Task/Fibonacci-word/C++/fibonacci-word.cpp | 53 ++ Task/Fibonacci-word/C/fibonacci-word.c | 97 ++++ .../Fibonacci-word/Clojure/fibonacci-word.clj | 18 + Task/Fibonacci-word/D/fibonacci-word.d | 23 + Task/Fibonacci-word/Go/fibonacci-word.go | 61 +++ Task/Fibonacci-word/Haskell/fibonacci-word.hs | 25 + Task/Fibonacci-word/Icon/fibonacci-word.icon | 27 ++ Task/Fibonacci-word/J/fibonacci-word-1.j | 1 + Task/Fibonacci-word/J/fibonacci-word-2.j | 1 + Task/Fibonacci-word/J/fibonacci-word-3.j | 38 ++ Task/Fibonacci-word/Java/fibonacci-word.java | 50 ++ .../Mathematica/fibonacci-word.math | 7 + .../PARI-GP/fibonacci-word.pari | 4 + Task/Fibonacci-word/PL-I/fibonacci-word.pli | 24 + .../Pascal/fibonacci-word.pascal | 109 +++++ .../Perl-6/fibonacci-word-1.pl6 | 11 + .../Perl-6/fibonacci-word-2.pl6 | 19 + Task/Fibonacci-word/Perl/fibonacci-word.pl | 31 ++ Task/Fibonacci-word/Python/fibonacci-word.py | 58 +++ Task/Fibonacci-word/R/fibonacci-word.r | 31 ++ Task/Fibonacci-word/README | 1 + Task/Fibonacci-word/REXX/fibonacci-word.rexx | 36 ++ .../Racket/fibonacci-word-1.rkt | 62 +++ .../Racket/fibonacci-word-2.rkt | 32 ++ Task/Fibonacci-word/Ruby/fibonacci-word.rb | 23 + .../Fibonacci-word/Scala/fibonacci-word.scala | 17 + .../Fibonacci-word/Seed7/fibonacci-word.seed7 | 53 ++ Task/Fibonacci-word/Tcl/fibonacci-word.tcl | 28 ++ Task/File-IO/README | 1 - Task/File-IO/REXX/file-io-1.rexx | 11 - Task/File-IO/REXX/file-io-2.rexx | 11 - .../00DESCRIPTION | 0 Task/File-input-output/00META.yaml | 2 + .../ACL2/file-input-output.acl2} | 0 .../ALGOL-68/file-input-output.alg} | 0 .../AWK/file-input-output.awk} | 0 .../Ada/file-input-output-1.ada} | 10 +- .../Ada/file-input-output-2.ada} | 10 +- .../Ada/file-input-output-3.ada} | 10 +- .../Ada/file-input-output-4.ada} | 10 +- .../Aime/file-input-output.aime} | 0 .../file-input-output.applescript} | 0 .../AutoHotkey/file-input-output-1.ahk} | 0 .../AutoHotkey/file-input-output-2.ahk} | 0 .../AutoHotkey/file-input-output-3.ahk} | 0 .../BASIC/file-input-output-1.basic} | 0 .../BASIC/file-input-output-2.basic} | 0 .../BBC-BASIC/file-input-output-1.bbc} | 0 .../BBC-BASIC/file-input-output-2.bbc} | 0 .../Babel/file-input-output.pb} | 4 +- .../Batch-File/file-input-output-1.bat} | 0 .../Batch-File/file-input-output-2.bat} | 0 .../Batch-File/file-input-output-3.bat} | 0 .../Befunge/file-input-output.bf} | 0 .../Bracmat/file-input-output.bracmat} | 0 .../C++/file-input-output-1.cpp} | 0 .../C++/file-input-output-2.cpp} | 0 .../C++/file-input-output-3.cpp} | 0 .../C++/file-input-output-4.cpp} | 0 .../C/file-input-output-1.c} | 0 .../C/file-input-output-2.c} | 0 .../C/file-input-output-3.c} | 0 .../COBOL/file-input-output-1.cobol} | 0 .../COBOL/file-input-output-2.cobol} | 0 .../COBOL/file-input-output-3.cobol} | 0 .../Clean/file-input-output-1.clean} | 0 .../Clean/file-input-output-2.clean} | 0 .../Clojure/file-input-output-1.clj} | 0 .../Clojure/file-input-output-2.clj} | 0 .../ColdFusion/file-input-output.cfm} | 0 .../Common-Lisp/file-input-output-1.lisp} | 0 .../Common-Lisp/file-input-output-2.lisp} | 0 .../D/file-input-output-1.d} | 0 .../File-input-output/D/file-input-output-2.d | 15 + .../D/file-input-output-3.d} | 0 .../D/file-input-output-4.d} | 0 .../Delphi/file-input-output-1.delphi} | 0 .../Delphi/file-input-output-2.delphi} | 0 .../Delphi/file-input-output-3.delphi} | 0 .../E/file-input-output.e} | 0 .../Eiffel/file-input-output.e} | 0 .../Erlang/file-input-output.erl} | 0 .../Euphoria/file-input-output-1.euphoria} | 0 .../Euphoria/file-input-output-2.euphoria} | 0 .../Factor/file-input-output-1.factor} | 0 .../Factor/file-input-output-2.factor} | 0 .../Factor/file-input-output-3.factor} | 0 .../Forth/file-input-output.fth} | 0 .../Fortran/file-input-output.f} | 0 .../Frink/file-input-output.frink} | 0 .../GAP/file-input-output.gap} | 0 .../GML/file-input-output.gml} | 11 +- .../GUISS/file-input-output.guiss} | 0 .../Go/file-input-output-1.go} | 0 .../Go/file-input-output-2.go} | 0 .../Groovy/file-input-output-1.groovy} | 0 .../Groovy/file-input-output-2.groovy} | 0 .../Groovy/file-input-output-3.groovy} | 0 .../Haskell/file-input-output.hs} | 0 .../HicEst/file-input-output-1.hicest} | 0 .../HicEst/file-input-output-2.hicest} | 0 .../HicEst/file-input-output-3.hicest} | 0 .../IDL/file-input-output.idl} | 0 .../Icon/file-input-output.icon} | 0 .../Io/file-input-output.io} | 0 .../J/file-input-output-1.j} | 0 .../J/file-input-output-2.j} | 0 .../Java/file-input-output-1.java} | 0 .../Java/file-input-output-2.java} | 0 .../Java/file-input-output-3.java} | 0 .../Java/file-input-output-4.java} | 0 .../Java/file-input-output-5.java} | 0 .../JavaScript/file-input-output-1.js} | 0 .../JavaScript/file-input-output-2.js} | 0 .../Julia/file-input-output-1.julia | 2 + .../Julia/file-input-output-2.julia | 1 + .../Julia/file-input-output-3.julia | 5 + .../Julia/file-input-output-4.julia | 1 + .../K/file-input-output.k} | 0 .../Lang5/file-input-output.lang5} | 0 .../Liberty-BASIC/file-input-output.liberty} | 0 .../Lisaac/file-input-output.lisaac} | 0 .../Logo/file-input-output.logo} | 0 .../Lua/file-input-output.lua} | 0 .../MAXScript/file-input-output.max} | 0 .../Mathematica/file-input-output.math} | 0 .../Mercury/file-input-output.mercury} | 0 .../Modula-3/file-input-output.mod3} | 0 .../NetRexx/file-input-output.netrexx} | 0 .../OCaml/file-input-output-1.ocaml} | 0 .../OCaml/file-input-output-2.ocaml} | 0 .../Objeck/file-input-output.objeck} | 0 .../Object-Pascal/file-input-output.object} | 0 .../Objective-C/file-input-output-1.m | 1 + .../Objective-C/file-input-output-2.m} | 0 .../Octave/file-input-output.octave | 27 ++ .../file-input-output.openedge} | 0 .../Oz/file-input-output.oz} | 0 .../PARI-GP/file-input-output.pari} | 0 .../PHP/file-input-output-1.php} | 0 .../PHP/file-input-output-2.php} | 0 .../PL-I/file-input-output.pli} | 0 .../Perl-6/file-input-output-1.pl6} | 0 .../Perl-6/file-input-output-2.pl6} | 0 .../Perl/file-input-output.pl} | 0 .../PicoLisp/file-input-output-1.l} | 0 .../PicoLisp/file-input-output-2.l} | 0 .../Pop11/file-input-output-1.pop11} | 0 .../Pop11/file-input-output-2.pop11} | 0 .../PowerShell/file-input-output-1.psh} | 0 .../PowerShell/file-input-output-2.psh} | 0 .../PureBasic/file-input-output-1.purebasic} | 0 .../PureBasic/file-input-output-2.purebasic} | 0 .../PureBasic/file-input-output-3.purebasic} | 0 .../Python/file-input-output-1.py} | 0 .../Python/file-input-output-2.py} | 0 .../Python/file-input-output-3.py} | 0 .../Python/file-input-output-4.py} | 0 .../R/file-input-output-1.r} | 0 .../R/file-input-output-2.r} | 0 .../R/file-input-output-3.r} | 0 Task/File-input-output/README | 1 + .../REALbasic/file-input-output.realbasic} | 0 .../REBOL/file-input-output.rebol} | 0 .../REXX/file-input-output-1.rexx | 10 + .../REXX/file-input-output-2.rexx} | 0 .../Racket/file-input-output.rkt} | 0 .../RapidQ/file-input-output-1.rapidq} | 0 .../RapidQ/file-input-output-2.rapidq} | 0 .../Raven/file-input-output.raven} | 0 .../Retro/file-input-output.retro} | 0 .../Ruby/file-input-output-1.rb} | 0 .../Ruby/file-input-output-2.rb} | 0 .../Ruby/file-input-output-3.rb} | 0 .../Run-BASIC/file-input-output.run} | 0 .../Rust/file-input-output.rust} | 0 .../SNOBOL4/file-input-output.sno} | 0 .../Scala/file-input-output.scala} | 7 +- .../Scheme/file-input-output.ss} | 0 .../Seed7/file-input-output.seed7} | 0 .../Slate/file-input-output.slate} | 0 .../Smalltalk/file-input-output.st} | 0 .../Standard-ML/file-input-output.ml} | 0 .../Tcl/file-input-output-1.tcl} | 0 .../Tcl/file-input-output-2.tcl} | 0 .../Tcl/file-input-output-3.tcl} | 0 .../Tcl/file-input-output-4.tcl} | 0 .../Tcl/file-input-output-5.tcl} | 0 .../Toka/file-input-output-1.toka} | 0 .../Toka/file-input-output-2.toka} | 0 .../Toka/file-input-output-3.toka} | 0 .../UNIX-Shell/file-input-output-1.sh} | 0 .../UNIX-Shell/file-input-output-2.sh} | 0 .../UNIX-Shell/file-input-output-3.sh} | 0 .../Ursala/file-input-output.ursala} | 0 .../VBScript/file-input-output.vb} | 0 .../file-input-output.vedit} | 0 .../file-input-output.visual} | 0 .../XPL0/file-input-output.xpl0} | 0 .../00DESCRIPTION | 25 + .../00META.yaml | 3 + .../find-the-last-sunday-of-each-month.ahk | 20 + .../find-the-last-sunday-of-each-month.bbc | 9 + .../find-the-last-sunday-of-each-month-1.cpp | 99 ++++ .../find-the-last-sunday-of-each-month-2.cpp | 23 + .../find-the-last-sunday-of-each-month.clj | 25 + .../D/find-the-last-sunday-of-each-month.d | 14 + .../find-the-last-sunday-of-each-month.erl | 18 + .../find-the-last-sunday-of-each-month.fbsl | 17 + .../Go/find-the-last-sunday-of-each-month.go | 46 ++ ...ind-the-last-sunday-of-each-month-1.groovy | 16 + ...ind-the-last-sunday-of-each-month-2.groovy | 3 + .../find-the-last-sunday-of-each-month.icon | 20 + .../J/find-the-last-sunday-of-each-month-1.j | 2 + .../J/find-the-last-sunday-of-each-month-2.j | 13 + .../find-the-last-sunday-of-each-month-1.java | 72 +++ .../find-the-last-sunday-of-each-month-2.java | 29 ++ .../find-the-last-sunday-of-each-month.math | 6 + .../find-the-last-sunday-of-each-month.ocaml | 41 ++ .../find-the-last-sunday-of-each-month.pl6 | 8 + .../find-the-last-sunday-of-each-month.pl | 14 + .../find-the-last-sunday-of-each-month-1.l | 7 + .../find-the-last-sunday-of-each-month-2.l | 13 + .../find-the-last-sunday-of-each-month.py | 42 ++ .../Find-the-last-Sunday-of-each-month/README | 1 + .../find-the-last-sunday-of-each-month.rebol | 16 + .../find-the-last-sunday-of-each-month.rexx | 79 +++ .../find-the-last-sunday-of-each-month.rkt | 41 ++ .../find-the-last-sunday-of-each-month.rb | 10 + ...find-the-last-sunday-of-each-month-1.scala | 15 + ...find-the-last-sunday-of-each-month-2.scala | 8 + .../find-the-last-sunday-of-each-month.seed7 | 30 ++ .../find-the-last-sunday-of-each-month.tcl | 14 + .../find-the-last-sunday-of-each-month.vb | 6 + Task/Flipping-bits-game/00DESCRIPTION | 17 + Task/Flipping-bits-game/00META.yaml | 3 + .../Ada/flipping-bits-game.ada | 104 ++++ .../AutoHotkey/flipping-bits-game.ahk | 83 ++++ .../C++/flipping-bits-game.cpp | 92 ++++ .../Flipping-bits-game/C/flipping-bits-game.c | 115 +++++ .../Flipping-bits-game/D/flipping-bits-game.d | 70 +++ .../Fortran/flipping-bits-game.f | 197 ++++++++ .../Go/flipping-bits-game.go | 122 +++++ .../Haskell/flipping-bits-game.hs | 94 ++++ .../J/flipping-bits-game-1.j | 21 + .../J/flipping-bits-game-2.j | 16 + .../MATLAB/flipping-bits-game.m | 87 ++++ .../PL-I/flipping-bits-game.pli | 49 ++ .../Perl-6/flipping-bits-game.pl6 | 54 +++ .../Perl/flipping-bits-game.pl | 76 +++ .../Python/flipping-bits-game.py | 85 ++++ Task/Flipping-bits-game/README | 1 + .../REXX/flipping-bits-game.rexx | 86 ++++ .../Racket/flipping-bits-game.rkt | 71 +++ .../Ruby/flipping-bits-game.rb | 104 ++++ .../Tcl/flipping-bits-game.tcl | 92 ++++ Task/Fractran/00DESCRIPTION | 37 ++ Task/Fractran/Ada/fractran.ada | 43 ++ Task/Fractran/AutoHotkey/fractran.ahk | 24 + Task/Fractran/Bracmat/fractran.bracmat | 36 ++ Task/Fractran/C++/fractran.cpp | 64 +++ Task/Fractran/C/fractran.c | 65 +++ Task/Fractran/Common-Lisp/fractran.lisp | 21 + Task/Fractran/D/fractran-1.d | 18 + Task/Fractran/D/fractran-2.d | 26 + Task/Fractran/Go/fractran-1.go | 62 +++ Task/Fractran/Go/fractran-2.go | 35 ++ Task/Fractran/Haskell/fractran.hs | 12 + Task/Fractran/Icon/fractran.icon | 27 ++ Task/Fractran/J/fractran-1.j | 2 + Task/Fractran/J/fractran-2.j | 3 + Task/Fractran/Java/fractran.java | 54 +++ Task/Fractran/JavaScript/fractran.js | 39 ++ Task/Fractran/Mathematica/fractran.math | 15 + Task/Fractran/Perl-6/fractran-1.pl6 | 6 + Task/Fractran/Perl-6/fractran-2.pl6 | 6 + Task/Fractran/Perl/fractran.pl | 31 ++ Task/Fractran/Python/fractran-1.py | 21 + Task/Fractran/Python/fractran-2.py | 13 + Task/Fractran/README | 1 + Task/Fractran/REXX/fractran-1.rexx | 23 + Task/Fractran/REXX/fractran-2.rexx | 35 ++ Task/Fractran/Racket/fractran.rkt | 31 ++ Task/Fractran/Ruby/fractran.rb | 18 + Task/Fractran/Seed7/fractran-1.seed7 | 36 ++ Task/Fractran/Seed7/fractran-2.seed7 | 29 ++ Task/Fractran/Tcl/fractran-1.tcl | 49 ++ Task/Fractran/Tcl/fractran-2.tcl | 12 + Task/Gaussian-elimination/00DESCRIPTION | 1 + Task/Gaussian-elimination/00META.yaml | 3 + .../ALGOL-68/gaussian-elimination-1.alg | 26 + .../ALGOL-68/gaussian-elimination-2.alg | 53 ++ .../ALGOL-68/gaussian-elimination-3.alg | 78 +++ .../ALGOL-68/gaussian-elimination-4.alg | 9 + .../ALGOL-68/gaussian-elimination-5.alg | 29 ++ .../C/gaussian-elimination.c | 73 +++ .../D/gaussian-elimination.d | 69 +++ .../Fortran/gaussian-elimination.f | 43 ++ .../Go/gaussian-elimination.go | 97 ++++ .../J/gaussian-elimination.j | 57 +++ .../Julia/gaussian-elimination.julia | 1 + .../MATLAB/gaussian-elimination.m | 70 +++ .../Mathematica/gaussian-elimination.math | 1 + .../OCaml/gaussian-elimination-1.ocaml | 28 ++ .../OCaml/gaussian-elimination-2.ocaml | 38 ++ .../OCaml/gaussian-elimination-3.ocaml | 8 + .../OCaml/gaussian-elimination-4.ocaml | 4 + .../OCaml/gaussian-elimination-5.ocaml | 8 + .../OCaml/gaussian-elimination-6.ocaml | 4 + .../PARI-GP/gaussian-elimination.pari | 1 + .../PHP/gaussian-elimination.php | 75 +++ .../PL-I/gaussian-elimination.pli | 71 +++ .../Perl-6/gaussian-elimination.pl6 | 54 +++ .../Perl/gaussian-elimination.pl | 9 + .../Python/gaussian-elimination.py | 96 ++++ Task/Gaussian-elimination/README | 1 + .../REXX/gaussian-elimination-1.rexx | 79 +++ .../REXX/gaussian-elimination-2.rexx | 35 ++ .../Racket/gaussian-elimination-1.rkt | 13 + .../Racket/gaussian-elimination-2.rkt | 8 + .../Ruby/gaussian-elimination.rb | 18 + .../Tcl/gaussian-elimination.tcl | 12 + .../00DESCRIPTION | 12 + .../generate-chess960-starting-position.ahk | 33 ++ .../generate-chess960-starting-position.cpp | 69 +++ .../D/generate-chess960-starting-position-1.d | 13 + .../D/generate-chess960-starting-position-2.d | 11 + .../D/generate-chess960-starting-position-3.d | 13 + .../Go/generate-chess960-starting-position.go | 63 +++ .../generate-chess960-starting-position.hs | 15 + .../J/generate-chess960-starting-position-1.j | 11 + .../J/generate-chess960-starting-position-2.j | 8 + .../generate-chess960-starting-position.java | 27 ++ ...generate-chess960-starting-position.objeck | 70 +++ .../generate-chess960-starting-position-1.pl6 | 3 + .../generate-chess960-starting-position-2.pl6 | 6 + .../generate-chess960-starting-position-3.pl6 | 6 + .../generate-chess960-starting-position-4.pl6 | 22 + .../generate-chess960-starting-position.pl | 17 + .../generate-chess960-starting-position.l | 16 + .../generate-chess960-starting-position-1.py | 11 + .../generate-chess960-starting-position-2.py | 11 + .../generate-chess960-starting-position-3.py | 15 + .../generate-chess960-starting-position-4.py | 31 ++ .../README | 1 + ...generate-chess960-starting-position-1.rexx | 26 + ...generate-chess960-starting-position-2.rexx | 38 ++ .../generate-chess960-starting-position.rkt | 32 ++ .../generate-chess960-starting-position-1.rb | 4 + .../generate-chess960-starting-position-2.rb | 5 + .../generate-chess960-starting-position-3.rb | 22 + .../generate-chess960-starting-position.seed7 | 18 + .../generate-chess960-starting-position.tcl | 18 + .../00DESCRIPTION | 11 + .../00META.yaml | 2 + .../generate-lower-case-ascii-alphabet-1.alg | 5 + .../generate-lower-case-ascii-alphabet-2.alg | 9 + .../generate-lower-case-ascii-alphabet.ats | 26 + .../generate-lower-case-ascii-alphabet.awk | 11 + .../generate-lower-case-ascii-alphabet-1.ada | 1 + .../generate-lower-case-ascii-alphabet-2.ada | 2 + .../generate-lower-case-ascii-alphabet-3.ada | 6 + ...rate-lower-case-ascii-alphabet-1.applesoft | 1 + ...rate-lower-case-ascii-alphabet-2.applesoft | 1 + .../generate-lower-case-ascii-alphabet.ahk | 3 + .../generate-lower-case-ascii-alphabet.bbc | 5 + ...generate-lower-case-ascii-alphabet.bracmat | 6 + .../generate-lower-case-ascii-alphabet.cpp | 8 + .../generate-lower-case-ascii-alphabet.cs | 24 + .../C/generate-lower-case-ascii-alphabet.c | 13 + .../generate-lower-case-ascii-alphabet.clj | 1 + .../generate-lower-case-ascii-alphabet.lisp | 4 + .../D/generate-lower-case-ascii-alphabet-1.d | 3 + .../D/generate-lower-case-ascii-alphabet-2.d | 6 + .../D/generate-lower-case-ascii-alphabet-3.d | 5 + .../D/generate-lower-case-ascii-alphabet-4.d | 8 + .../generate-lower-case-ascii-alphabet.delphi | 11 + .../generate-lower-case-ascii-alphabet.factor | 7 + .../generate-lower-case-ascii-alphabet.f | 6 + .../Go/generate-lower-case-ascii-alphabet.go | 7 + ...enerate-lower-case-ascii-alphabet-1.groovy | 1 + ...enerate-lower-case-ascii-alphabet-2.groovy | 1 + .../generate-lower-case-ascii-alphabet.hs | 4 + .../generate-lower-case-ascii-alphabet.icon | 2 + .../J/generate-lower-case-ascii-alphabet.j | 2 + .../generate-lower-case-ascii-alphabet.java | 9 + .../generate-lower-case-ascii-alphabet.js | 4 + .../generate-lower-case-ascii-alphabet.julia | 5 + .../generate-lower-case-ascii-alphabet.logo | 1 + .../generate-lower-case-ascii-alphabet.math | 2 + ...generate-lower-case-ascii-alphabet.mercury | 16 + .../generate-lower-case-ascii-alphabet.php | 4 + .../generate-lower-case-ascii-alphabet-1.pli | 15 + .../generate-lower-case-ascii-alphabet-2.pli | 5 + .../generate-lower-case-ascii-alphabet.pl6 | 1 + .../generate-lower-case-ascii-alphabet.pl | 1 + .../generate-lower-case-ascii-alphabet.l | 1 + .../generate-lower-case-ascii-alphabet.pro | 4 + ...nerate-lower-case-ascii-alphabet.purebasic | 4 + .../generate-lower-case-ascii-alphabet.py | 5 + .../Generate-lower-case-ASCII-alphabet/README | 1 + .../generate-lower-case-ascii-alphabet-1.rexx | 4 + .../generate-lower-case-ascii-alphabet-2.rexx | 6 + .../generate-lower-case-ascii-alphabet.rkt | 1 + .../generate-lower-case-ascii-alphabet.rb | 2 + .../generate-lower-case-ascii-alphabet.scala | 18 + .../generate-lower-case-ascii-alphabet.ss | 1 + .../generate-lower-case-ascii-alphabet.ml | 1 + .../generate-lower-case-ascii-alphabet-1.tcl | 1 + .../generate-lower-case-ascii-alphabet-2.tcl | 7 + .../generate-lower-case-ascii-alphabet-1.sh | 1 + .../generate-lower-case-ascii-alphabet-2.sh | 1 + .../generate-lower-case-ascii-alphabet-3.sh | 1 + .../generate-lower-case-ascii-alphabet-1.vim | 4 + .../generate-lower-case-ascii-alphabet-2.vim | 1 + Task/Hash-join/00DESCRIPTION | 38 ++ Task/Hash-join/Bracmat/hash-join.bracmat | 57 +++ Task/Hash-join/C-sharp/hash-join.cs | 100 ++++ Task/Hash-join/Clojure/hash-join.clj | 20 + Task/Hash-join/Common-Lisp/hash-join.lisp | 17 + Task/Hash-join/D/hash-join.d | 35 ++ Task/Hash-join/Deja-Vu/hash-join.djv | 19 + Task/Hash-join/Erlang/hash-join.erl | 17 + Task/Hash-join/Go/hash-join.go | 31 ++ Task/Hash-join/Groovy/hash-join-1.groovy | 15 + Task/Hash-join/Groovy/hash-join-2.groovy | 8 + Task/Hash-join/Groovy/hash-join-3.groovy | 13 + Task/Hash-join/Haskell/hash-join-1.hs | 28 ++ Task/Hash-join/Haskell/hash-join-2.hs | 18 + Task/Hash-join/J/hash-join-1.j | 15 + Task/Hash-join/J/hash-join-2.j | 9 + Task/Hash-join/J/hash-join-3.j | 16 + Task/Hash-join/Mathematica/hash-join.math | 10 + Task/Hash-join/OCaml/hash-join.ocaml | 8 + Task/Hash-join/Oberon-2/hash-join.oberon-2 | 94 ++++ Task/Hash-join/PHP/hash-join.php | 27 ++ Task/Hash-join/Perl-6/hash-join.pl6 | 18 + Task/Hash-join/Perl/hash-join.pl | 30 ++ Task/Hash-join/Python/hash-join.py | 23 + Task/Hash-join/README | 1 + Task/Hash-join/REXX/hash-join.rexx | 33 ++ Task/Hash-join/Racket/hash-join.rkt | 29 ++ Task/Hash-join/Ruby/hash-join.rb | 22 + Task/Hash-join/SQL/hash-join-1.sql | 13 + Task/Hash-join/SQL/hash-join-2.sql | 1 + Task/Hash-join/Scala/hash-join.scala | 19 + Task/Hash-join/Scheme/hash-join.ss | 20 + Task/Hash-join/TXR/hash-join.txr | 20 + Task/Hash-join/Tcl/hash-join.tcl | 39 ++ Task/Hello-world-Newbie/00DESCRIPTION | 13 + .../ALGOL-68/hello-world-newbie.alg | 3 + .../AWK/hello-world-newbie.awk | 3 + .../AutoHotkey/hello-world-newbie.ahk | 1 + .../COBOL/hello-world-newbie-1.cobol | 1 + .../COBOL/hello-world-newbie-2.cobol | 7 + .../COBOL/hello-world-newbie-3.cobol | 1 + .../COBOL/hello-world-newbie-4.cobol | 2 + .../Clojure/hello-world-newbie-1.clj | 1 + .../Clojure/hello-world-newbie-2.clj | 3 + .../Clojure/hello-world-newbie-3.clj | 1 + .../Hello-world-Newbie/D/hello-world-newbie.d | 6 + .../Erlang/hello-world-newbie.erl | 6 + .../Haskell/hello-world-newbie-1.hs | 1 + .../Haskell/hello-world-newbie-2.hs | 4 + .../Haskell/hello-world-newbie-3.hs | 1 + .../Haskell/hello-world-newbie-4.hs | 2 + .../Hello-world-Newbie/J/hello-world-newbie.j | 1 + .../hello-world-newbie.locomotive | 2 + .../OCaml/hello-world-newbie-1.ocaml | 1 + .../OCaml/hello-world-newbie-2.ocaml | 1 + .../OCaml/hello-world-newbie-3.ocaml | 1 + .../PARI-GP/hello-world-newbie.pari | 1 + .../Perl/hello-world-newbie.pl | 69 +++ .../Python/hello-world-newbie.py | 1 + Task/Hello-world-Newbie/README | 1 + .../REXX/hello-world-newbie.rexx | 2 + .../Rust/hello-world-newbie.rust | 3 + .../Scala/hello-world-newbie.scala | 1 + .../TI-83-BASIC/hello-world-newbie.ti-83 | 2 + .../Tcl/hello-world-newbie.tcl | 1 + .../ZX-Spectrum-Basic/hello-world-newbie.zx | 1 + Task/Heronian-triangles/00DESCRIPTION | 29 ++ .../Heronian-triangles/D/heronian-triangles.d | 45 ++ .../Haskell/heronian-triangles.hs | 63 +++ .../J/heronian-triangles-1.j | 9 + .../J/heronian-triangles-2.j | 22 + .../Java/heronian-triangles-1.java | 57 +++ .../Java/heronian-triangles-2.java | 23 + .../JavaScript/heronian-triangles-1.js | 50 ++ .../JavaScript/heronian-triangles-2.js | 23 + .../Perl-6/heronian-triangles.pl6 | 42 ++ .../Perl/heronian-triangles.pl | 63 +++ .../PowerShell/heronian-triangles-1.psh | 47 ++ .../PowerShell/heronian-triangles-2.psh | 23 + .../Python/heronian-triangles.py | 33 ++ Task/Heronian-triangles/README | 1 + .../REXX/heronian-triangles.rexx | 53 ++ .../Racket/heronian-triangles.rkt | 55 +++ .../Ruby/heronian-triangles.rb | 46 ++ .../00DESCRIPTION | 15 + ...ickerson-series-of-almost-integers.bracmat | 28 ++ .../hickerson-series-of-almost-integers.cpp | 18 + .../C/hickerson-series-of-almost-integers.c | 29 ++ .../hickerson-series-of-almost-integers.cobol | 29 ++ .../hickerson-series-of-almost-integers.clj | 20 + .../D/hickerson-series-of-almost-integers.d | 10 + .../hickerson-series-of-almost-integers.f | 23 + .../Go/hickerson-series-of-almost-integers.go | 23 + .../J/hickerson-series-of-almost-integers-1.j | 2 + .../J/hickerson-series-of-almost-integers-2.j | 18 + .../hickerson-series-of-almost-integers.math | 4 + .../hickerson-series-of-almost-integers.pari | 3 + .../hickerson-series-of-almost-integers-1.pli | 22 + .../hickerson-series-of-almost-integers-2.pli | 16 + .../hickerson-series-of-almost-integers.pl6 | 9 + .../hickerson-series-of-almost-integers.pl | 14 + .../hickerson-series-of-almost-integers.py | 18 + .../README | 1 + .../hickerson-series-of-almost-integers.rexx | 89 ++++ .../hickerson-series-of-almost-integers.rkt | 19 + .../hickerson-series-of-almost-integers.rb | 20 + .../hickerson-series-of-almost-integers.seed7 | 17 + .../hickerson-series-of-almost-integers.tcl | 18 + Task/IBAN/00DESCRIPTION | 8 + Task/IBAN/00META.yaml | 2 + Task/IBAN/Ada/iban-1.ada | 3 + Task/IBAN/Ada/iban-2.ada | 88 ++++ Task/IBAN/Ada/iban-3.ada | 21 + Task/IBAN/AutoHotkey/iban.ahk | 43 ++ Task/IBAN/BBC-BASIC/iban.bbc | 93 ++++ Task/IBAN/Bracmat/iban.bracmat | 51 ++ Task/IBAN/C++/iban.cpp | 72 +++ Task/IBAN/C-sharp/iban-1.cs | 120 +++++ Task/IBAN/C-sharp/iban-2.cs | 100 ++++ Task/IBAN/C/iban.c | 97 ++++ Task/IBAN/COBOL/iban.cobol | 161 ++++++ Task/IBAN/Cache-ObjectScript/iban.cos | 98 ++++ Task/IBAN/Clojure/iban.clj | 24 + Task/IBAN/Common-Lisp/iban.lisp | 60 +++ Task/IBAN/D/iban.d | 37 ++ Task/IBAN/Go/iban.go | 61 +++ Task/IBAN/Groovy/iban-1.groovy | 16 + Task/IBAN/Groovy/iban-2.groovy | 7 + Task/IBAN/Haskell/iban.hs | 55 +++ Task/IBAN/J/iban.j | 34 ++ Task/IBAN/Java/iban.java | 47 ++ Task/IBAN/MATLAB/iban-1.m | 30 ++ Task/IBAN/MATLAB/iban-2.m | 11 + Task/IBAN/Mathematica/iban-1.math | 29 ++ Task/IBAN/Mathematica/iban-2.math | 4 + Task/IBAN/Oberon-2/iban.oberon-2 | 161 ++++++ Task/IBAN/Perl-6/iban.pl6 | 19 + Task/IBAN/Perl/iban.pl | 48 ++ Task/IBAN/PicoLisp/iban.l | 30 ++ Task/IBAN/Python/iban.py | 28 ++ Task/IBAN/README | 1 + Task/IBAN/REXX/iban-1.rexx | 47 ++ Task/IBAN/REXX/iban-2.rexx | 56 +++ Task/IBAN/Racket/iban.rkt | 25 + Task/IBAN/Ruby/iban.rb | 29 ++ Task/IBAN/Scala/iban-1.scala | 45 ++ Task/IBAN/Scala/iban-2.scala | 98 ++++ Task/IBAN/Seed7/iban.seed7 | 57 +++ Task/IBAN/Tcl/iban-1.tcl | 34 ++ Task/IBAN/Tcl/iban-2.tcl | 4 + Task/IBAN/UNIX-Shell/iban.sh | 34 ++ Task/Integer-overflow/00DESCRIPTION | 95 ++++ .../Integer-overflow/Ada/integer-overflow.ada | 51 ++ .../AutoHotkey/integer-overflow.ahk | 1 + Task/Integer-overflow/C/integer-overflow.c | 28 ++ .../Clojure/integer-overflow-1.clj | 4 + .../Clojure/integer-overflow-2.clj | 8 + Task/Integer-overflow/D/integer-overflow.d | 37 ++ Task/Integer-overflow/Go/integer-overflow.go | 108 +++++ .../Haskell/integer-overflow.hs | 26 + Task/Integer-overflow/J/integer-overflow-1.j | 39 ++ Task/Integer-overflow/J/integer-overflow-2.j | 39 ++ Task/Integer-overflow/J/integer-overflow-3.j | 39 ++ Task/Integer-overflow/J/integer-overflow-4.j | 39 ++ .../Java/integer-overflow.java | 18 + .../Integer-overflow/Perl/integer-overflow.pl | 11 + .../Python/integer-overflow-1.py | 18 + .../Python/integer-overflow-2.py | 18 + Task/Integer-overflow/README | 1 + .../REXX/integer-overflow.rexx | 16 + .../Integer-overflow/Ruby/integer-overflow.rb | 8 + .../Scala/integer-overflow.scala | 14 + .../Seed7/integer-overflow.seed7 | 19 + .../Integer-overflow/Tcl/integer-overflow.tcl | 4 + Task/Iterated-digits-squaring/00DESCRIPTION | 23 + .../C++/iterated-digits-squaring.cpp | 37 ++ .../C/iterated-digits-squaring.c | 82 ++++ .../D/iterated-digits-squaring-1.d | 18 + .../D/iterated-digits-squaring-2.d | 41 ++ .../D/iterated-digits-squaring-3.d | 74 +++ .../D/iterated-digits-squaring-4.d | 60 +++ .../Go/iterated-digits-squaring.go | 30 ++ .../Haskell/iterated-digits-squaring.hs | 13 + .../J/iterated-digits-squaring-1.j | 1 + .../J/iterated-digits-squaring-2.j | 1 + .../J/iterated-digits-squaring-3.j | 2 + .../J/iterated-digits-squaring-4.j | 1 + .../J/iterated-digits-squaring-5.j | 2 + .../J/iterated-digits-squaring-6.j | 1 + .../J/iterated-digits-squaring-7.j | 2 + .../J/iterated-digits-squaring-8.j | 2 + .../Java/iterated-digits-squaring.java | 24 + .../Julia/iterated-digits-squaring-1.julia | 18 + .../Julia/iterated-digits-squaring-2.julia | 27 ++ .../Lua/iterated-digits-squaring.lua | 47 ++ .../Mathematica/iterated-digits-squaring.math | 37 ++ .../iterated-digits-squaring.oberon-2 | 32 ++ .../Pascal/iterated-digits-squaring.pascal | 136 ++++++ .../Perl-6/iterated-digits-squaring-1.pl6 | 16 + .../Perl-6/iterated-digits-squaring-2.pl6 | 33 ++ .../Perl-6/iterated-digits-squaring-3.pl6 | 34 ++ .../Perl/iterated-digits-squaring.pl | 24 + .../Python/iterated-digits-squaring-1.py | 56 +++ .../Python/iterated-digits-squaring-2.py | 42 ++ .../Python/iterated-digits-squaring-3.py | 14 + .../Python/iterated-digits-squaring-4.py | 19 + Task/Iterated-digits-squaring/README | 1 + .../REXX/iterated-digits-squaring-1.rexx | 22 + .../REXX/iterated-digits-squaring-2.rexx | 43 ++ .../Racket/iterated-digits-squaring.rkt | 96 ++++ .../Ruby/iterated-digits-squaring.rb | 28 ++ .../Tcl/iterated-digits-squaring-1.tcl | 10 + .../Tcl/iterated-digits-squaring-2.tcl | 13 + .../Tcl/iterated-digits-squaring-3.tcl | 32 ++ Task/K-d-tree/00DESCRIPTION | 28 ++ Task/K-d-tree/C/k-d-tree.c | 173 +++++++ Task/K-d-tree/D/k-d-tree-1.d | 209 ++++++++ Task/K-d-tree/D/k-d-tree-2.d | 165 +++++++ Task/K-d-tree/Go/k-d-tree.go | 183 +++++++ Task/K-d-tree/Haskell/k-d-tree.hs | 201 ++++++++ Task/K-d-tree/J/k-d-tree-1.j | 69 +++ Task/K-d-tree/J/k-d-tree-2.j | 5 + Task/K-d-tree/J/k-d-tree-3.j | 5 + Task/K-d-tree/J/k-d-tree-4.j | 10 + Task/K-d-tree/J/k-d-tree-5.j | 10 + Task/K-d-tree/J/k-d-tree-6.j | 6 + Task/K-d-tree/J/k-d-tree-7.j | 6 + Task/K-d-tree/Perl-6/k-d-tree.pl6 | 126 +++++ Task/K-d-tree/Python/k-d-tree.py | 130 +++++ Task/K-d-tree/README | 1 + Task/K-d-tree/Racket/k-d-tree-1.rkt | 68 +++ Task/K-d-tree/Racket/k-d-tree-2.rkt | 27 ++ Task/K-d-tree/Racket/k-d-tree-3.rkt | 20 + Task/K-d-tree/Scala/k-d-tree-1.scala | 51 ++ Task/K-d-tree/Scala/k-d-tree-2.scala | 35 ++ Task/K-d-tree/Tcl/k-d-tree-1.tcl | 69 +++ Task/K-d-tree/Tcl/k-d-tree-2.tcl | 37 ++ Task/Left-factorials/00DESCRIPTION | 23 + Task/Left-factorials/00META.yaml | 3 + .../Bracmat/left-factorials.bracmat | 37 ++ Task/Left-factorials/C/left-factorials.c | 50 ++ Task/Left-factorials/D/left-factorials.d | 18 + Task/Left-factorials/Go/left-factorials.go | 45 ++ .../Haskell/left-factorials.hs | 18 + .../Left-factorials/Icon/left-factorials.icon | 16 + Task/Left-factorials/J/left-factorials-1.j | 1 + Task/Left-factorials/J/left-factorials-2.j | 34 ++ .../Left-factorials/Java/left-factorials.java | 33 ++ .../Julia/left-factorials.julia | 2 + .../Mathematica/left-factorials.math | 7 + .../PARI-GP/left-factorials.pari | 4 + Task/Left-factorials/PL-I/left-factorials.pli | 23 + .../Perl-6/left-factorials-1.pl6 | 7 + .../Perl-6/left-factorials-2.pl6 | 5 + .../Perl-6/left-factorials-3.pl6 | 1 + Task/Left-factorials/Perl/left-factorials.pl | 23 + .../Left-factorials/Python/left-factorials.py | 15 + Task/Left-factorials/README | 1 + .../Left-factorials/REXX/left-factorials.rexx | 22 + .../Racket/left-factorials.rkt | 17 + .../Left-factorials/Ruby/left-factorials-1.rb | 9 + .../Left-factorials/Ruby/left-factorials-2.rb | 8 + .../Left-factorials/Ruby/left-factorials-3.rb | 12 + .../Seed7/left-factorials.seed7 | 36 ++ Task/Left-factorials/Tcl/left-factorials.tcl | 15 + .../00DESCRIPTION | 10 + .../longest-increasing-subsequence.ahk | 22 + .../C++/longest-increasing-subsequence.cpp | 61 +++ .../C/longest-increasing-subsequence.c | 44 ++ .../longest-increasing-subsequence-1.clj | 12 + .../longest-increasing-subsequence-2.clj | 2 + .../longest-increasing-subsequence-1.lisp | 20 + .../longest-increasing-subsequence-2.lisp | 23 + .../longest-increasing-subsequence-3.lisp | 20 + .../D/longest-increasing-subsequence-1.d | 15 + .../D/longest-increasing-subsequence-2.d | 38 ++ .../D/longest-increasing-subsequence-3.d | 50 ++ .../longest-increasing-subsequence.djv | 25 + .../Go/longest-increasing-subsequence.go | 43 ++ .../longest-increasing-subsequence-1.hs | 12 + .../longest-increasing-subsequence-2.hs | 52 ++ .../Icon/longest-increasing-subsequence.icon | 11 + .../J/longest-increasing-subsequence-1.j | 2 + .../J/longest-increasing-subsequence-2.j | 8 + .../Java/longest-increasing-subsequence.java | 40 ++ .../longest-increasing-subsequence.js | 38 ++ .../Lua/longest-increasing-subsequence.lua | 26 + .../longest-increasing-subsequence.math | 1 + .../longest-increasing-subsequence-1.ocaml | 23 + .../longest-increasing-subsequence-2.ocaml | 22 + .../longest-increasing-subsequence.m | 53 ++ .../PHP/longest-increasing-subsequence.php | 37 ++ .../longest-increasing-subsequence-1.pl6 | 16 + .../longest-increasing-subsequence-2.pl6 | 16 + .../Perl/longest-increasing-subsequence-1.pl | 20 + .../Perl/longest-increasing-subsequence-2.pl | 34 ++ .../Prolog/longest-increasing-subsequence.pro | 14 + .../longest-increasing-subsequence-1.py | 11 + .../longest-increasing-subsequence-2.py | 34 ++ Task/Longest-increasing-subsequence/README | 1 + .../Racket/longest-increasing-subsequence.rkt | 27 ++ .../Ruby/longest-increasing-subsequence.rb | 33 ++ .../longest-increasing-subsequence.scala | 25 + .../Scheme/longest-increasing-subsequence.ss | 24 + .../longest-increasing-subsequence.ml | 31 ++ .../Tcl/longest-increasing-subsequence-1.tcl | 21 + .../Tcl/longest-increasing-subsequence-2.tcl | 2 + Task/Ludic-numbers/00DESCRIPTION | 29 ++ Task/Ludic-numbers/00META.yaml | 2 + .../AutoHotkey/ludic-numbers.ahk | 45 ++ Task/Ludic-numbers/C++/ludic-numbers.cpp | 81 ++++ Task/Ludic-numbers/C/ludic-numbers.c | 71 +++ Task/Ludic-numbers/Clojure/ludic-numbers.clj | 25 + Task/Ludic-numbers/D/ludic-numbers-1.d | 51 ++ Task/Ludic-numbers/D/ludic-numbers-2.d | 58 +++ Task/Ludic-numbers/D/ludic-numbers-3.d | 42 ++ Task/Ludic-numbers/Eiffel/ludic-numbers-1.e | 78 +++ Task/Ludic-numbers/Eiffel/ludic-numbers-2.e | 32 ++ Task/Ludic-numbers/Go/ludic-numbers.go | 81 ++++ Task/Ludic-numbers/Haskell/ludic-numbers-1.hs | 12 + Task/Ludic-numbers/Haskell/ludic-numbers-2.hs | 9 + Task/Ludic-numbers/Icon/ludic-numbers.icon | 35 ++ Task/Ludic-numbers/J/ludic-numbers-1.j | 1 + Task/Ludic-numbers/J/ludic-numbers-2.j | 22 + Task/Ludic-numbers/Java/ludic-numbers.java | 45 ++ .../Mathematica/ludic-numbers.math | 10 + Task/Ludic-numbers/PL-I/ludic-numbers.pli | 52 ++ Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 | 29 ++ Task/Ludic-numbers/Perl/ludic-numbers.pl | 60 +++ Task/Ludic-numbers/PicoLisp/ludic-numbers.l | 40 ++ Task/Ludic-numbers/Python/ludic-numbers-1.py | 22 + Task/Ludic-numbers/Python/ludic-numbers-2.py | 12 + Task/Ludic-numbers/README | 1 + Task/Ludic-numbers/REXX/ludic-numbers.rexx | 39 ++ Task/Ludic-numbers/Racket/ludic-numbers.rkt | 40 ++ Task/Ludic-numbers/Ruby/ludic-numbers.rb | 21 + Task/Ludic-numbers/Seed7/ludic-numbers.seed7 | 61 +++ Task/Ludic-numbers/Tcl/ludic-numbers.tcl | 43 ++ Task/Machine-code/00DESCRIPTION | 17 + Task/Machine-code/AutoHotkey/machine-code.ahk | 11 + Task/Machine-code/BBC-BASIC/machine-code.bbc | 18 + Task/Machine-code/C/machine-code.c | 31 ++ .../Common-Lisp/machine-code.lisp | 55 +++ Task/Machine-code/D/machine-code.d | 17 + Task/Machine-code/PARI-GP/machine-code.pari | 29 ++ Task/Machine-code/Pascal/machine-code.pascal | 35 ++ .../PureBasic/machine-code.purebasic | 38 ++ Task/Machine-code/Python/machine-code.py | 37 ++ Task/Machine-code/README | 1 + Task/Machine-code/Tcl/machine-code-1.tcl | 30 ++ Task/Machine-code/Tcl/machine-code-2.tcl | 4 + Task/Magic-squares-of-odd-order/00DESCRIPTION | 23 + .../AWK/magic-squares-of-odd-order.awk | 70 +++ .../Ada/magic-squares-of-odd-order.ada | 35 ++ .../AutoHotkey/magic-squares-of-odd-order.ahk | 39 ++ .../C++/magic-squares-of-odd-order.cpp | 83 ++++ .../C/magic-squares-of-odd-order.c | 19 + .../magic-squares-of-odd-order.lisp | 21 + .../D/magic-squares-of-odd-order-1.d | 15 + .../D/magic-squares-of-odd-order-2.d | 66 +++ .../D/magic-squares-of-odd-order-3.d | 25 + .../Go/magic-squares-of-odd-order.go | 40 ++ .../Haskell/magic-squares-of-odd-order.hs | 62 +++ .../J/magic-squares-of-odd-order-1.j | 1 + .../J/magic-squares-of-odd-order-2.j | 4 + .../J/magic-squares-of-odd-order-3.j | 2 + .../J/magic-squares-of-odd-order-4.j | 10 + .../Java/magic-squares-of-odd-order.java | 47 ++ .../magic-squares-of-odd-order.math | 7 + .../magic-squares-of-odd-order-1.maxima | 17 + .../magic-squares-of-odd-order-2.maxima | 33 ++ .../PL-I/magic-squares-of-odd-order.pli | 38 ++ .../Perl-6/magic-squares-of-odd-order.pl6 | 16 + .../Python/magic-squares-of-odd-order.py | 45 ++ Task/Magic-squares-of-odd-order/README | 1 + .../REXX/magic-squares-of-odd-order.rexx | 18 + .../Racket/magic-squares-of-odd-order.rkt | 33 ++ .../Ruby/magic-squares-of-odd-order.rb | 10 + .../Rust/magic-squares-of-odd-order.rust | 13 + .../Seed7/magic-squares-of-odd-order.seed7 | 37 ++ .../Tcl/magic-squares-of-odd-order-1.tcl | 18 + .../Tcl/magic-squares-of-odd-order-2.tcl | 5 + Task/Make-directory-path/00DESCRIPTION | 9 + Task/Make-directory-path/00META.yaml | 2 + .../Clojure/make-directory-path.clj | 5 + .../Go/make-directory-path.go | 1 + .../Java/make-directory-path.java | 14 + .../JavaScript/make-directory-path.js | 27 ++ .../Mathematica/make-directory-path.math | 1 + .../Perl-6/make-directory-path.pl6 | 1 + .../Python/make-directory-path-1.py | 23 + .../Python/make-directory-path-2.py | 7 + .../Python/make-directory-path-3.py | 2 + Task/Make-directory-path/README | 1 + .../REXX/make-directory-path.rexx | 5 + .../Racket/make-directory-path.rkt | 22 + .../Ruby/make-directory-path.rb | 2 + .../Scala/make-directory-path-1.scala | 1 + .../Scala/make-directory-path-2.scala | 6 + .../Tcl/make-directory-path.tcl | 1 + .../UNIX-Shell/make-directory-path.sh | 1 + Task/Maximum-triangle-path-sum/00DESCRIPTION | 35 ++ .../ALGOL-68/maximum-triangle-path-sum.alg | 46 ++ .../Ada/maximum-triangle-path-sum.ada | 41 ++ .../Bracmat/maximum-triangle-path-sum.bracmat | 44 ++ .../C++/maximum-triangle-path-sum.cpp | 43 ++ .../C/maximum-triangle-path-sum.c | 45 ++ .../maximum-triangle-path-sum.lisp | 24 + .../D/maximum-triangle-path-sum.d | 9 + .../Go/maximum-triangle-path-sum.go | 55 +++ .../Haskell/maximum-triangle-path-sum.hs | 5 + .../J/maximum-triangle-path-sum-1.j | 2 + .../J/maximum-triangle-path-sum-2.j | 2 + .../Java/maximum-triangle-path-sum.java | 19 + .../maximum-triangle-path-sum.math | 4 + .../PARI-GP/maximum-triangle-path-sum.pari | 2 + .../Pascal/maximum-triangle-path-sum.pascal | 106 ++++ .../Perl-6/maximum-triangle-path-sum-1.pl6 | 8 + .../Perl-6/maximum-triangle-path-sum-2.pl6 | 3 + .../Perl-6/maximum-triangle-path-sum-3.pl6 | 3 + .../Perl/maximum-triangle-path-sum.pl | 12 + .../Prolog/maximum-triangle-path-sum.pro | 40 ++ .../Python/maximum-triangle-path-sum-1.py | 31 ++ .../Python/maximum-triangle-path-sum-2.py | 6 + Task/Maximum-triangle-path-sum/README | 1 + .../REXX/maximum-triangle-path-sum.rexx | 34 ++ .../Racket/maximum-triangle-path-sum.rkt | 59 +++ .../Ruby/maximum-triangle-path-sum.rb | 26 + .../Scala/maximum-triangle-path-sum.scala | 21 + .../Tcl/maximum-triangle-path-sum.tcl | 45 ++ Task/Move-to-front-algorithm/00DESCRIPTION | 94 ++++ .../ALGOL-68/move-to-front-algorithm.alg | 137 ++++++ .../Ada/move-to-front-algorithm.ada | 82 ++++ .../C++/move-to-front-algorithm.cpp | 82 ++++ .../C/move-to-front-algorithm.c | 88 ++++ .../Common-Lisp/move-to-front-algorithm.lisp | 27 ++ .../D/move-to-front-algorithm.d | 49 ++ .../Go/move-to-front-algorithm.go | 46 ++ .../Haskell/move-to-front-algorithm.hs | 19 + .../Icon/move-to-front-algorithm.icon | 29 ++ .../J/move-to-front-algorithm-1.j | 21 + .../J/move-to-front-algorithm-2.j | 6 + .../Java/move-to-front-algorithm.java | 40 ++ .../JavaScript/move-to-front-algorithm.js | 20 + .../MATLAB/move-to-front-algorithm.m | 30 ++ .../move-to-front-algorithm-1.math | 8 + .../move-to-front-algorithm-2.math | 1 + .../PL-I/move-to-front-algorithm.pli | 40 ++ .../Perl-6/move-to-front-algorithm.pl6 | 23 + .../Perl/move-to-front-algorithm.pl | 26 + .../Python/move-to-front-algorithm-1.py | 28 ++ .../Python/move-to-front-algorithm-2.py | 13 + Task/Move-to-front-algorithm/README | 1 + .../REXX/move-to-front-algorithm-1.rexx | 35 ++ .../REXX/move-to-front-algorithm-2.rexx | 21 + .../Racket/move-to-front-algorithm.rkt | 45 ++ .../Ruby/move-to-front-algorithm.rb | 30 ++ .../Tcl/move-to-front-algorithm.tcl | 39 ++ Task/Munching-squares/00DESCRIPTION | 3 + Task/Munching-squares/00META.yaml | 4 + .../Munching-squares/Ada/munching-squares.ada | 21 + .../Burlesque/munching-squares.blq | 27 ++ .../Munching-squares/C++/munching-squares.cpp | 161 ++++++ .../C-sharp/munching-squares.cs | 24 + Task/Munching-squares/C/munching-squares.c | 44 ++ Task/Munching-squares/D/munching-squares.d | 14 + .../Gnuplot/munching-squares.gnuplot | 4 + Task/Munching-squares/Go/munching-squares.go | 17 + .../Haskell/munching-squares.hs | 4 + .../Icon/munching-squares.icon | 18 + Task/Munching-squares/J/munching-squares.j | 2 + .../Java/munching-squares.java | 31 ++ .../Liberty-BASIC/munching-squares.liberty | 31 ++ .../MATLAB/munching-squares.m | 8 + .../Mathematica/munching-squares-1.math | 4 + .../Mathematica/munching-squares-2.math | 1 + .../OCaml/munching-squares.ocaml | 13 + .../Octave/munching-squares.octave | 8 + .../Munching-squares/PHP/munching-squares.php | 24 + .../PL-I/munching-squares.pli | 14 + .../Perl-6/munching-squares-1.pl6 | 18 + .../Perl-6/munching-squares-2.pl6 | 19 + .../Munching-squares/Perl/munching-squares.pl | 12 + .../Prolog/munching-squares.pro | 18 + .../PureBasic/munching-squares.purebasic | 26 + .../Python/munching-squares.py | 11 + Task/Munching-squares/README | 1 + .../Racket/munching-squares.rkt | 9 + .../Munching-squares/Ruby/munching-squares.rb | 25 + .../Run-BASIC/munching-squares.run | 11 + .../Scala/munching-squares.scala | 26 + .../TI-83-BASIC/munching-squares.ti-83 | 76 +++ .../Munching-squares/Tcl/munching-squares.tcl | 27 ++ .../XPL0/munching-squares.xpl0 | 15 + Task/Mutex/00DESCRIPTION | 19 - Task/Mutex/00META.yaml | 6 - Task/Mutex/Ada/mutex-1.ada | 6 - Task/Mutex/Ada/mutex-2.ada | 10 - Task/Mutex/Ada/mutex-3.ada | 15 - Task/Mutex/BBC-BASIC/mutex.bbc | 13 - Task/Mutex/C/mutex-1.c | 1 - Task/Mutex/C/mutex-2.c | 1 - Task/Mutex/C/mutex-3.c | 1 - Task/Mutex/C/mutex-4.c | 1 - Task/Mutex/C/mutex-5.c | 3 - Task/Mutex/C/mutex-6.c | 2 - Task/Mutex/C/mutex-7.c | 1 - Task/Mutex/C/mutex-8.c | 1 - Task/Mutex/C/mutex-9.c | 1 - Task/Mutex/D/mutex-1.d | 11 - Task/Mutex/D/mutex-2.d | 46 -- Task/Mutex/D/mutex-3.d | 11 - Task/Mutex/E/mutex-1.e | 16 - Task/Mutex/E/mutex-2.e | 39 -- Task/Mutex/Erlang/mutex.erl | 40 -- Task/Mutex/Go/mutex-1.go | 28 -- Task/Mutex/Go/mutex-2.go | 40 -- Task/Mutex/Haskell/mutex-1.hs | 4 - Task/Mutex/Haskell/mutex-2.hs | 7 - Task/Mutex/Java/mutex-1.java | 10 - Task/Mutex/Java/mutex-2.java | 10 - Task/Mutex/Java/mutex-3.java | 35 -- Task/Mutex/Logtalk/mutex-1.logtalk | 33 -- Task/Mutex/Logtalk/mutex-2.logtalk | 11 - Task/Mutex/OCaml/mutex.ocaml | 8 - Task/Mutex/Objeck/mutex.objeck | 6 - Task/Mutex/Objective-C/mutex.m | 11 - Task/Mutex/Oz/mutex-1.oz | 1 - Task/Mutex/Oz/mutex-2.oz | 3 - Task/Mutex/Oz/mutex-3.oz | 9 - Task/Mutex/Perl-6/mutex.pl6 | 3 - Task/Mutex/Perl/mutex.pl | 28 -- Task/Mutex/PureBasic/mutex-1.purebasic | 5 - Task/Mutex/PureBasic/mutex-2.purebasic | 34 -- Task/Mutex/Python/mutex.py | 30 -- Task/Mutex/README | 1 - Task/Mutex/Racket/mutex-1.rkt | 6 - Task/Mutex/Racket/mutex-2.rkt | 10 - Task/Mutex/Ruby/mutex-1.rb | 6 - Task/Mutex/Ruby/mutex-2.rb | 2 - Task/Mutex/Ruby/mutex-3.rb | 16 - Task/Mutex/Tcl/mutex-1.tcl | 13 - Task/Mutex/Tcl/mutex-2.tcl | 11 - .../Narcissistic-decimal-number/00DESCRIPTION | 7 + .../AWK/narcissistic-decimal-number.awk | 16 + .../Ada/narcissistic-decimal-number.ada | 32 ++ .../narcissistic-decimal-number.ahk | 42 ++ .../C++/narcissistic-decimal-number.cpp | 67 +++ .../C/narcissistic-decimal-number.c | 63 +++ .../narcissistic-decimal-number.lisp | 14 + .../D/narcissistic-decimal-number-1.d | 8 + .../D/narcissistic-decimal-number-2.d | 29 ++ .../D/narcissistic-decimal-number-3.d | 54 +++ .../Go/narcissistic-decimal-number.go | 29 ++ .../Haskell/narcissistic-decimal-number.hs | 15 + .../Icon/narcissistic-decimal-number.icon | 11 + .../J/narcissistic-decimal-number-1.j | 2 + .../J/narcissistic-decimal-number-2.j | 2 + .../Java/narcissistic-decimal-number.java | 23 + .../MATLAB/narcissistic-decimal-number.m | 17 + .../Pascal/narcissistic-decimal-number.pascal | 81 ++++ .../Perl-6/narcissistic-decimal-number-1.pl6 | 8 + .../Perl-6/narcissistic-decimal-number-2.pl6 | 20 + .../Perl/narcissistic-decimal-number.pl | 11 + .../PicoLisp/narcissistic-decimal-number.l | 13 + .../Python/narcissistic-decimal-number-1.py | 18 + .../Python/narcissistic-decimal-number-2.py | 58 +++ Task/Narcissistic-decimal-number/README | 1 + .../REXX/narcissistic-decimal-number-1.rexx | 15 + .../REXX/narcissistic-decimal-number-2.rexx | 20 + .../REXX/narcissistic-decimal-number-3.rexx | 27 ++ .../Racket/narcissistic-decimal-number-1.rkt | 64 +++ .../Racket/narcissistic-decimal-number-2.rkt | 59 +++ .../Ruby/narcissistic-decimal-number.rb | 28 ++ .../Scala/narcissistic-decimal-number.scala | 8 + .../Tcl/narcissistic-decimal-number.tcl | 19 + .../UNIX-Shell/narcissistic-decimal-number.sh | 14 + Task/Natural-sorting/00DESCRIPTION | 71 +++ Task/Natural-sorting/C/natural-sorting-1.c | 257 ++++++++++ Task/Natural-sorting/C/natural-sorting-2.c | 53 ++ Task/Natural-sorting/D/natural-sorting.d | 58 +++ Task/Natural-sorting/Go/natural-sorting.go | 134 +++++ Task/Natural-sorting/J/natural-sorting-1.j | 10 + Task/Natural-sorting/J/natural-sorting-2.j | 45 ++ Task/Natural-sorting/J/natural-sorting-3.j | 33 ++ .../Perl-6/natural-sorting-1.pl6 | 27 ++ .../Perl-6/natural-sorting-2.pl6 | 79 +++ .../Natural-sorting/Perl/natural-sorting-1.pl | 22 + .../Natural-sorting/Perl/natural-sorting-2.pl | 30 ++ .../PicoLisp/natural-sorting-1.l | 29 ++ .../PicoLisp/natural-sorting-2.l | 2 + .../PicoLisp/natural-sorting-3.l | 2 + .../PicoLisp/natural-sorting-4.l | 42 ++ .../Natural-sorting/Python/natural-sorting.py | 155 ++++++ Task/Natural-sorting/README | 1 + .../Racket/natural-sorting.rkt | 21 + .../Natural-sorting/Ruby/natural-sorting-1.rb | 1 + .../Natural-sorting/Ruby/natural-sorting-2.rb | 24 + .../Natural-sorting/Ruby/natural-sorting-3.rb | 18 + .../Scala/natural-sorting.scala | 53 ++ Task/Natural-sorting/Tcl/natural-sorting.tcl | 59 +++ Task/Nth/00DESCRIPTION | 8 + Task/Nth/00META.yaml | 4 + Task/Nth/ALGOL-68/nth.alg | 49 ++ Task/Nth/AWK/nth.awk | 32 ++ Task/Nth/Ada/nth.ada | 26 + Task/Nth/Applesoft-BASIC/nth.applesoft | 19 + Task/Nth/AutoHotkey/nth.ahk | 16 + Task/Nth/BBC-BASIC/nth.bbc | 16 + Task/Nth/Babel/nth.pb | 28 ++ Task/Nth/C/nth.c | 52 ++ Task/Nth/Clojure/nth-1.clj | 14 + Task/Nth/Clojure/nth-2.clj | 1 + Task/Nth/Common-Lisp/nth.lisp | 15 + Task/Nth/D/nth.d | 12 + Task/Nth/Forth/nth.fth | 10 + Task/Nth/Fortran/nth.f | 89 ++++ Task/Nth/Go/nth.go | 37 ++ Task/Nth/Haskell/nth.hs | 19 + Task/Nth/Icon/nth.icon | 11 + Task/Nth/J/nth-1.j | 3 + Task/Nth/J/nth-2.j | 7 + Task/Nth/Java/nth-1.java | 26 + Task/Nth/Java/nth-2.java | 48 ++ Task/Nth/MATLAB/nth.m | 18 + Task/Nth/Mathematica/nth.math | 12 + Task/Nth/PARI-GP/nth.pari | 5 + Task/Nth/PHP/nth.php | 25 + Task/Nth/PL-I/nth.pli | 26 + Task/Nth/Perl-6/nth-1.pl6 | 5 + Task/Nth/Perl-6/nth-2.pl6 | 5 + Task/Nth/Perl/nth-1.pl | 15 + Task/Nth/Perl/nth-2.pl | 4 + Task/Nth/PicoLisp/nth.l | 18 + Task/Nth/Prolog/nth.pro | 16 + Task/Nth/Python/nth.py | 8 + Task/Nth/R/nth.r | 18 + Task/Nth/README | 1 + Task/Nth/REXX/nth.rexx | 17 + Task/Nth/Racket/nth.rkt | 10 + Task/Nth/Ruby/nth.rb | 18 + Task/Nth/Rust/nth.rust | 26 + Task/Nth/Scala/nth.scala | 20 + Task/Nth/Seed7/nth.seed7 | 29 ++ Task/Nth/Tcl/nth.tcl | 15 + Task/Odd-word-problem/00DESCRIPTION | 14 + .../ALGOL-68/odd-word-problem.alg | 75 +++ .../Odd-word-problem/Ada/odd-word-problem.ada | 55 +++ .../Bracmat/odd-word-problem.bracmat | 33 ++ .../Odd-word-problem/C++/odd-word-problem.cpp | 36 ++ Task/Odd-word-problem/C/odd-word-problem.c | 32 ++ .../Clojure/odd-word-problem-1.clj | 26 + .../Clojure/odd-word-problem-2.clj | 6 + .../CoffeeScript/odd-word-problem-1.coffee | 36 ++ .../CoffeeScript/odd-word-problem-2.coffee | 23 + .../CoffeeScript/odd-word-problem-3.coffee | 27 ++ .../Common-Lisp/odd-word-problem-1.lisp | 19 + .../Common-Lisp/odd-word-problem-2.lisp | 6 + Task/Odd-word-problem/D/odd-word-problem.d | 19 + .../Erlang/odd-word-problem.erl | 16 + .../FALSE/odd-word-problem.false | 4 + .../Factor/odd-word-problem.factor | 62 +++ .../Forth/odd-word-problem.fth | 6 + .../Odd-word-problem/Go/odd-word-problem-1.go | 52 ++ .../Odd-word-problem/Go/odd-word-problem-2.go | 52 ++ .../Odd-word-problem/Go/odd-word-problem-3.go | 89 ++++ .../Haskell/odd-word-problem-1.hs | 20 + .../Haskell/odd-word-problem-2.hs | 31 ++ .../Icon/odd-word-problem-1.icon | 22 + .../Icon/odd-word-problem-2.icon | 10 + Task/Odd-word-problem/J/odd-word-problem-1.j | 26 + Task/Odd-word-problem/J/odd-word-problem-2.j | 4 + .../Java/odd-word-problem.java | 57 +++ .../OCaml/odd-word-problem.ocaml | 25 + .../Odd-word-problem/PHP/odd-word-problem.php | 27 ++ .../PL-I/odd-word-problem.pli | 25 + .../Perl-6/odd-word-problem.pl6 | 12 + .../Perl/odd-word-problem-1.pl | 20 + .../Perl/odd-word-problem-2.pl | 26 + .../Perl/odd-word-problem-3.pl | 24 + .../PicoLisp/odd-word-problem-1.l | 14 + .../PicoLisp/odd-word-problem-2.l | 2 + .../Prolog/odd-word-problem.pro | 27 ++ .../PureBasic/odd-word-problem.purebasic | 58 +++ .../Python/odd-word-problem-1.py | 28 ++ .../Python/odd-word-problem-2.py | 4 + .../Python/odd-word-problem-3.py | 28 ++ .../Python/odd-word-problem-4.py | 33 ++ Task/Odd-word-problem/README | 1 + .../REXX/odd-word-problem.rexx | 35 ++ .../Racket/odd-word-problem.rkt | 26 + .../Ruby/odd-word-problem-1.rb | 13 + .../Ruby/odd-word-problem-2.rb | 71 +++ .../Run-BASIC/odd-word-problem.run | 31 ++ .../Scala/odd-word-problem.scala | 17 + .../Scheme/odd-word-problem.ss | 19 + .../Seed7/odd-word-problem.seed7 | 35 ++ .../TUSCRIPT/odd-word-problem.tu | 18 + .../Odd-word-problem/Tcl/odd-word-problem.tcl | 13 + Task/Old-lady-swallowed-a-fly/00DESCRIPTION | 3 + .../ALGOL-68/old-lady-swallowed-a-fly-1.alg | 34 ++ .../ALGOL-68/old-lady-swallowed-a-fly-2.alg | 39 ++ .../AWK/old-lady-swallowed-a-fly.awk | 33 ++ .../Ada/old-lady-swallowed-a-fly.ada | 58 +++ .../AutoHotkey/old-lady-swallowed-a-fly.ahk | 19 + .../Babel/old-lady-swallowed-a-fly.pb | 44 ++ .../C/old-lady-swallowed-a-fly.c | 29 ++ .../D/old-lady-swallowed-a-fly-1.d | 29 ++ .../D/old-lady-swallowed-a-fly-2.d | 41 ++ .../Factor/old-lady-swallowed-a-fly.factor | 10 + .../Forth/old-lady-swallowed-a-fly.fth | 54 +++ .../Frege/old-lady-swallowed-a-fly.frege | 41 ++ .../Haskell/old-lady-swallowed-a-fly.hs | 41 ++ .../Icon/old-lady-swallowed-a-fly.icon | 32 ++ .../J/old-lady-swallowed-a-fly.j | 24 + .../Java/old-lady-swallowed-a-fly.java | 29 ++ .../OCaml/old-lady-swallowed-a-fly-1.ocaml | 32 ++ .../OCaml/old-lady-swallowed-a-fly-2.ocaml | 19 + .../OCaml/old-lady-swallowed-a-fly-3.ocaml | 32 ++ .../PHP/old-lady-swallowed-a-fly.php | 40 ++ .../Perl-6/old-lady-swallowed-a-fly.pl6 | 25 + .../Perl/old-lady-swallowed-a-fly-1.pl | 32 ++ .../Perl/old-lady-swallowed-a-fly-2.pl | 18 + .../PicoLisp/old-lady-swallowed-a-fly.l | 42 ++ .../Python/old-lady-swallowed-a-fly.py | 11 + Task/Old-lady-swallowed-a-fly/README | 1 + .../REXX/old-lady-swallowed-a-fly.rexx | 24 + .../Racket/old-lady-swallowed-a-fly-1.rkt | 24 + .../Racket/old-lady-swallowed-a-fly-2.rkt | 6 + .../Ruby/old-lady-swallowed-a-fly.rb | 32 ++ .../Scala/old-lady-swallowed-a-fly.scala | 27 ++ .../Seed7/old-lady-swallowed-a-fly.seed7 | 34 ++ .../TXR/old-lady-swallowed-a-fly.txr | 83 ++++ .../Tcl/old-lady-swallowed-a-fly.tcl | 12 + Task/Order-disjoint-list-items/00DESCRIPTION | 27 ++ .../AutoHotkey/order-disjoint-list-items.ahk | 21 + .../Bracmat/order-disjoint-list-items.bracmat | 35 ++ .../D/order-disjoint-list-items.d | 51 ++ .../Go/order-disjoint-list-items.go | 57 +++ .../Icon/order-disjoint-list-items.icon | 23 + .../J/order-disjoint-list-items-1.j | 9 + .../J/order-disjoint-list-items-2.j | 14 + .../Java/order-disjoint-list-items.java | 50 ++ .../Perl-6/order-disjoint-list-items-1.pl6 | 4 + .../Perl-6/order-disjoint-list-items-2.pl6 | 12 + .../Perl/order-disjoint-list-items.pl | 21 + .../Python/order-disjoint-list-items.py | 37 ++ Task/Order-disjoint-list-items/README | 1 + .../REXX/order-disjoint-list-items.rexx | 40 ++ .../Racket/order-disjoint-list-items.rkt | 37 ++ .../Ruby/order-disjoint-list-items.rb | 17 + .../Scala/order-disjoint-list-items-1.scala | 5 + .../Scala/order-disjoint-list-items-2.scala | 14 + .../Tcl/order-disjoint-list-items-1.tcl | 13 + .../Tcl/order-disjoint-list-items-2.tcl | 18 + .../Tcl/order-disjoint-list-items-3.tcl | 11 + Task/Paraffins/00DESCRIPTION | 67 +++ Task/Paraffins/C/paraffins-1.c | 115 +++++ Task/Paraffins/C/paraffins-2.c | 106 ++++ Task/Paraffins/D/paraffins.d | 44 ++ Task/Paraffins/Go/paraffins.go | 61 +++ Task/Paraffins/Haskell/paraffins.hs | 32 ++ Task/Paraffins/J/paraffins-1.j | 32 ++ Task/Paraffins/J/paraffins-2.j | 7 + Task/Paraffins/Mathematica/paraffins.math | 14 + Task/Paraffins/Pascal/paraffins.pascal | 88 ++++ Task/Paraffins/Perl-6/paraffins.pl6 | 45 ++ Task/Paraffins/Perl/paraffins.pl | 40 ++ Task/Paraffins/Pike/paraffins.pike | 63 +++ Task/Paraffins/Python/paraffins.py | 53 ++ Task/Paraffins/README | 1 + Task/Paraffins/REXX/paraffins.rexx | 27 ++ Task/Paraffins/Racket/paraffins.rkt | 36 ++ Task/Paraffins/Ruby/paraffins.rb | 36 ++ Task/Paraffins/Seed7/paraffins.seed7 | 62 +++ Task/Paraffins/Tcl/paraffins.tcl | 46 ++ Task/Parse-an-IP-Address/00DESCRIPTION | 27 ++ .../C/parse-an-ip-address-1.c | 298 ++++++++++++ .../C/parse-an-ip-address-2.c | 80 +++ .../Go/parse-an-ip-address.go | 69 +++ .../Icon/parse-an-ip-address.icon | 81 ++++ .../J/parse-an-ip-address-1.j | 37 ++ .../J/parse-an-ip-address-2.j | 12 + .../Java/parse-an-ip-address-1.java | 190 ++++++++ .../Java/parse-an-ip-address-2.java | 59 +++ .../Perl-6/parse-an-ip-address.pl6 | 84 ++++ .../Perl/parse-an-ip-address-1.pl | 82 ++++ .../Perl/parse-an-ip-address-2.pl | 28 ++ .../PicoLisp/parse-an-ip-address-1.l | 32 ++ .../PicoLisp/parse-an-ip-address-2.l | 14 + .../PicoLisp/parse-an-ip-address-3.l | 277 +++++++++++ .../Python/parse-an-ip-address.py | 124 +++++ Task/Parse-an-IP-Address/README | 1 + .../REXX/parse-an-ip-address-1.rexx | 39 ++ .../REXX/parse-an-ip-address-2.rexx | 83 ++++ .../Racket/parse-an-ip-address.rkt | 29 ++ .../Ruby/parse-an-ip-address.rb | 64 +++ .../Tcl/parse-an-ip-address-1.tcl | 39 ++ .../Tcl/parse-an-ip-address-2.tcl | 27 ++ Task/Penneys-game/00DESCRIPTION | 18 + Task/Penneys-game/C++/penneys-game.cpp | 86 ++++ Task/Penneys-game/C/penneys-game.c | 121 +++++ Task/Penneys-game/D/penneys-game.d | 35 ++ Task/Penneys-game/Haskell/penneys-game.hs | 91 ++++ Task/Penneys-game/J/penneys-game-1.j | 28 ++ Task/Penneys-game/J/penneys-game-2.j | 12 + Task/Penneys-game/Java/penneys-game.java | 52 ++ Task/Penneys-game/Perl-6/penneys-game.pl6 | 72 +++ Task/Penneys-game/Python/penneys-game.py | 30 ++ Task/Penneys-game/README | 1 + Task/Penneys-game/REXX/penneys-game.rexx | 67 +++ Task/Penneys-game/Racket/penneys-game.rkt | 37 ++ Task/Penneys-game/Ruby/penneys-game.rb | 35 ++ Task/Penneys-game/Tcl/penneys-game.tcl | 98 ++++ Task/Penneys-game/UNIX-Shell/penneys-game.sh | 70 +++ .../00DESCRIPTION | 23 + Task/Percolation-Bond-percolation/00META.yaml | 2 + .../C/percolation-bond-percolation.c | 100 ++++ .../D/percolation-bond-percolation.d | 106 ++++ .../Go/percolation-bond-percolation.go | 132 +++++ .../Python/percolation-bond-percolation.py | 83 ++++ Task/Percolation-Bond-percolation/README | 1 + .../Racket/percolation-bond-percolation.rkt | 117 +++++ .../Tcl/percolation-bond-percolation.tcl | 112 +++++ .../00DESCRIPTION | 22 + .../00META.yaml | 2 + .../C/percolation-mean-cluster-density.c | 77 +++ .../D/percolation-mean-cluster-density.d | 90 ++++ .../J/percolation-mean-cluster-density-1.j | 1 + .../J/percolation-mean-cluster-density-10.j | 12 + .../J/percolation-mean-cluster-density-11.j | 13 + .../J/percolation-mean-cluster-density-12.j | 1 + .../J/percolation-mean-cluster-density-13.j | 16 + .../J/percolation-mean-cluster-density-14.j | 11 + .../J/percolation-mean-cluster-density-2.j | 22 + .../J/percolation-mean-cluster-density-3.j | 1 + .../J/percolation-mean-cluster-density-4.j | 14 + .../J/percolation-mean-cluster-density-5.j | 1 + .../J/percolation-mean-cluster-density-6.j | 2 + .../J/percolation-mean-cluster-density-7.j | 1 + .../J/percolation-mean-cluster-density-8.j | 4 + .../J/percolation-mean-cluster-density-9.j | 1 + .../percolation-mean-cluster-density.py | 63 +++ Task/Percolation-Mean-cluster-density/README | 1 + .../percolation-mean-cluster-density.rkt | 97 ++++ .../Tcl/percolation-mean-cluster-density.tcl | 55 +++ .../00DESCRIPTION | 28 ++ Task/Percolation-Mean-run-density/00META.yaml | 2 + .../C++/percolation-mean-run-density.cpp | 56 +++ .../C/percolation-mean-run-density.c | 36 ++ .../D/percolation-mean-run-density.d | 23 + .../Fortran/percolation-mean-run-density.f | 59 +++ .../Haskell/percolation-mean-run-density.hs | 28 ++ .../Icon/percolation-mean-run-density.icon | 15 + .../J/percolation-mean-run-density.j | 21 + .../Perl-6/percolation-mean-run-density.pl6 | 10 + .../Perl/percolation-mean-run-density.pl | 17 + .../Python/percolation-mean-run-density.py | 24 + Task/Percolation-Mean-run-density/README | 1 + .../Racket/percolation-mean-run-density.rkt | 32 ++ .../Tcl/percolation-mean-run-density.tcl | 33 ++ .../00DESCRIPTION | 19 + Task/Percolation-Site-percolation/00META.yaml | 2 + .../C/percolation-site-percolation-1.c | 65 +++ .../C/percolation-site-percolation-2.c | 118 +++++ .../D/percolation-site-percolation.d | 95 ++++ .../Fortran/percolation-site-percolation.f | 123 +++++ .../Go/percolation-site-percolation.go | 114 +++++ .../J/percolation-site-percolation.j | 42 ++ .../Python/percolation-site-percolation.py | 71 +++ Task/Percolation-Site-percolation/README | 1 + .../Racket/percolation-site-percolation.rkt | 81 ++++ .../Tcl/percolation-site-percolation.tcl | 77 +++ .../00DESCRIPTION | 48 ++ .../C/permutations-rank-of-a-permutation.c | 68 +++ .../D/permutations-rank-of-a-permutation.d | 63 +++ .../Go/permutations-rank-of-a-permutation.go | 82 ++++ .../permutations-rank-of-a-permutation.hs | 14 + .../J/permutations-rank-of-a-permutation.j | 25 + .../permutations-rank-of-a-permutation.java | 72 +++ .../permutations-rank-of-a-permutation.math | 14 + .../permutations-rank-of-a-permutation.pari | 3 + .../permutations-rank-of-a-permutation-1.py | 86 ++++ .../permutations-rank-of-a-permutation-2.py | 17 + .../Permutations-Rank-of-a-permutation/README | 1 + .../permutations-rank-of-a-permutation.rexx | 33 ++ .../permutations-rank-of-a-permutation.rkt | 15 + .../permutations-rank-of-a-permutation-1.rb | 38 ++ .../permutations-rank-of-a-permutation-2.rb | 20 + .../permutations-rank-of-a-permutation-1.tcl | 34 ++ .../permutations-rank-of-a-permutation-2.tcl | 24 + .../permutations-rank-of-a-permutation-3.tcl | 7 + Task/Pernicious-numbers/00DESCRIPTION | 12 + Task/Pernicious-numbers/00META.yaml | 2 + .../Ada/pernicious-numbers-1.ada | 40 ++ .../Ada/pernicious-numbers-2.ada | 14 + .../AutoHotkey/pernicious-numbers.ahk | 16 + .../C++/pernicious-numbers.cpp | 51 ++ .../Pernicious-numbers/C/pernicious-numbers.c | 25 + .../Common-Lisp/pernicious-numbers.lisp | 11 + .../D/pernicious-numbers-1.d | 7 + .../D/pernicious-numbers-2.d | 1 + .../Go/pernicious-numbers.go | 33 ++ .../Haskell/pernicious-numbers.hs | 17 + .../Icon/pernicious-numbers.icon | 16 + .../J/pernicious-numbers-1.j | 3 + .../J/pernicious-numbers-2.j | 4 + .../Java/pernicious-numbers.java | 29 ++ .../Mathematica/pernicious-numbers-1.math | 17 + .../Mathematica/pernicious-numbers-2.math | 1 + .../Mathematica/pernicious-numbers-3.math | 1 + .../Mathematica/pernicious-numbers-4.math | 1 + .../PARI-GP/pernicious-numbers.pari | 3 + .../Pascal/pernicious-numbers.pascal | 65 +++ .../Perl-6/pernicious-numbers.pl6 | 6 + .../Perl/pernicious-numbers-1.pl | 22 + .../Perl/pernicious-numbers-2.pl | 5 + .../Python/pernicious-numbers.py | 20 + Task/Pernicious-numbers/README | 1 + .../REXX/pernicious-numbers.rexx | 31 ++ .../Racket/pernicious-numbers.rkt | 21 + .../Ruby/pernicious-numbers.rb | 16 + .../Scala/pernicious-numbers.scala | 8 + .../Tcl/pernicious-numbers.tcl | 14 + Task/Phrase-reversals/00DESCRIPTION | 12 + .../Phrase-reversals/AWK/phrase-reversals.awk | 18 + .../Phrase-reversals/Ada/phrase-reversals.ada | 43 ++ .../AutoHotkey/phrase-reversals.ahk | 34 ++ .../Bracmat/phrase-reversals.bracmat | 16 + .../Phrase-reversals/C++/phrase-reversals.cpp | 37 ++ Task/Phrase-reversals/C/phrase-reversals.c | 70 +++ Task/Phrase-reversals/D/phrase-reversals.d | 8 + .../Phrase-reversals/Go/phrase-reversals-1.go | 35 ++ .../Phrase-reversals/Go/phrase-reversals-2.go | 54 +++ .../Groovy/phrase-reversals.groovy | 7 + .../Haskell/phrase-reversals.hs | 6 + Task/Phrase-reversals/J/phrase-reversals-1.j | 4 + Task/Phrase-reversals/J/phrase-reversals-2.j | 5 + .../Java/phrase-reversals.java | 36 ++ .../Mathematica/phrase-reversals.math | 13 + .../Phrase-reversals/PHP/phrase-reversals.php | 28 ++ .../Perl-6/phrase-reversals.pl6 | 6 + .../Phrase-reversals/Perl/phrase-reversals.pl | 9 + .../Python/phrase-reversals.py | 8 + Task/Phrase-reversals/README | 1 + .../REXX/phrase-reversals-1.rexx | 16 + .../REXX/phrase-reversals-2.rexx | 9 + .../Racket/phrase-reversals.rkt | 12 + .../Phrase-reversals/Ruby/phrase-reversals.rb | 5 + .../Phrase-reversals/Tcl/phrase-reversals.tcl | 7 + .../UNIX-Shell/phrase-reversals-1.sh | 14 + .../UNIX-Shell/phrase-reversals-2.sh | 26 + Task/Quickselect-algorithm/00DESCRIPTION | 5 + .../AutoHotkey/quickselect-algorithm.ahk | 39 ++ .../C++/quickselect-algorithm-1.cpp | 14 + .../C++/quickselect-algorithm-2.cpp | 37 ++ .../C/quickselect-algorithm.c | 35 ++ .../COBOL/quickselect-algorithm.cobol | 95 ++++ .../D/quickselect-algorithm-1.d | 9 + .../D/quickselect-algorithm-2.d | 48 ++ .../Go/quickselect-algorithm-1.go | 41 ++ .../Go/quickselect-algorithm-2.go | 55 +++ .../Haskell/quickselect-algorithm.hs | 13 + .../Icon/quickselect-algorithm.icon | 21 + .../J/quickselect-algorithm-1.j | 14 + .../J/quickselect-algorithm-2.j | 2 + .../J/quickselect-algorithm-3.j | 2 + .../Java/quickselect-algorithm.java | 53 ++ .../NetRexx/quickselect-algorithm.netrexx | 97 ++++ .../OCaml/quickselect-algorithm.ocaml | 10 + .../PARI-GP/quickselect-algorithm.pari | 28 ++ .../PL-I/quickselect-algorithm.pli | 59 +++ .../Perl-6/quickselect-algorithm.pl6 | 42 ++ .../Perl/quickselect-algorithm.pl | 19 + .../Python/quickselect-algorithm.py | 45 ++ Task/Quickselect-algorithm/README | 1 + .../REXX/quickselect-algorithm.rexx | 30 ++ .../Racket/quickselect-algorithm.rkt | 11 + .../Ruby/quickselect-algorithm.rb | 18 + .../Scala/quickselect-algorithm.scala | 20 + .../Standard-ML/quickselect-algorithm.ml | 12 + .../Tcl/quickselect-algorithm-1.tcl | 50 ++ .../Tcl/quickselect-algorithm-2.tcl | 4 + Task/RSA-code/00DESCRIPTION | 37 ++ Task/RSA-code/00META.yaml | 2 + Task/RSA-code/Common-Lisp/rsa-code.lisp | 32 ++ Task/RSA-code/D/rsa-code.d | 35 ++ Task/RSA-code/Go/rsa-code.go | 48 ++ Task/RSA-code/Icon/rsa-code.icon | 65 +++ Task/RSA-code/J/rsa-code.j | 16 + Task/RSA-code/Perl-6/rsa-code.pl6 | 44 ++ Task/RSA-code/PicoLisp/rsa-code.l | 116 +++++ Task/RSA-code/Python/rsa-code-1.py | 222 +++++++++ Task/RSA-code/Python/rsa-code-2.py | 186 +++++++ Task/RSA-code/Python/rsa-code-3.py | 18 + Task/RSA-code/README | 1 + Task/RSA-code/Racket/rsa-code.rkt | 172 +++++++ Task/RSA-code/Seed7/rsa-code.seed7 | 30 ++ Task/RSA-code/Tcl/rsa-code.tcl | 48 ++ Task/Ranking-methods/00DESCRIPTION | 23 + Task/Ranking-methods/AWK/ranking-methods.awk | 100 ++++ Task/Ranking-methods/Go/ranking-methods.go | 113 +++++ .../Haskell/ranking-methods.hs | 72 +++ Task/Ranking-methods/J/ranking-methods-1.j | 19 + Task/Ranking-methods/J/ranking-methods-2.j | 80 +++ .../Ranking-methods/Java/ranking-methods.java | 75 +++ .../Perl-6/ranking-methods.pl6 | 45 ++ .../Ranking-methods/Python/ranking-methods.py | 74 +++ Task/Ranking-methods/README | 1 + .../Racket/ranking-methods.rkt | 77 +++ Task/Ranking-methods/Ruby/ranking-methods.rb | 23 + .../Scala/ranking-methods.scala | 44 ++ Task/Ranking-methods/Tcl/ranking-methods.tcl | 56 +++ Task/Rep-string/00DESCRIPTION | 22 + Task/Rep-string/ALGOL-68/rep-string.alg | 68 +++ Task/Rep-string/Ada/rep-string.ada | 31 ++ Task/Rep-string/AutoHotkey/rep-string.ahk | 19 + Task/Rep-string/Bracmat/rep-string.bracmat | 36 ++ Task/Rep-string/C++/rep-string.cpp | 36 ++ Task/Rep-string/C/rep-string.c | 34 ++ Task/Rep-string/D/rep-string.d | 44 ++ Task/Rep-string/Go/rep-string.go | 38 ++ Task/Rep-string/Haskell/rep-string.hs | 45 ++ Task/Rep-string/Icon/rep-string.icon | 14 + Task/Rep-string/J/rep-string-1.j | 4 + Task/Rep-string/J/rep-string-2.j | 17 + Task/Rep-string/J/rep-string-3.j | 1 + Task/Rep-string/J/rep-string-4.j | 11 + Task/Rep-string/Java/rep-string.java | 30 ++ Task/Rep-string/Maple/rep-string-1.maple | 8 + Task/Rep-string/Maple/rep-string-2.maple | 16 + Task/Rep-string/Mathematica/rep-string-1.math | 1 + Task/Rep-string/Mathematica/rep-string-2.math | 2 + Task/Rep-string/NetRexx/rep-string.netrexx | 61 +++ Task/Rep-string/PARI-GP/rep-string.pari | 3 + Task/Rep-string/PL-I/rep-string.pli | 19 + Task/Rep-string/Perl-6/rep-string-1.pl6 | 9 + Task/Rep-string/Perl-6/rep-string-2.pl6 | 17 + Task/Rep-string/Perl/rep-string.pl | 8 + Task/Rep-string/Prolog/rep-string.pro | 32 ++ Task/Rep-string/Python/rep-string-1.py | 23 + Task/Rep-string/Python/rep-string-2.py | 30 ++ Task/Rep-string/Python/rep-string-3.py | 25 + Task/Rep-string/README | 1 + Task/Rep-string/REXX/rep-string-1.rexx | 52 ++ Task/Rep-string/REXX/rep-string-2.rexx | 13 + Task/Rep-string/Racket/rep-string.rkt | 26 + Task/Rep-string/Ruby/rep-string.rb | 16 + Task/Rep-string/Scala/rep-string.scala | 27 ++ Task/Rep-string/Seed7/rep-string.seed7 | 30 ++ Task/Rep-string/Tcl/rep-string-1.tcl | 11 + Task/Rep-string/Tcl/rep-string-2.tcl | 12 + Task/Rep-string/UNIX-Shell/rep-string.sh | 35 ++ Task/Reverse-words-in-a-string/00DESCRIPTION | 22 + .../AWK/reverse-words-in-a-string.awk | 22 + .../Ada/reverse-words-in-a-string-1.ada | 11 + .../Ada/reverse-words-in-a-string-2.ada | 20 + .../Ada/reverse-words-in-a-string-3.ada | 21 + .../Aime/reverse-words-in-a-string.aime | 32 ++ .../reverse-words-in-a-string.applesoft | 26 + .../AutoHotkey/reverse-words-in-a-string.ahk | 21 + .../BBC-BASIC/reverse-words-in-a-string.bbc | 16 + .../Bracmat/reverse-words-in-a-string.bracmat | 37 ++ .../C++/reverse-words-in-a-string-1.cpp | 60 +++ .../C++/reverse-words-in-a-string-2.cpp | 40 ++ .../C/reverse-words-in-a-string.c | 35 ++ .../Clojure/reverse-words-in-a-string.clj | 14 + .../reverse-words-in-a-string.lisp | 29 ++ .../D/reverse-words-in-a-string.d | 18 + .../Elixir/reverse-words-in-a-string-1.elixir | 10 + .../Elixir/reverse-words-in-a-string-2.elixir | 13 + .../Go/reverse-words-in-a-string.go | 36 ++ .../Groovy/reverse-words-in-a-string.groovy | 15 + .../Haskell/reverse-words-in-a-string.hs | 18 + .../Icon/reverse-words-in-a-string.icon | 14 + .../J/reverse-words-in-a-string.j | 22 + .../Java/reverse-words-in-a-string-1.java | 22 + .../Java/reverse-words-in-a-string-2.java | 39 ++ .../Julia/reverse-words-in-a-string.julia | 1 + .../Lua/reverse-words-in-a-string.lua | 19 + .../MATLAB/reverse-words-in-a-string.m | 25 + .../reverse-words-in-a-string.math | 16 + .../OCaml/reverse-words-in-a-string.ocaml | 16 + .../Objeck/reverse-words-in-a-string.objeck | 29 ++ .../PL-I/reverse-words-in-a-string.pli | 24 + .../Perl-6/reverse-words-in-a-string.pl6 | 1 + .../Perl/reverse-words-in-a-string.pl | 12 + .../Python/reverse-words-in-a-string-1.py | 13 + .../Python/reverse-words-in-a-string-2.py | 10 + Task/Reverse-words-in-a-string/README | 1 + .../REXX/reverse-words-in-a-string.rexx | 19 + .../Racket/reverse-words-in-a-string.rkt | 27 ++ .../Ruby/reverse-words-in-a-string.rb | 18 + .../Scala/reverse-words-in-a-string.scala | 17 + .../Scheme/reverse-words-in-a-string.ss | 14 + .../Seed7/reverse-words-in-a-string.seed7 | 28 ++ .../Smalltalk/reverse-words-in-a-string.st | 12 + .../Tcl/reverse-words-in-a-string-1.tcl | 17 + .../Tcl/reverse-words-in-a-string-2.tcl | 1 + .../UNIX-Shell/reverse-words-in-a-string-1.sh | 17 + .../UNIX-Shell/reverse-words-in-a-string-2.sh | 1 + .../UNIX-Shell/reverse-words-in-a-string-3.sh | 1 + .../rosetta-code-find-bare-lang-tags.ahk | 1 + .../C/rosetta-code-find-bare-lang-tags.c | 1 + .../Perl/rosetta-code-find-bare-lang-tags.pl | 1 + Task/Runge-Kutta-method/00DESCRIPTION | 19 + Task/Runge-Kutta-method/00META.yaml | 2 + .../AWK/runge-kutta-method.awk | 19 + .../Ada/runge-kutta-method.ada | 52 ++ .../BASIC/runge-kutta-method.basic | 15 + .../Runge-Kutta-method/C/runge-kutta-method.c | 37 ++ .../Runge-Kutta-method/D/runge-kutta-method.d | 38 ++ .../Dart/runge-kutta-method.dart | 27 ++ .../F-Sharp/runge-kutta-method.fs | 21 + .../Fortran/runge-kutta-method.f | 29 ++ .../Go/runge-kutta-method.go | 57 +++ .../Haskell/runge-kutta-method-1.hs | 17 + .../Haskell/runge-kutta-method-2.hs | 12 + .../J/runge-kutta-method-1.j | 18 + .../J/runge-kutta-method-2.j | 17 + .../J/runge-kutta-method-3.j | 17 + .../JavaScript/runge-kutta-method.js | 36 ++ .../Julia/runge-kutta-method.julia | 33 ++ .../MATLAB/runge-kutta-method.m | 37 ++ .../Mathematica/runge-kutta-method.math | 20 + .../Maxima/runge-kutta-method.maxima | 40 ++ .../OCaml/runge-kutta-method.ocaml | 16 + .../Octave/runge-kutta-method.octave | 8 + .../PARI-GP/runge-kutta-method.pari | 16 + .../PL-I/runge-kutta-method.pli | 25 + .../Pascal/runge-kutta-method.pascal | 71 +++ .../Perl-6/runge-kutta-method.pl6 | 21 + .../Perl/runge-kutta-method.pl | 22 + .../Python/runge-kutta-method.py | 21 + Task/Runge-Kutta-method/README | 1 + .../REXX/runge-kutta-method.rexx | 35 ++ .../Racket/runge-kutta-method-1.rkt | 8 + .../Racket/runge-kutta-method-2.rkt | 5 + .../Racket/runge-kutta-method-3.rkt | 10 + .../Racket/runge-kutta-method-4.rkt | 4 + .../Ruby/runge-kutta-method.rb | 27 ++ .../Run-BASIC/runge-kutta-method.run | 12 + .../Standard-ML/runge-kutta-method.ml | 41 ++ .../Tcl/runge-kutta-method.tcl | 33 ++ Task/Semiprime/00DESCRIPTION | 3 + Task/Semiprime/00META.yaml | 2 + Task/Semiprime/Ada/semiprime.ada | 21 + Task/Semiprime/AutoHotkey/semiprime.ahk | 55 +++ Task/Semiprime/C++/semiprime.cpp | 21 + Task/Semiprime/C/semiprime.c | 21 + Task/Semiprime/Common-Lisp/semiprime.lisp | 9 + Task/Semiprime/D/semiprime.d | 19 + Task/Semiprime/Forth/semiprime.fth | 8 + Task/Semiprime/Go/semiprime.go | 23 + Task/Semiprime/Haskell/semiprime-1.hs | 4 + Task/Semiprime/Haskell/semiprime-2.hs | 4 + Task/Semiprime/Icon/semiprime.icon | 9 + Task/Semiprime/J/semiprime-1.j | 1 + Task/Semiprime/J/semiprime-2.j | 2 + Task/Semiprime/Java/semiprime.java | 57 +++ Task/Semiprime/Julia/semiprime.julia | 1 + Task/Semiprime/Mathematica/semiprime-1.math | 5 + Task/Semiprime/Mathematica/semiprime-2.math | 2 + Task/Semiprime/Objeck/semiprime.objeck | 25 + Task/Semiprime/PARI-GP/semiprime-1.pari | 1 + Task/Semiprime/PARI-GP/semiprime-2.pari | 5 + Task/Semiprime/PARI-GP/semiprime-3.pari | 77 +++ Task/Semiprime/PL-I/semiprime.pli | 89 ++++ Task/Semiprime/Pascal/semiprime.pascal | 41 ++ Task/Semiprime/Perl-6/semiprime.pl6 | 15 + Task/Semiprime/Perl/semiprime-1.pl | 4 + Task/Semiprime/Perl/semiprime-2.pl | 9 + Task/Semiprime/PicoLisp/semiprime.l | 21 + Task/Semiprime/Python/semiprime-1.py | 8 + Task/Semiprime/Python/semiprime-2.py | 5 + Task/Semiprime/README | 1 + Task/Semiprime/REXX/semiprime-1.rexx | 56 +++ Task/Semiprime/REXX/semiprime-2.rexx | 30 ++ Task/Semiprime/Racket/semiprime-1.rkt | 15 + Task/Semiprime/Racket/semiprime-2.rkt | 12 + Task/Semiprime/Ruby/semiprime.rb | 12 + Task/Semiprime/Scala/semiprime.scala | 20 + Task/Semiprime/Seed7/semiprime.seed7 | 27 ++ Task/Semiprime/Tcl/semiprime.tcl | 24 + .../00DESCRIPTION | 7 + .../00META.yaml | 2 + .../sequence-of-primes-by-trial-division.ats | 70 +++ .../sequence-of-primes-by-trial-division.ada | 18 + .../D/sequence-of-primes-by-trial-division.d | 23 + .../sequence-of-primes-by-trial-division-1.go | 52 ++ .../sequence-of-primes-by-trial-division-2.go | 32 ++ .../sequence-of-primes-by-trial-division-1.hs | 1 + .../sequence-of-primes-by-trial-division-2.hs | 3 + .../sequence-of-primes-by-trial-division-3.hs | 2 + .../sequence-of-primes-by-trial-division-4.hs | 5 + .../sequence-of-primes-by-trial-division-5.hs | 6 + .../sequence-of-primes-by-trial-division-6.hs | 8 + .../sequence-of-primes-by-trial-division-7.hs | 6 + .../sequence-of-primes-by-trial-division-1.j | 5 + .../sequence-of-primes-by-trial-division-2.j | 2 + .../sequence-of-primes-by-trial-division.pl6 | 3 + .../README | 1 + ...equence-of-primes-by-trial-division-1.rexx | 18 + ...equence-of-primes-by-trial-division-2.rexx | 26 + ...sequence-of-primes-by-trial-division-1.rkt | 6 + ...sequence-of-primes-by-trial-division-2.rkt | 10 + ...sequence-of-primes-by-trial-division-3.rkt | 18 + ...sequence-of-primes-by-trial-division-4.rkt | 10 + .../sequence-of-primes-by-trial-division.rb | 5 + ...sequence-of-primes-by-trial-division.scala | 6 + .../sequence-of-primes-by-trial-division.tcl | 16 + Task/Solve-a-Holy-Knights-tour/00DESCRIPTION | 24 + .../Ada/solve-a-holy-knights-tour.ada | 36 ++ .../Bracmat/solve-a-holy-knights-tour.bracmat | 213 ++++++++ .../C++/solve-a-holy-knights-tour.cpp | 135 ++++++ .../D/solve-a-holy-knights-tour.d | 133 +++++ .../Haskell/solve-a-holy-knights-tour-1.hs | 105 ++++ .../Haskell/solve-a-holy-knights-tour-2.hs | 128 +++++ .../Haskell/solve-a-holy-knights-tour-3.hs | 98 ++++ .../J/solve-a-holy-knights-tour-1.j | 33 ++ .../J/solve-a-holy-knights-tour-2.j | 2 + .../J/solve-a-holy-knights-tour-3.j | 9 + .../J/solve-a-holy-knights-tour-4.j | 18 + .../J/solve-a-holy-knights-tour-5.j | 43 ++ .../J/solve-a-holy-knights-tour-6.j | 9 + .../J/solve-a-holy-knights-tour-7.j | 15 + .../J/solve-a-holy-knights-tour-8.j | 14 + .../Perl-6/solve-a-holy-knights-tour.pl6 | 16 + Task/Solve-a-Holy-Knights-tour/README | 1 + .../REXX/solve-a-holy-knights-tour.rexx | 62 +++ .../Racket/solve-a-holy-knights-tour.rkt | 38 ++ .../Ruby/solve-a-holy-knights-tour.rb | 17 + .../Tcl/solve-a-holy-knights-tour.tcl | 98 ++++ Task/Solve-a-Hopido-puzzle/00DESCRIPTION | 22 + .../C++/solve-a-hopido-puzzle.cpp | 133 +++++ .../D/solve-a-hopido-puzzle-1.d | 114 +++++ .../D/solve-a-hopido-puzzle-2.d | 98 ++++ .../Perl-6/solve-a-hopido-puzzle.pl6 | 14 + Task/Solve-a-Hopido-puzzle/README | 1 + .../REXX/solve-a-hopido-puzzle.rexx | 57 +++ .../Racket/solve-a-hopido-puzzle.rkt | 17 + .../Ruby/solve-a-hopido-puzzle.rb | 15 + .../Tcl/solve-a-hopido-puzzle.tcl | 96 ++++ Task/Solve-a-Numbrix-puzzle/00DESCRIPTION | 65 +++ .../C++/solve-a-numbrix-puzzle.cpp | 155 ++++++ .../D/solve-a-numbrix-puzzle-1.d | 209 ++++++++ .../D/solve-a-numbrix-puzzle-2.d | 90 ++++ .../Perl-6/solve-a-numbrix-puzzle-1.pl6 | 15 + .../Perl-6/solve-a-numbrix-puzzle-2.pl6 | 11 + Task/Solve-a-Numbrix-puzzle/README | 1 + .../REXX/solve-a-numbrix-puzzle.rexx | 53 ++ .../Racket/solve-a-numbrix-puzzle-1.rkt | 95 ++++ .../Racket/solve-a-numbrix-puzzle-2.rkt | 35 ++ .../Ruby/solve-a-numbrix-puzzle.rb | 29 ++ .../00DESCRIPTION | 42 ++ .../00META.yaml | 4 + .../Ada/solve-the-no-connection-puzzle-1.ada | 10 + .../Ada/solve-the-no-connection-puzzle-2.ada | 47 ++ .../Ada/solve-the-no-connection-puzzle-3.ada | 6 + .../Ada/solve-the-no-connection-puzzle-4.ada | 73 +++ .../Ada/solve-the-no-connection-puzzle-5.ada | 73 +++ .../D/solve-the-no-connection-puzzle-1.d | 27 ++ .../D/solve-the-no-connection-puzzle-2.d | 65 +++ .../Go/solve-the-no-connection-puzzle.go | 90 ++++ .../J/solve-the-no-connection-puzzle-1.j | 34 ++ .../J/solve-the-no-connection-puzzle-2.j | 17 + .../J/solve-the-no-connection-puzzle-3.j | 10 + .../Perl-6/solve-the-no-connection-puzzle.pl6 | 11 + .../Prolog/solve-the-no-connection-puzzle.pro | 54 +++ .../solve-the-no-connection-puzzle-1.py | 27 ++ .../solve-the-no-connection-puzzle-2.py | 21 + Task/Solve-the-no-connection-puzzle/README | 1 + .../solve-the-no-connection-puzzle-1.rexx | 55 +++ .../solve-the-no-connection-puzzle-2.rexx | 76 +++ .../Racket/solve-the-no-connection-puzzle.rkt | 43 ++ .../Ruby/solve-the-no-connection-puzzle.rb | 24 + .../Tcl/solve-the-no-connection-puzzle.tcl | 45 ++ .../XPL0/solve-the-no-connection-puzzle.xpl0 | 37 ++ Task/Sparkline-in-unicode/00DESCRIPTION | 19 + .../AutoHotkey/sparkline-in-unicode.ahk | 23 + .../C++/sparkline-in-unicode.cpp | 68 +++ .../D/sparkline-in-unicode.d | 16 + .../Elixir/sparkline-in-unicode-1.elixir | 8 + .../Elixir/sparkline-in-unicode-2.elixir | 6 + .../FALSE/sparkline-in-unicode.false | 68 +++ .../Go/sparkline-in-unicode.go | 74 +++ .../Groovy/sparkline-in-unicode-1.groovy | 6 + .../Groovy/sparkline-in-unicode-2.groovy | 4 + .../Haskell/sparkline-in-unicode.hs | 39 ++ .../J/sparkline-in-unicode-1.j | 7 + .../J/sparkline-in-unicode-2.j | 1 + .../J/sparkline-in-unicode-3.j | 1 + .../J/sparkline-in-unicode-4.j | 4 + .../Java/sparkline-in-unicode.java | 41 ++ .../Mathematica/sparkline-in-unicode.math | 1 + .../NetRexx/sparkline-in-unicode.netrexx | 54 +++ .../Perl-6/sparkline-in-unicode.pl6 | 8 + .../Perl/sparkline-in-unicode.pl | 19 + .../Python/sparkline-in-unicode.py | 17 + Task/Sparkline-in-unicode/README | 1 + .../REXX/sparkline-in-unicode-1.rexx | 67 +++ .../REXX/sparkline-in-unicode-2.rexx | 26 + .../Racket/sparkline-in-unicode-1.rkt | 13 + .../Racket/sparkline-in-unicode-2.rkt | 2 + .../Ruby/sparkline-in-unicode.rb | 8 + .../Scala/sparkline-in-unicode.scala | 16 + .../Seed7/sparkline-in-unicode.seed7 | 53 ++ .../Tcl/sparkline-in-unicode-1.tcl | 15 + .../Tcl/sparkline-in-unicode-2.tcl | 8 + Task/State-name-puzzle/00DESCRIPTION | 40 ++ Task/State-name-puzzle/00META.yaml | 2 + .../Bracmat/state-name-puzzle.bracmat | 91 ++++ Task/State-name-puzzle/C/state-name-puzzle.c | 106 ++++ Task/State-name-puzzle/D/state-name-puzzle.d | 28 ++ .../State-name-puzzle/Go/state-name-puzzle.go | 77 +++ .../Icon/state-name-puzzle-1.icon | 49 ++ .../Icon/state-name-puzzle-2.icon | 21 + .../Icon/state-name-puzzle-3.icon | 58 +++ .../State-name-puzzle/J/state-name-puzzle-1.j | 21 + .../State-name-puzzle/J/state-name-puzzle-2.j | 6 + .../State-name-puzzle/J/state-name-puzzle-3.j | 2 + .../State-name-puzzle/J/state-name-puzzle-4.j | 96 ++++ .../Java/state-name-puzzle.java | 60 +++ .../Mathematica/state-name-puzzle.math | 13 + .../Perl-6/state-name-puzzle.pl6 | 36 ++ .../Perl/state-name-puzzle.pl | 65 +++ .../PicoLisp/state-name-puzzle.l | 41 ++ .../Prolog/state-name-puzzle.pro | 70 +++ .../Python/state-name-puzzle.py | 26 + Task/State-name-puzzle/README | 1 + .../REXX/state-name-puzzle.rexx | 88 ++++ .../Racket/state-name-puzzle-1.rkt | 30 ++ .../Racket/state-name-puzzle-2.rkt | 1 + .../Ruby/state-name-puzzle.rb | 45 ++ .../Scala/state-name-puzzle.scala | 26 + .../Tcl/state-name-puzzle.tcl | 67 +++ Task/Statistics-Basic/00DESCRIPTION | 25 + Task/Statistics-Basic/00META.yaml | 2 + .../Ada/statistics-basic-1.ada | 63 +++ .../Ada/statistics-basic-2.ada | 77 +++ Task/Statistics-Basic/C/statistics-basic.c | 102 ++++ .../CoffeeScript/statistics-basic.coffee | 36 ++ Task/Statistics-Basic/D/statistics-basic.d | 45 ++ .../Dart/statistics-basic.dart | 99 ++++ .../Fortran/statistics-basic.f | 36 ++ .../Statistics-Basic/Go/statistics-basic-1.go | 41 ++ .../Statistics-Basic/Go/statistics-basic-2.go | 64 +++ .../Icon/statistics-basic.icon | 26 + Task/Statistics-Basic/J/statistics-basic-1.j | 7 + Task/Statistics-Basic/J/statistics-basic-2.j | 3 + Task/Statistics-Basic/J/statistics-basic-3.j | 23 + Task/Statistics-Basic/J/statistics-basic-4.j | 36 ++ .../Liberty-BASIC/statistics-basic.liberty | 41 ++ .../MATLAB/statistics-basic.m | 20 + .../Mathematica/statistics-basic.math | 4 + .../PARI-GP/statistics-basic-1.pari | 21 + .../PARI-GP/statistics-basic-2.pari | 4 + .../PL-I/statistics-basic.pli | 39 ++ .../Perl-6/statistics-basic.pl6 | 10 + .../Statistics-Basic/Perl/statistics-basic.pl | 24 + .../PicoLisp/statistics-basic-1.l | 21 + .../PicoLisp/statistics-basic-2.l | 11 + .../PureBasic/statistics-basic.purebasic | 56 +++ .../Python/statistics-basic.py | 39 ++ Task/Statistics-Basic/README | 1 + .../REXX/statistics-basic.rexx | 38 ++ .../Racket/statistics-basic.rkt | 21 + .../Statistics-Basic/Ruby/statistics-basic.rb | 20 + .../Scala/statistics-basic.scala | 21 + .../Statistics-Basic/Tcl/statistics-basic.tcl | 27 ++ Task/Stern-Brocot-sequence/00DESCRIPTION | 35 ++ .../C/stern-brocot-sequence-1.c | 38 ++ .../C/stern-brocot-sequence-2.c | 10 + .../Clojure/stern-brocot-sequence.clj | 18 + .../D/stern-brocot-sequence-1.d | 29 ++ .../D/stern-brocot-sequence-2.d | 18 + .../D/stern-brocot-sequence-3.d | 28 ++ .../Go/stern-brocot-sequence-1.go | 48 ++ .../Go/stern-brocot-sequence-2.go | 74 +++ .../Haskell/stern-brocot-sequence.hs | 9 + .../J/stern-brocot-sequence-1.j | 8 + .../J/stern-brocot-sequence-2.j | 2 + .../J/stern-brocot-sequence-3.j | 2 + .../J/stern-brocot-sequence-4.j | 2 + .../J/stern-brocot-sequence-5.j | 2 + .../Java/stern-brocot-sequence.java | 34 ++ .../Perl-6/stern-brocot-sequence.pl6 | 12 + .../Perl/stern-brocot-sequence.pl | 36 ++ .../Python/stern-brocot-sequence-1.py | 36 ++ .../Python/stern-brocot-sequence-2.py | 22 + Task/Stern-Brocot-sequence/README | 1 + .../REXX/stern-brocot-sequence.rexx | 45 ++ .../Racket/stern-brocot-sequence.rkt | 38 ++ .../Ruby/stern-brocot-sequence.rb | 20 + .../VBScript/stern-brocot-sequence.vb | 40 ++ Task/String-append/00DESCRIPTION | 6 + Task/String-append/00META.yaml | 5 + Task/String-append/ALGOL-68/string-append.alg | 6 + Task/String-append/AWK/string-append.awk | 7 + .../AutoHotkey/string-append.ahk | 3 + .../String-append/BASIC/string-append-1.basic | 3 + .../String-append/BASIC/string-append-2.basic | 4 + Task/String-append/C++/string-append.cpp | 9 + Task/String-append/C/string-append.c | 25 + .../String-append/Clojure/string-append-1.clj | 8 + .../String-append/Clojure/string-append-2.clj | 2 + .../Common-Lisp/string-append.lisp | 8 + Task/String-append/D/string-append.d | 7 + .../Euphoria/string-append.euphoria | 7 + Task/String-append/Go/string-append.go | 2 + Task/String-append/Haskell/string-append.hs | 1 + Task/String-append/Icon/string-append.icon | 5 + Task/String-append/J/string-append.j | 6 + Task/String-append/Java/string-append.java | 8 + .../String-append/JavaScript/string-append.js | 8 + Task/String-append/Julia/string-append.julia | 2 + .../Mathematica/string-append.math | 4 + .../NetRexx/string-append.netrexx | 3 + .../NewLISP/string-append.newlisp | 3 + Task/String-append/OCaml/string-append.ocaml | 5 + .../String-append/Objeck/string-append.objeck | 7 + Task/String-append/PARI-GP/string-append.pari | 2 + Task/String-append/PL-I/string-append.pli | 6 + .../String-append/Pascal/string-append.pascal | 17 + Task/String-append/Perl-6/string-append.pl6 | 3 + Task/String-append/Perl/string-append.pl | 3 + Task/String-append/PicoLisp/string-append.l | 3 + .../PureBasic/string-append.purebasic | 9 + Task/String-append/Python/string-append.py | 6 + Task/String-append/README | 1 + Task/String-append/REXX/string-append-1.rexx | 3 + Task/String-append/REXX/string-append-2.rexx | 3 + Task/String-append/Racket/string-append.rkt | 12 + Task/String-append/Ruby/string-append.rb | 4 + Task/String-append/Scala/string-append.scala | 8 + Task/String-append/Seed7/string-append.seed7 | 9 + Task/String-append/Tcl/string-append.tcl | 4 + Task/String-append/VBA/string-append.vba | 6 + .../00DESCRIPTION | 0 .../00META.yaml | 0 .../ALGOL-68/string-matching.alg} | 0 Task/String-matching/AWK/string-matching.awk | 20 + .../Ada/string-matching.ada} | 0 .../String-matching/Aime/string-matching.aime | 23 + .../AutoHotkey/string-matching.ahk} | 0 .../AutoIt/string-matching.autoit} | 0 .../BASIC/string-matching-1.basic} | 0 .../BASIC/string-matching-2.basic | 18 + .../BBC-BASIC/string-matching.bbc} | 0 .../Bracmat/string-matching.bracmat} | 0 .../C++/string-matching.cpp} | 0 .../C/string-matching-1.c} | 0 .../C/string-matching-2.c} | 0 .../Clojure/string-matching.clj} | 0 .../CoffeeScript/string-matching.coffee} | 0 .../Common-Lisp/string-matching.lisp | 28 ++ .../string-matching.component | 113 +++++ Task/String-matching/D/string-matching.d | 16 + .../Delphi/string-matching.delphi} | 0 .../E/string-matching.e} | 0 .../Elena/string-matching.elena | 22 + .../Elixir/string-matching.elixir | 18 + .../Erlang/string-matching.erl} | 0 .../Euphoria/string-matching.euphoria} | 0 .../FBSL/string-matching.fbsl} | 0 .../Fantom/string-matching.fantom} | 0 .../Forth/string-matching.fth} | 0 .../GML/string-matching.gml} | 0 .../Go/string-matching.go} | 0 .../Groovy/string-matching.groovy | 23 + .../Haskell/string-matching-1.hs} | 0 .../Haskell/string-matching-2.hs} | 0 .../J/string-matching-1.j} | 0 .../J/string-matching-2.j} | 0 .../J/string-matching-3.j} | 0 .../Java/string-matching.java} | 0 .../JavaScript/string-matching.js} | 0 .../Julia/string-matching.julia} | 0 .../K/string-matching-1.k} | 0 .../K/string-matching-2.k} | 0 .../Lang5/string-matching.lang5} | 0 .../Liberty-BASIC/string-matching.liberty} | 0 .../Logo/string-matching.logo} | 0 .../Lua/string-matching.lua} | 0 .../MATLAB/string-matching.m} | 0 .../Maple/string-matching.maple} | 0 .../Mathematica/string-matching.math} | 0 .../NetRexx/string-matching.netrexx} | 0 .../NewLISP/string-matching.newlisp | 18 + .../OCaml/string-matching-1.ocaml} | 0 .../OCaml/string-matching-2.ocaml} | 0 .../OCaml/string-matching-3.ocaml} | 0 .../OCaml/string-matching-4.ocaml} | 0 .../OCaml/string-matching-5.ocaml} | 0 .../Objeck/string-matching.objeck} | 0 .../Objective-C/string-matching.m} | 0 .../OxygenBasic/string-matching.oxy} | 0 .../PARI-GP/string-matching.pari} | 0 .../PHP/string-matching-1.php} | 0 .../PHP/string-matching-2.php} | 0 .../PL-I/string-matching-1.pli} | 0 .../PL-I/string-matching-2.pli} | 0 .../Perl-6/string-matching.pl6} | 0 .../String-matching/Perl/string-matching-1.pl | 3 + .../String-matching/Perl/string-matching-2.pl | 3 + .../String-matching/Perl/string-matching-3.pl | 2 + .../String-matching/Perl/string-matching-4.pl | 1 + .../String-matching/Perl/string-matching-5.pl | 1 + .../PicoLisp/string-matching.l} | 0 .../PowerShell/string-matching.psh} | 0 .../PureBasic/string-matching-1.purebasic} | 0 .../PureBasic/string-matching-2.purebasic} | 0 .../PureBasic/string-matching-3.purebasic} | 0 .../Python/string-matching.py} | 0 Task/String-matching/README | 1 + .../String-matching/REXX/string-matching.rexx | 33 ++ .../Racket/string-matching.rkt} | 0 .../Retro/string-matching.retro} | 0 .../Ruby/string-matching.rb} | 0 .../Run-BASIC/string-matching.run} | 0 .../Scala/string-matching.scala} | 0 .../Seed7/string-matching.seed7} | 0 .../Smalltalk/string-matching.st} | 0 .../Standard-ML/string-matching.ml} | 0 .../TUSCRIPT/string-matching.tu} | 0 .../String-matching/TXR/string-matching-1.txr | 18 + .../TXR/string-matching-2.txr} | 0 .../Tcl/string-matching-1.tcl} | 0 .../Tcl/string-matching-2.tcl} | 0 .../Tcl/string-matching-3.tcl} | 0 .../Tcl/string-matching-4.tcl} | 0 .../XPL0/string-matching.xpl0} | 0 Task/String-prepend/00DESCRIPTION | 9 + Task/String-prepend/00META.yaml | 2 + .../ALGOL-68/string-prepend.alg | 6 + Task/String-prepend/AWK/string-prepend.awk | 7 + .../AutoHotkey/string-prepend.ahk | 3 + .../String-prepend/BASIC/string-prepend.basic | 3 + .../Bracmat/string-prepend.bracmat | 3 + Task/String-prepend/C++/string-prepend.cpp | 13 + Task/String-prepend/C-sharp/string-prepend.cs | 15 + Task/String-prepend/C/string-prepend.c | 14 + .../String-prepend/COBOL/string-prepend.cobol | 12 + .../String-prepend/Clojure/string-prepend.clj | 5 + .../Common-Lisp/string-prepend.lisp | 7 + Task/String-prepend/D/string-prepend.d | 7 + .../String-prepend/Deja-Vu/string-prepend.djv | 3 + .../Factor/string-prepend.factor | 2 + Task/String-prepend/Go/string-prepend.go | 2 + Task/String-prepend/Haskell/string-prepend.hs | 2 + Task/String-prepend/Icon/string-prepend.icon | 2 + Task/String-prepend/J/string-prepend.j | 6 + Task/String-prepend/Java/string-prepend.java | 7 + .../String-prepend/Julia/string-prepend.julia | 2 + Task/String-prepend/Lua/string-prepend-1.lua | 3 + Task/String-prepend/Lua/string-prepend-2.lua | 3 + Task/String-prepend/Lua/string-prepend-3.lua | 3 + .../Mathematica/string-prepend.math | 2 + .../Mercury/string-prepend.mercury | 9 + .../NetRexx/string-prepend.netrexx | 3 + .../NewLISP/string-prepend.newlisp | 3 + .../PARI-GP/string-prepend.pari | 2 + Task/String-prepend/PL-I/string-prepend.pli | 6 + .../Pascal/string-prepend.pascal | 17 + Task/String-prepend/Perl-6/string-prepend.pl6 | 24 + Task/String-prepend/Perl/string-prepend.pl | 3 + Task/String-prepend/PicoLisp/string-prepend.l | 3 + .../Prolog/string-prepend-1.pro | 12 + .../Prolog/string-prepend-2.pro | 2 + .../PureBasic/string-prepend.purebasic | 8 + Task/String-prepend/Python/string-prepend.py | 6 + Task/String-prepend/README | 1 + Task/String-prepend/REXX/string-prepend.rexx | 17 + Task/String-prepend/Racket/string-prepend.rkt | 12 + Task/String-prepend/Ruby/string-prepend.rb | 3 + .../String-prepend/Scala/string-prepend.scala | 5 + .../String-prepend/Seed7/string-prepend.seed7 | 9 + Task/String-prepend/Tcl/string-prepend.tcl | 3 + Task/String-prepend/VBA/string-prepend.vba | 6 + Task/Sum-multiples-of-3-and-5/00DESCRIPTION | 9 + .../AWK/sum-multiples-of-3-and-5-1.awk | 9 + .../AWK/sum-multiples-of-3-and-5-2.awk | 13 + .../AutoHotkey/sum-multiples-of-3-and-5.ahk | 35 ++ .../C++/sum-multiples-of-3-and-5.cpp | 42 ++ .../C/sum-multiples-of-3-and-5-1.c | 24 + .../C/sum-multiples-of-3-and-5-2.c | 53 ++ .../COBOL/sum-multiples-of-3-and-5-1.cobol | 23 + .../COBOL/sum-multiples-of-3-and-5-2.cobol | 47 ++ .../Clojure/sum-multiples-of-3-and-5-1.clj | 6 + .../Clojure/sum-multiples-of-3-and-5-2.clj | 6 + .../sum-multiples-of-3-and-5-1.lisp | 4 + .../sum-multiples-of-3-and-5-2.lisp | 6 + .../sum-multiples-of-3-and-5.component | 26 + .../D/sum-multiples-of-3-and-5.d | 15 + .../Deja-Vu/sum-multiples-of-3-and-5.djv | 7 + .../Delphi/sum-multiples-of-3-and-5.delphi | 22 + .../Eiffel/sum-multiples-of-3-and-5-1.e | 27 ++ .../Eiffel/sum-multiples-of-3-and-5-2.e | 15 + .../Erlang/sum-multiples-of-3-and-5.erl | 8 + .../FBSL/sum-multiples-of-3-and-5.fbsl | 14 + .../Forth/sum-multiples-of-3-and-5-1.fth | 12 + .../Forth/sum-multiples-of-3-and-5-2.fth | 42 ++ .../Go/sum-multiples-of-3-and-5-1.go | 16 + .../Go/sum-multiples-of-3-and-5-2.go | 31 ++ .../Groovy/sum-multiples-of-3-and-5-1.groovy | 2 + .../Groovy/sum-multiples-of-3-and-5-2.groovy | 4 + .../Haskell/sum-multiples-of-3-and-5.hs | 18 + .../Icon/sum-multiples-of-3-and-5.icon | 8 + .../J/sum-multiples-of-3-and-5-1.j | 3 + .../J/sum-multiples-of-3-and-5-2.j | 7 + .../J/sum-multiples-of-3-and-5-3.j | 25 + .../Java/sum-multiples-of-3-and-5.java | 12 + .../Julia/sum-multiples-of-3-and-5-1.julia | 1 + .../Julia/sum-multiples-of-3-and-5-2.julia | 2 + .../Limbo/sum-multiples-of-3-and-5.limbo | 72 +++ .../MATLAB/sum-multiples-of-3-and-5-1.m | 1 + .../MATLAB/sum-multiples-of-3-and-5-2.m | 1 + .../MATLAB/sum-multiples-of-3-and-5-3.m | 5 + .../Maple/sum-multiples-of-3-and-5.maple | 7 + .../sum-multiples-of-3-and-5-1.math | 5 + .../sum-multiples-of-3-and-5-2.math | 1 + .../sum-multiples-of-3-and-5-3.math | 1 + .../Maxima/sum-multiples-of-3-and-5.maxima | 7 + .../NetRexx/sum-multiples-of-3-and-5.netrexx | 77 +++ .../PARI-GP/sum-multiples-of-3-and-5.pari | 4 + .../PL-I/sum-multiples-of-3-and-5.pli | 13 + .../Pascal/sum-multiples-of-3-and-5.pascal | 23 + .../Perl-6/sum-multiples-of-3-and-5-1.pl6 | 3 + .../Perl-6/sum-multiples-of-3-and-5-2.pl6 | 10 + .../Perl/sum-multiples-of-3-and-5-1.pl | 11 + .../Perl/sum-multiples-of-3-and-5-2.pl | 15 + .../PicoLisp/sum-multiples-of-3-and-5.l | 12 + .../PowerShell/sum-multiples-of-3-and-5.psh | 31 ++ .../Prolog/sum-multiples-of-3-and-5-1.pro | 15 + .../Prolog/sum-multiples-of-3-and-5-2.pro | 9 + .../Python/sum-multiples-of-3-and-5.py | 32 ++ .../R/sum-multiples-of-3-and-5.r | 3 + Task/Sum-multiples-of-3-and-5/README | 1 + .../REXX/sum-multiples-of-3-and-5-1.rexx | 12 + .../REXX/sum-multiples-of-3-and-5-2.rexx | 24 + .../REXX/sum-multiples-of-3-and-5-3.rexx | 15 + .../Racket/sum-multiples-of-3-and-5-1.rkt | 26 + .../Racket/sum-multiples-of-3-and-5-2.rkt | 21 + .../Ruby/sum-multiples-of-3-and-5-1.rb | 4 + .../Ruby/sum-multiples-of-3-and-5-2.rb | 13 + .../Ruby/sum-multiples-of-3-and-5-3.rb | 12 + .../Run-BASIC/sum-multiples-of-3-and-5.run | 7 + .../Scala/sum-multiples-of-3-and-5.scala | 21 + .../Scheme/sum-multiples-of-3-and-5-1.ss | 1 + .../Scheme/sum-multiples-of-3-and-5-2.ss | 8 + .../Scheme/sum-multiples-of-3-and-5-3.ss | 10 + .../Seed7/sum-multiples-of-3-and-5.seed7 | 25 + .../Tcl/sum-multiples-of-3-and-5-1.tcl | 17 + .../Tcl/sum-multiples-of-3-and-5-2.tcl | 9 + .../Tcl/sum-multiples-of-3-and-5-3.tcl | 4 + .../XPL0/sum-multiples-of-3-and-5.xpl0 | 42 ++ Task/Textonyms/00DESCRIPTION | 33 ++ Task/Textonyms/Go/textonyms.go | 141 ++++++ Task/Textonyms/J/textonyms-1.j | 38 ++ Task/Textonyms/J/textonyms-2.j | 4 + Task/Textonyms/J/textonyms-3.j | 12 + Task/Textonyms/J/textonyms-4.j | 4 + Task/Textonyms/Perl-6/textonyms.pl6 | 22 + Task/Textonyms/Perl/textonyms.pl | 7 + Task/Textonyms/Python/textonyms.py | 62 +++ Task/Textonyms/README | 1 + Task/Textonyms/REXX/textonyms.rexx | 47 ++ Task/Textonyms/Ruby/textonyms.rb | 7 + Task/Textonyms/VBScript/textonyms.vb | 47 ++ Task/The-ISAAC-Cipher/00DESCRIPTION | 56 +++ Task/The-ISAAC-Cipher/00META.yaml | 2 + .../C-sharp/the-isaac-cipher.cs | 159 ++++++ Task/The-ISAAC-Cipher/C/the-isaac-cipher.c | 231 +++++++++ Task/The-ISAAC-Cipher/D/the-isaac-cipher.d | 165 +++++++ .../Delphi/the-isaac-cipher.delphi | 198 ++++++++ Task/The-ISAAC-Cipher/Go/the-isaac-cipher.go | 119 +++++ .../Haskell/the-isaac-cipher.hs | 127 +++++ .../Haxe/the-isaac-cipher.haxe | 161 ++++++ .../Java/the-isaac-cipher.java | 225 +++++++++ .../Pascal/the-isaac-cipher.pascal | 213 ++++++++ .../The-ISAAC-Cipher/Perl/the-isaac-cipher.pl | 31 ++ .../PicoLisp/the-isaac-cipher.l | 105 ++++ .../Python/the-isaac-cipher.py | 196 ++++++++ Task/The-ISAAC-Cipher/README | 1 + .../REXX/the-isaac-cipher-1.rexx | 208 ++++++++ .../REXX/the-isaac-cipher-2.rexx | 239 +++++++++ .../Racket/the-isaac-cipher.rkt | 255 ++++++++++ .../Tcl/the-isaac-cipher-1.tcl | 110 +++++ .../Tcl/the-isaac-cipher-2.tcl | 6 + .../00DESCRIPTION | 4 + .../AWK/the-twelve-days-of-christmas.awk | 25 + .../the-twelve-days-of-christmas.as | 111 +++++ .../Ada/the-twelve-days-of-christmas.ada | 36 ++ .../the-twelve-days-of-christmas.ahk | 22 + .../the-twelve-days-of-christmas.bracmat | 38 ++ .../C++/the-twelve-days-of-christmas.cpp | 59 +++ .../C/the-twelve-days-of-christmas.c | 52 ++ .../COBOL/the-twelve-days-of-christmas.cobol | 44 ++ .../Clojure/the-twelve-days-of-christmas.clj | 16 + .../D/the-twelve-days-of-christmas.d | 29 ++ .../Go/the-twelve-days-of-christmas.go | 33 ++ .../the-twelve-days-of-christmas.groovy | 12 + .../Icon/the-twelve-days-of-christmas.icon | 13 + .../J/the-twelve-days-of-christmas.j | 26 + .../Java/the-twelve-days-of-christmas.java | 26 + .../the-twelve-days-of-christmas.js | 42 ++ .../LOLCODE/the-twelve-days-of-christmas.lol | 53 ++ .../Logo/the-twelve-days-of-christmas.logo | 21 + .../Lua/the-twelve-days-of-christmas.lua | 38 ++ .../the-twelve-days-of-christmas.math | 16 + .../the-twelve-days-of-christmas.objeck | 35 ++ .../PHP/the-twelve-days-of-christmas.php | 46 ++ .../Perl-6/the-twelve-days-of-christmas.pl6 | 27 ++ .../Perl/the-twelve-days-of-christmas.pl | 25 + .../PicoLisp/the-twelve-days-of-christmas.l | 29 ++ .../the-twelve-days-of-christmas.psh | 39 ++ .../Python/the-twelve-days-of-christmas.py | 23 + Task/The-Twelve-Days-of-Christmas/README | 1 + .../REXX/the-twelve-days-of-christmas.rexx | 17 + .../Racket/the-twelve-days-of-christmas.rkt | 35 ++ .../Ruby/the-twelve-days-of-christmas.rb | 23 + .../Rust/the-twelve-days-of-christmas.rust | 43 ++ .../Seed7/the-twelve-days-of-christmas.seed7 | 26 + .../Tcl/the-twelve-days-of-christmas.tcl | 23 + Task/Total-circles-area/00DESCRIPTION | 44 ++ .../C/total-circles-area-1.c | 99 ++++ .../C/total-circles-area-2.c | 107 ++++ .../D/total-circles-area-1.d | 114 +++++ .../D/total-circles-area-2.d | 168 +++++++ .../Go/total-circles-area.go | 232 +++++++++ .../Haskell/total-circles-area-1.hs | 53 ++ .../Haskell/total-circles-area-2.hs | 169 +++++++ .../Total-circles-area/J/total-circles-area.j | 75 +++ .../Julia/total-circles-area.julia | 43 ++ .../MATLAB/total-circles-area.m | 45 ++ .../Mathematica/total-circles-area-1.math | 28 ++ .../Mathematica/total-circles-area-2.math | 1 + .../Perl-6/total-circles-area.pl6 | 177 +++++++ .../Python/total-circles-area-1.py | 56 +++ .../Python/total-circles-area-2.py | 57 +++ .../Python/total-circles-area-3.py | 106 ++++ .../Python/total-circles-area-4.py | 158 ++++++ Task/Total-circles-area/README | 1 + .../REXX/total-circles-area-1.rexx | 49 ++ .../REXX/total-circles-area-2.rexx | 83 ++++ .../Ruby/total-circles-area-1.rb | 51 ++ .../Ruby/total-circles-area-2.rb | 30 ++ .../Ruby/total-circles-area-3.rb | 31 ++ .../Tcl/total-circles-area.tcl | 110 +++++ Task/Ulam-spiral--for-primes-/00DESCRIPTION | 101 ++++ .../Ada/ulam-spiral--for-primes--1.ada | 19 + .../Ada/ulam-spiral--for-primes--2.ada | 36 ++ .../Ada/ulam-spiral--for-primes--3.ada | 27 ++ .../C/ulam-spiral--for-primes--1.c | 87 ++++ .../C/ulam-spiral--for-primes--2.c | 30 ++ .../D/ulam-spiral--for-primes--1.d | 34 ++ .../D/ulam-spiral--for-primes--2.d | 33 ++ .../J/ulam-spiral--for-primes--1.j | 1 + .../J/ulam-spiral--for-primes--2.j | 12 + .../J/ulam-spiral--for-primes--3.j | 6 + .../J/ulam-spiral--for-primes--4.j | 6 + .../J/ulam-spiral--for-primes--5.j | 4 + .../J/ulam-spiral--for-primes--6.j | 1 + .../J/ulam-spiral--for-primes--7.j | 29 ++ .../Java/ulam-spiral--for-primes-.java | 64 +++ .../Perl-6/ulam-spiral--for-primes-.pl6 | 51 ++ .../Perl/ulam-spiral--for-primes-.pl | 29 ++ .../Python/ulam-spiral--for-primes-.py | 36 ++ Task/Ulam-spiral--for-primes-/README | 1 + .../REXX/ulam-spiral--for-primes--1.rexx | 42 ++ .../REXX/ulam-spiral--for-primes--2.rexx | 42 ++ .../Racket/ulam-spiral--for-primes-.rkt | 36 ++ Task/Unix-ls/00DESCRIPTION | 17 + Task/Unix-ls/AWK/unix-ls.awk | 8 + Task/Unix-ls/Ada/unix-ls.ada | 29 ++ Task/Unix-ls/C/unix-ls.c | 63 +++ Task/Unix-ls/Clojure/unix-ls.clj | 3 + Task/Unix-ls/D/unix-ls.d | 6 + Task/Unix-ls/Forth/unix-ls-1.fth | 12 + Task/Unix-ls/Forth/unix-ls-2.fth | 15 + Task/Unix-ls/Go/unix-ls.go | 24 + Task/Unix-ls/Haskell/unix-ls.hs | 9 + Task/Unix-ls/J/unix-ls.j | 2 + Task/Unix-ls/Mathematica/unix-ls.math | 1 + Task/Unix-ls/OCaml/unix-ls.ocaml | 3 + Task/Unix-ls/PARI-GP/unix-ls-1.pari | 1 + Task/Unix-ls/PARI-GP/unix-ls-2.pari | 1 + Task/Unix-ls/Perl-6/unix-ls.pl6 | 1 + Task/Unix-ls/Python/unix-ls.py | 16 + Task/Unix-ls/README | 1 + Task/Unix-ls/REXX/unix-ls.rexx | 3 + Task/Unix-ls/Racket/unix-ls.rkt | 20 + Task/Unix-ls/Ruby/unix-ls.rb | 1 + Task/Unix-ls/Rust/unix-ls.rust | 17 + Task/Unix-ls/Tcl/unix-ls.tcl | 1 + .../Vogels-approximation-method/00DESCRIPTION | 73 +++ .../D/vogels-approximation-method.d | 80 +++ .../Java/vogels-approximation-method.java | 97 ++++ .../Python/vogels-approximation-method.py | 57 +++ Task/Vogels-approximation-method/README | 1 + .../Racket/vogels-approximation-method.rkt | 103 ++++ .../Ruby/vogels-approximation-method-1.rb | 54 +++ .../Ruby/vogels-approximation-method-2.rb | 7 + .../Tcl/vogels-approximation-method-1.tcl | 104 ++++ .../Tcl/vogels-approximation-method-2.tcl | 21 + Task/World-Cup-group-stage/00DESCRIPTION | 7 + .../D/world-cup-group-stage-1.d | 20 + .../D/world-cup-group-stage-2.d | 30 ++ .../Erlang/world-cup-group-stage.erl | 33 ++ .../J/world-cup-group-stage-1.j | 4 + .../J/world-cup-group-stage-2.j | 2 + .../J/world-cup-group-stage-3.j | 2 + .../J/world-cup-group-stage-4.j | 2 + .../J/world-cup-group-stage-5.j | 2 + .../J/world-cup-group-stage-6.j | 7 + .../J/world-cup-group-stage-7.j | 5 + .../J/world-cup-group-stage-8.j | 5 + .../Java/world-cup-group-stage.java | 41 ++ .../Perl-6/world-cup-group-stage.pl6 | 20 + .../Python/world-cup-group-stage.py | 16 + Task/World-Cup-group-stage/README | 1 + .../Racket/world-cup-group-stage.rkt | 60 +++ .../Ruby/world-cup-group-stage.rb | 27 ++ .../Tcl/world-cup-group-stage.tcl | 29 ++ Task/Zero-to-the-zero-power/00DESCRIPTION | 20 + .../ALGOL-68/zero-to-the-zero-power.alg | 1 + .../AWK/zero-to-the-zero-power.awk | 5 + .../Ada/zero-to-the-zero-power.ada | 31 ++ .../AutoHotkey/zero-to-the-zero-power.ahk | 1 + .../Bracmat/zero-to-the-zero-power.bracmat | 1 + .../C++/zero-to-the-zero-power.cpp | 11 + .../C/zero-to-the-zero-power.c | 11 + .../D/zero-to-the-zero-power.d | 12 + .../Factor/zero-to-the-zero-power.factor | 3 + .../Forth/zero-to-the-zero-power.fth | 1 + .../Fortran/zero-to-the-zero-power.f | 11 + .../Go/zero-to-the-zero-power.go | 15 + .../Groovy/zero-to-the-zero-power.groovy | 1 + .../Haskell/zero-to-the-zero-power.hs | 9 + .../Icon/zero-to-the-zero-power.icon | 3 + .../J/zero-to-the-zero-power.j | 2 + .../Java/zero-to-the-zero-power.java | 1 + .../JavaScript/zero-to-the-zero-power.js | 2 + .../Maple/zero-to-the-zero-power-1.maple | 1 + .../Maple/zero-to-the-zero-power-2.maple | 1 + .../Mathematica/zero-to-the-zero-power.math | 1 + .../NetRexx/zero-to-the-zero-power.netrexx | 2 + .../PARI-GP/zero-to-the-zero-power.pari | 1 + .../PHP/zero-to-the-zero-power.php | 2 + .../PL-I/zero-to-the-zero-power.pli | 7 + .../Perl-6/zero-to-the-zero-power.pl6 | 1 + .../Perl/zero-to-the-zero-power.pl | 5 + .../PowerShell/zero-to-the-zero-power.psh | 1 + .../Python/zero-to-the-zero-power.py | 12 + Task/Zero-to-the-zero-power/README | 1 + .../REXX/zero-to-the-zero-power.rexx | 2 + .../Racket/zero-to-the-zero-power.rkt | 14 + .../Ruby/zero-to-the-zero-power.rb | 5 + .../Rust/zero-to-the-zero-power.rust | 5 + .../Scala/zero-to-the-zero-power.scala | 1 + .../Scheme/zero-to-the-zero-power.ss | 3 + .../Seed7/zero-to-the-zero-power.seed7 | 11 + .../Smalltalk/zero-to-the-zero-power.st | 2 + .../Tcl/zero-to-the-zero-power.tcl | 4 + .../00DESCRIPTION | 94 ++++ .../zhang-suen-thinning-algorithm.ahk | 79 +++ .../D/zhang-suen-thinning-algorithm.d | 128 +++++ .../Go/zhang-suen-thinning-algorithm.go | 189 ++++++++ .../zhang-suen-thinning-algorithm-1.groovy | 25 + .../zhang-suen-thinning-algorithm-2.groovy | 39 ++ .../Haskell/zhang-suen-thinning-algorithm.hs | 122 +++++ .../J/zhang-suen-thinning-algorithm-1.j | 27 ++ .../J/zhang-suen-thinning-algorithm-2.j | 10 + .../J/zhang-suen-thinning-algorithm-3.j | 25 + .../Java/zhang-suen-thinning-algorithm.java | 117 +++++ .../zhang-suen-thinning-algorithm.math | 38 ++ .../PL-I/zhang-suen-thinning-algorithm.pli | 123 +++++ .../Perl-6/zhang-suen-thinning-algorithm.pl6 | 40 ++ .../Python/zhang-suen-thinning-algorithm.py | 118 +++++ Task/Zhang-Suen-thinning-algorithm/README | 1 + .../REXX/zhang-suen-thinning-algorithm.rexx | 41 ++ .../Racket/zhang-suen-thinning-algorithm.rkt | 114 +++++ .../Ruby/zhang-suen-thinning-algorithm.rb | 68 +++ .../Tcl/zhang-suen-thinning-algorithm.tcl | 78 +++ 5697 files changed, 93386 insertions(+), 804 deletions(-) create mode 120000 Lang/360-Assembly/Catalan-numbers-Pascals-triangle create mode 120000 Lang/ACL2/File-input-output create mode 120000 Lang/ALGOL-68/Amb create mode 120000 Lang/ALGOL-68/Calendar---for-REAL-programmers create mode 120000 Lang/ALGOL-68/Closures-Value-capture create mode 120000 Lang/ALGOL-68/Combinations-and-permutations create mode 120000 Lang/ALGOL-68/Currying create mode 120000 Lang/ALGOL-68/Digital-root-Multiplicative-digital-root create mode 120000 Lang/ALGOL-68/Fibonacci-word create mode 120000 Lang/ALGOL-68/File-input-output create mode 120000 Lang/ALGOL-68/Gaussian-elimination create mode 120000 Lang/ALGOL-68/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/ALGOL-68/Hello-world-Newbie create mode 120000 Lang/ALGOL-68/Maximum-triangle-path-sum create mode 120000 Lang/ALGOL-68/Move-to-front-algorithm create mode 120000 Lang/ALGOL-68/Nth create mode 120000 Lang/ALGOL-68/Odd-word-problem create mode 120000 Lang/ALGOL-68/Old-lady-swallowed-a-fly create mode 120000 Lang/ALGOL-68/Rep-string create mode 120000 Lang/ALGOL-68/String-append create mode 120000 Lang/ALGOL-68/String-matching create mode 120000 Lang/ALGOL-68/String-prepend create mode 120000 Lang/ALGOL-68/Zero-to-the-zero-power create mode 120000 Lang/ATS/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/ATS/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/AWK/Benfords-law create mode 120000 Lang/AWK/CSV-data-manipulation create mode 120000 Lang/AWK/Comma-quibbling create mode 120000 Lang/AWK/Digital-root-Multiplicative-digital-root create mode 120000 Lang/AWK/Draw-a-clock create mode 120000 Lang/AWK/File-input-output create mode 120000 Lang/AWK/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/AWK/Hello-world-Newbie create mode 120000 Lang/AWK/Magic-squares-of-odd-order create mode 120000 Lang/AWK/Narcissistic-decimal-number create mode 120000 Lang/AWK/Nth create mode 120000 Lang/AWK/Old-lady-swallowed-a-fly create mode 120000 Lang/AWK/Phrase-reversals create mode 120000 Lang/AWK/Ranking-methods create mode 120000 Lang/AWK/Reverse-words-in-a-string create mode 120000 Lang/AWK/Runge-Kutta-method create mode 120000 Lang/AWK/String-append create mode 120000 Lang/AWK/String-matching create mode 120000 Lang/AWK/String-prepend create mode 120000 Lang/AWK/Sum-multiples-of-3-and-5 create mode 120000 Lang/AWK/The-Twelve-Days-of-Christmas create mode 120000 Lang/AWK/Unix-ls create mode 120000 Lang/AWK/Zero-to-the-zero-power create mode 120000 Lang/ActionScript/Draw-a-clock create mode 120000 Lang/ActionScript/The-Twelve-Days-of-Christmas create mode 120000 Lang/Ada/ABC-Problem create mode 120000 Lang/Ada/Almost-prime create mode 120000 Lang/Ada/Amb create mode 120000 Lang/Ada/Benfords-law create mode 120000 Lang/Ada/Calendar---for-REAL-programmers create mode 120000 Lang/Ada/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Ada/Catamorphism create mode 120000 Lang/Ada/Chinese-remainder-theorem create mode 120000 Lang/Ada/Closures-Value-capture create mode 120000 Lang/Ada/Comma-quibbling create mode 120000 Lang/Ada/Conjugate-transpose create mode 120000 Lang/Ada/Convert-decimal-number-to-rational create mode 120000 Lang/Ada/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Ada/Extensible-prime-generator create mode 120000 Lang/Ada/Fibonacci-word create mode 120000 Lang/Ada/File-input-output create mode 120000 Lang/Ada/Flipping-bits-game create mode 120000 Lang/Ada/Fractran create mode 120000 Lang/Ada/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Ada/IBAN create mode 120000 Lang/Ada/Integer-overflow create mode 120000 Lang/Ada/Magic-squares-of-odd-order create mode 120000 Lang/Ada/Maximum-triangle-path-sum create mode 120000 Lang/Ada/Move-to-front-algorithm create mode 120000 Lang/Ada/Munching-squares create mode 120000 Lang/Ada/Narcissistic-decimal-number create mode 120000 Lang/Ada/Nth create mode 120000 Lang/Ada/Odd-word-problem create mode 120000 Lang/Ada/Old-lady-swallowed-a-fly create mode 120000 Lang/Ada/Pernicious-numbers create mode 120000 Lang/Ada/Phrase-reversals create mode 120000 Lang/Ada/Rep-string create mode 120000 Lang/Ada/Reverse-words-in-a-string create mode 120000 Lang/Ada/Runge-Kutta-method create mode 120000 Lang/Ada/Semiprime create mode 120000 Lang/Ada/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Ada/Solve-a-Holy-Knights-tour create mode 120000 Lang/Ada/Solve-the-no-connection-puzzle create mode 120000 Lang/Ada/Statistics-Basic create mode 120000 Lang/Ada/String-matching create mode 120000 Lang/Ada/The-Twelve-Days-of-Christmas create mode 120000 Lang/Ada/Ulam-spiral--for-primes- create mode 120000 Lang/Ada/Unix-ls create mode 120000 Lang/Ada/Zero-to-the-zero-power create mode 120000 Lang/Aime/Benfords-law create mode 120000 Lang/Aime/File-input-output create mode 120000 Lang/Aime/Reverse-words-in-a-string create mode 120000 Lang/Aime/String-matching create mode 120000 Lang/AppleScript/File-input-output create mode 120000 Lang/Applesoft-BASIC/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Applesoft-BASIC/Nth create mode 120000 Lang/Applesoft-BASIC/Reverse-words-in-a-string create mode 120000 Lang/AutoHotkey/9-billion-names-of-God-the-integer create mode 120000 Lang/AutoHotkey/ABC-Problem create mode 120000 Lang/AutoHotkey/AKS-test-for-primes create mode 120000 Lang/AutoHotkey/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/AutoHotkey/Almost-prime create mode 120000 Lang/AutoHotkey/Amb create mode 120000 Lang/AutoHotkey/Amicable-pairs create mode 120000 Lang/AutoHotkey/Benfords-law create mode 120000 Lang/AutoHotkey/CSV-data-manipulation create mode 120000 Lang/AutoHotkey/Calendar---for-REAL-programmers create mode 120000 Lang/AutoHotkey/Catalan-numbers-Pascals-triangle create mode 120000 Lang/AutoHotkey/Circles-of-given-radius-through-two-points create mode 120000 Lang/AutoHotkey/Comma-quibbling create mode 120000 Lang/AutoHotkey/Convert-decimal-number-to-rational create mode 120000 Lang/AutoHotkey/Draw-a-clock create mode 120000 Lang/AutoHotkey/Extensible-prime-generator create mode 120000 Lang/AutoHotkey/Fibonacci-word create mode 120000 Lang/AutoHotkey/Fibonacci-word-fractal create mode 120000 Lang/AutoHotkey/File-input-output create mode 120000 Lang/AutoHotkey/Find-the-last-Sunday-of-each-month create mode 120000 Lang/AutoHotkey/Flipping-bits-game create mode 120000 Lang/AutoHotkey/Fractran create mode 120000 Lang/AutoHotkey/Generate-Chess960-starting-position create mode 120000 Lang/AutoHotkey/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/AutoHotkey/Hello-world-Newbie create mode 120000 Lang/AutoHotkey/IBAN create mode 120000 Lang/AutoHotkey/Integer-overflow create mode 120000 Lang/AutoHotkey/Longest-increasing-subsequence create mode 120000 Lang/AutoHotkey/Ludic-numbers create mode 120000 Lang/AutoHotkey/Machine-code create mode 120000 Lang/AutoHotkey/Magic-squares-of-odd-order create mode 120000 Lang/AutoHotkey/Narcissistic-decimal-number create mode 120000 Lang/AutoHotkey/Nth create mode 120000 Lang/AutoHotkey/Old-lady-swallowed-a-fly create mode 120000 Lang/AutoHotkey/Order-disjoint-list-items create mode 120000 Lang/AutoHotkey/Pernicious-numbers create mode 120000 Lang/AutoHotkey/Phrase-reversals create mode 120000 Lang/AutoHotkey/Quickselect-algorithm create mode 120000 Lang/AutoHotkey/Rep-string create mode 120000 Lang/AutoHotkey/Reverse-words-in-a-string create mode 120000 Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags create mode 120000 Lang/AutoHotkey/Semiprime create mode 120000 Lang/AutoHotkey/Sparkline-in-unicode create mode 120000 Lang/AutoHotkey/String-append create mode 120000 Lang/AutoHotkey/String-matching create mode 120000 Lang/AutoHotkey/String-prepend create mode 120000 Lang/AutoHotkey/Sum-multiples-of-3-and-5 create mode 120000 Lang/AutoHotkey/The-Twelve-Days-of-Christmas create mode 120000 Lang/AutoHotkey/Zero-to-the-zero-power create mode 120000 Lang/AutoHotkey/Zhang-Suen-thinning-algorithm create mode 120000 Lang/AutoIt/String-matching create mode 120000 Lang/Axiom/Closures-Value-capture create mode 120000 Lang/BASIC/Circles-of-given-radius-through-two-points create mode 120000 Lang/BASIC/File-input-output create mode 120000 Lang/BASIC/Runge-Kutta-method create mode 120000 Lang/BASIC/String-append create mode 120000 Lang/BASIC/String-matching create mode 120000 Lang/BASIC/String-prepend create mode 120000 Lang/BBC-BASIC/ABC-Problem create mode 120000 Lang/BBC-BASIC/Calendar---for-REAL-programmers create mode 120000 Lang/BBC-BASIC/File-input-output create mode 120000 Lang/BBC-BASIC/Find-the-last-Sunday-of-each-month create mode 120000 Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/BBC-BASIC/IBAN create mode 120000 Lang/BBC-BASIC/Machine-code create mode 120000 Lang/BBC-BASIC/Nth create mode 120000 Lang/BBC-BASIC/Reverse-words-in-a-string create mode 120000 Lang/BBC-BASIC/String-matching create mode 120000 Lang/Babel/Closures-Value-capture create mode 120000 Lang/Babel/File-input-output create mode 120000 Lang/Babel/Nth create mode 120000 Lang/Babel/Old-lady-swallowed-a-fly create mode 120000 Lang/Batch-File/ABC-Problem create mode 120000 Lang/Batch-File/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Batch-File/File-input-output create mode 120000 Lang/Befunge/File-input-output create mode 120000 Lang/Bracmat/ABC-Problem create mode 120000 Lang/Bracmat/AKS-test-for-primes create mode 120000 Lang/Bracmat/Amb create mode 120000 Lang/Bracmat/Catamorphism create mode 120000 Lang/Bracmat/Chinese-remainder-theorem create mode 120000 Lang/Bracmat/Closures-Value-capture create mode 120000 Lang/Bracmat/Combinations-and-permutations create mode 120000 Lang/Bracmat/Convert-decimal-number-to-rational create mode 120000 Lang/Bracmat/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Bracmat/File-input-output create mode 120000 Lang/Bracmat/Fractran create mode 120000 Lang/Bracmat/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Bracmat/Hash-join create mode 120000 Lang/Bracmat/Hickerson-series-of-almost-integers create mode 120000 Lang/Bracmat/IBAN create mode 120000 Lang/Bracmat/Left-factorials create mode 120000 Lang/Bracmat/Maximum-triangle-path-sum create mode 120000 Lang/Bracmat/Odd-word-problem create mode 120000 Lang/Bracmat/Order-disjoint-list-items create mode 120000 Lang/Bracmat/Phrase-reversals create mode 120000 Lang/Bracmat/Rep-string create mode 120000 Lang/Bracmat/Reverse-words-in-a-string create mode 120000 Lang/Bracmat/Solve-a-Holy-Knights-tour create mode 120000 Lang/Bracmat/State-name-puzzle create mode 120000 Lang/Bracmat/String-matching create mode 120000 Lang/Bracmat/String-prepend create mode 120000 Lang/Bracmat/The-Twelve-Days-of-Christmas create mode 120000 Lang/Bracmat/Zero-to-the-zero-power create mode 120000 Lang/Burlesque/Munching-squares create mode 120000 Lang/C++/9-billion-names-of-God-the-integer create mode 120000 Lang/C++/ABC-Problem create mode 120000 Lang/C++/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/C++/Benfords-law create mode 120000 Lang/C++/CSV-data-manipulation create mode 120000 Lang/C++/Casting-out-nines create mode 120000 Lang/C++/Catalan-numbers-Pascals-triangle create mode 120000 Lang/C++/Catamorphism create mode 120000 Lang/C++/Closures-Value-capture create mode 120000 Lang/C++/Comma-quibbling create mode 120000 Lang/C++/Digital-root-Multiplicative-digital-root create mode 120000 Lang/C++/Draw-a-clock create mode 120000 Lang/C++/Fibonacci-word create mode 120000 Lang/C++/Fibonacci-word-fractal create mode 120000 Lang/C++/File-input-output create mode 120000 Lang/C++/Find-the-last-Sunday-of-each-month create mode 120000 Lang/C++/Flipping-bits-game create mode 120000 Lang/C++/Fractran create mode 120000 Lang/C++/Generate-Chess960-starting-position create mode 120000 Lang/C++/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/C++/Hickerson-series-of-almost-integers create mode 120000 Lang/C++/IBAN create mode 120000 Lang/C++/Iterated-digits-squaring create mode 120000 Lang/C++/Longest-increasing-subsequence create mode 120000 Lang/C++/Ludic-numbers create mode 120000 Lang/C++/Magic-squares-of-odd-order create mode 120000 Lang/C++/Maximum-triangle-path-sum create mode 120000 Lang/C++/Move-to-front-algorithm create mode 120000 Lang/C++/Munching-squares create mode 120000 Lang/C++/Narcissistic-decimal-number create mode 120000 Lang/C++/Odd-word-problem create mode 120000 Lang/C++/Penneys-game create mode 120000 Lang/C++/Percolation-Mean-run-density create mode 120000 Lang/C++/Pernicious-numbers create mode 120000 Lang/C++/Phrase-reversals create mode 120000 Lang/C++/Quickselect-algorithm create mode 120000 Lang/C++/Rep-string create mode 120000 Lang/C++/Reverse-words-in-a-string create mode 120000 Lang/C++/Semiprime create mode 120000 Lang/C++/Solve-a-Holy-Knights-tour create mode 120000 Lang/C++/Solve-a-Hopido-puzzle create mode 120000 Lang/C++/Solve-a-Numbrix-puzzle create mode 120000 Lang/C++/Sparkline-in-unicode create mode 120000 Lang/C++/String-append create mode 120000 Lang/C++/String-matching create mode 120000 Lang/C++/String-prepend create mode 120000 Lang/C++/Sum-multiples-of-3-and-5 create mode 120000 Lang/C++/The-Twelve-Days-of-Christmas create mode 120000 Lang/C++/Zero-to-the-zero-power create mode 120000 Lang/C-sharp/ABC-Problem create mode 120000 Lang/C-sharp/Almost-prime create mode 120000 Lang/C-sharp/Amb create mode 120000 Lang/C-sharp/CSV-data-manipulation create mode 120000 Lang/C-sharp/Catamorphism create mode 120000 Lang/C-sharp/Currying create mode 120000 Lang/C-sharp/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/C-sharp/Hash-join create mode 120000 Lang/C-sharp/IBAN create mode 120000 Lang/C-sharp/Munching-squares create mode 120000 Lang/C-sharp/String-prepend create mode 120000 Lang/C-sharp/The-ISAAC-Cipher create mode 120000 Lang/C/9-billion-names-of-God-the-integer create mode 120000 Lang/C/ABC-Problem create mode 120000 Lang/C/AKS-test-for-primes create mode 120000 Lang/C/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/C/Almost-prime create mode 120000 Lang/C/Amb create mode 120000 Lang/C/Amicable-pairs create mode 120000 Lang/C/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/C/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/C/Benfords-law create mode 120000 Lang/C/Bernoulli-numbers create mode 120000 Lang/C/Bitcoin-public-point-to-address create mode 120000 Lang/C/Catamorphism create mode 120000 Lang/C/Chinese-remainder-theorem create mode 120000 Lang/C/Circles-of-given-radius-through-two-points create mode 120000 Lang/C/Closures-Value-capture create mode 120000 Lang/C/Combinations-and-permutations create mode 120000 Lang/C/Comma-quibbling create mode 120000 Lang/C/Conjugate-transpose create mode 120000 Lang/C/Convert-decimal-number-to-rational create mode 120000 Lang/C/Digital-root-Multiplicative-digital-root create mode 120000 Lang/C/Draw-a-clock create mode 120000 Lang/C/Extensible-prime-generator create mode 120000 Lang/C/Fibonacci-word create mode 120000 Lang/C/File-input-output create mode 120000 Lang/C/Flipping-bits-game create mode 120000 Lang/C/Fractran create mode 120000 Lang/C/Gaussian-elimination create mode 120000 Lang/C/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/C/Hickerson-series-of-almost-integers create mode 120000 Lang/C/IBAN create mode 120000 Lang/C/Integer-overflow create mode 120000 Lang/C/Iterated-digits-squaring create mode 120000 Lang/C/K-d-tree create mode 120000 Lang/C/Left-factorials create mode 120000 Lang/C/Longest-increasing-subsequence create mode 120000 Lang/C/Ludic-numbers create mode 120000 Lang/C/Machine-code create mode 120000 Lang/C/Magic-squares-of-odd-order create mode 120000 Lang/C/Maximum-triangle-path-sum create mode 120000 Lang/C/Move-to-front-algorithm create mode 120000 Lang/C/Munching-squares create mode 120000 Lang/C/Narcissistic-decimal-number create mode 120000 Lang/C/Natural-sorting create mode 120000 Lang/C/Nth create mode 120000 Lang/C/Odd-word-problem create mode 120000 Lang/C/Old-lady-swallowed-a-fly create mode 120000 Lang/C/Paraffins create mode 120000 Lang/C/Parse-an-IP-Address create mode 120000 Lang/C/Penneys-game create mode 120000 Lang/C/Percolation-Bond-percolation create mode 120000 Lang/C/Percolation-Mean-cluster-density create mode 120000 Lang/C/Percolation-Mean-run-density create mode 120000 Lang/C/Percolation-Site-percolation create mode 120000 Lang/C/Permutations-Rank-of-a-permutation create mode 120000 Lang/C/Pernicious-numbers create mode 120000 Lang/C/Phrase-reversals create mode 120000 Lang/C/Quickselect-algorithm create mode 120000 Lang/C/Rep-string create mode 120000 Lang/C/Reverse-words-in-a-string create mode 120000 Lang/C/Rosetta-Code-Find-bare-lang-tags create mode 120000 Lang/C/Runge-Kutta-method create mode 120000 Lang/C/Semiprime create mode 120000 Lang/C/State-name-puzzle create mode 120000 Lang/C/Statistics-Basic create mode 120000 Lang/C/Stern-Brocot-sequence create mode 120000 Lang/C/String-append create mode 120000 Lang/C/String-matching create mode 120000 Lang/C/String-prepend create mode 120000 Lang/C/Sum-multiples-of-3-and-5 create mode 120000 Lang/C/The-ISAAC-Cipher create mode 120000 Lang/C/The-Twelve-Days-of-Christmas create mode 120000 Lang/C/Total-circles-area create mode 120000 Lang/C/Ulam-spiral--for-primes- create mode 120000 Lang/C/Unix-ls create mode 120000 Lang/C/Zero-to-the-zero-power create mode 120000 Lang/COBOL/Comma-quibbling create mode 120000 Lang/COBOL/File-input-output create mode 120000 Lang/COBOL/Hello-world-Newbie create mode 120000 Lang/COBOL/Hickerson-series-of-almost-integers create mode 120000 Lang/COBOL/IBAN create mode 120000 Lang/COBOL/Quickselect-algorithm create mode 120000 Lang/COBOL/String-prepend create mode 120000 Lang/COBOL/Sum-multiples-of-3-and-5 create mode 120000 Lang/COBOL/The-Twelve-Days-of-Christmas create mode 120000 Lang/Cache-ObjectScript/IBAN create mode 120000 Lang/Clean/File-input-output create mode 120000 Lang/Clojure/ABC-Problem create mode 120000 Lang/Clojure/AKS-test-for-primes create mode 120000 Lang/Clojure/Amb create mode 120000 Lang/Clojure/CSV-data-manipulation create mode 120000 Lang/Clojure/Catamorphism create mode 120000 Lang/Clojure/Comma-quibbling create mode 120000 Lang/Clojure/Fibonacci-word create mode 120000 Lang/Clojure/File-input-output create mode 120000 Lang/Clojure/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Clojure/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Clojure/Hash-join create mode 120000 Lang/Clojure/Hello-world-Newbie create mode 120000 Lang/Clojure/Hickerson-series-of-almost-integers create mode 120000 Lang/Clojure/IBAN create mode 120000 Lang/Clojure/Integer-overflow create mode 120000 Lang/Clojure/Longest-increasing-subsequence create mode 120000 Lang/Clojure/Ludic-numbers create mode 120000 Lang/Clojure/Make-directory-path create mode 120000 Lang/Clojure/Nth create mode 120000 Lang/Clojure/Odd-word-problem create mode 120000 Lang/Clojure/Reverse-words-in-a-string create mode 120000 Lang/Clojure/Stern-Brocot-sequence create mode 120000 Lang/Clojure/String-append create mode 120000 Lang/Clojure/String-matching create mode 120000 Lang/Clojure/String-prepend create mode 120000 Lang/Clojure/Sum-multiples-of-3-and-5 create mode 120000 Lang/Clojure/The-Twelve-Days-of-Christmas create mode 120000 Lang/Clojure/Unix-ls create mode 120000 Lang/CoffeeScript/ABC-Problem create mode 120000 Lang/CoffeeScript/AKS-test-for-primes create mode 120000 Lang/CoffeeScript/Benfords-law create mode 120000 Lang/CoffeeScript/Closures-Value-capture create mode 120000 Lang/CoffeeScript/Comma-quibbling create mode 120000 Lang/CoffeeScript/Odd-word-problem create mode 120000 Lang/CoffeeScript/Statistics-Basic create mode 120000 Lang/CoffeeScript/String-matching create mode 120000 Lang/ColdFusion/File-input-output create mode 120000 Lang/Common-Lisp/9-billion-names-of-God-the-integer create mode 120000 Lang/Common-Lisp/ABC-Problem create mode 120000 Lang/Common-Lisp/AKS-test-for-primes create mode 120000 Lang/Common-Lisp/Almost-prime create mode 120000 Lang/Common-Lisp/Amb create mode 120000 Lang/Common-Lisp/Benfords-law create mode 120000 Lang/Common-Lisp/Bernoulli-numbers create mode 120000 Lang/Common-Lisp/CSV-data-manipulation create mode 120000 Lang/Common-Lisp/Casting-out-nines create mode 120000 Lang/Common-Lisp/Catamorphism create mode 120000 Lang/Common-Lisp/Chinese-remainder-theorem create mode 120000 Lang/Common-Lisp/Closures-Value-capture create mode 120000 Lang/Common-Lisp/Comma-quibbling create mode 120000 Lang/Common-Lisp/Currying create mode 120000 Lang/Common-Lisp/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Common-Lisp/File-input-output create mode 120000 Lang/Common-Lisp/Fractran create mode 120000 Lang/Common-Lisp/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Common-Lisp/Hash-join create mode 120000 Lang/Common-Lisp/IBAN create mode 120000 Lang/Common-Lisp/Longest-increasing-subsequence create mode 120000 Lang/Common-Lisp/Machine-code create mode 120000 Lang/Common-Lisp/Magic-squares-of-odd-order create mode 120000 Lang/Common-Lisp/Maximum-triangle-path-sum create mode 120000 Lang/Common-Lisp/Move-to-front-algorithm create mode 120000 Lang/Common-Lisp/Narcissistic-decimal-number create mode 120000 Lang/Common-Lisp/Nth create mode 120000 Lang/Common-Lisp/Odd-word-problem create mode 120000 Lang/Common-Lisp/Pernicious-numbers create mode 120000 Lang/Common-Lisp/RSA-code create mode 120000 Lang/Common-Lisp/Reverse-words-in-a-string create mode 120000 Lang/Common-Lisp/Semiprime create mode 120000 Lang/Common-Lisp/String-append create mode 120000 Lang/Common-Lisp/String-matching create mode 120000 Lang/Common-Lisp/String-prepend create mode 120000 Lang/Common-Lisp/Sum-multiples-of-3-and-5 create mode 120000 Lang/Component-Pascal/String-matching create mode 120000 Lang/Component-Pascal/Sum-multiples-of-3-and-5 create mode 120000 Lang/D/9-billion-names-of-God-the-integer create mode 120000 Lang/D/ABC-Problem create mode 120000 Lang/D/AKS-test-for-primes create mode 120000 Lang/D/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/D/Aliquot-sequence-classifications create mode 120000 Lang/D/Almost-prime create mode 120000 Lang/D/Amb create mode 120000 Lang/D/Amicable-pairs create mode 120000 Lang/D/Benfords-law create mode 120000 Lang/D/Bernoulli-numbers create mode 120000 Lang/D/Bitcoin-public-point-to-address create mode 120000 Lang/D/CSV-data-manipulation create mode 120000 Lang/D/Calendar---for-REAL-programmers create mode 120000 Lang/D/Casting-out-nines create mode 120000 Lang/D/Catalan-numbers-Pascals-triangle create mode 120000 Lang/D/Catamorphism create mode 120000 Lang/D/Chinese-remainder-theorem create mode 120000 Lang/D/Circles-of-given-radius-through-two-points create mode 120000 Lang/D/Closures-Value-capture create mode 120000 Lang/D/Combinations-and-permutations create mode 120000 Lang/D/Comma-quibbling create mode 120000 Lang/D/Conjugate-transpose create mode 120000 Lang/D/Convert-decimal-number-to-rational create mode 120000 Lang/D/Currying create mode 120000 Lang/D/Digital-root-Multiplicative-digital-root create mode 120000 Lang/D/Extensible-prime-generator create mode 120000 Lang/D/Fibonacci-word create mode 120000 Lang/D/Fibonacci-word-fractal create mode 120000 Lang/D/File-input-output create mode 120000 Lang/D/Find-the-last-Sunday-of-each-month create mode 120000 Lang/D/Flipping-bits-game create mode 120000 Lang/D/Fractran create mode 120000 Lang/D/Gaussian-elimination create mode 120000 Lang/D/Generate-Chess960-starting-position create mode 120000 Lang/D/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/D/Hash-join create mode 120000 Lang/D/Hello-world-Newbie create mode 120000 Lang/D/Heronian-triangles create mode 120000 Lang/D/Hickerson-series-of-almost-integers create mode 120000 Lang/D/IBAN create mode 120000 Lang/D/Integer-overflow create mode 120000 Lang/D/Iterated-digits-squaring create mode 120000 Lang/D/K-d-tree create mode 120000 Lang/D/Left-factorials create mode 120000 Lang/D/Longest-increasing-subsequence create mode 120000 Lang/D/Ludic-numbers create mode 120000 Lang/D/Machine-code create mode 120000 Lang/D/Magic-squares-of-odd-order create mode 120000 Lang/D/Maximum-triangle-path-sum create mode 120000 Lang/D/Move-to-front-algorithm create mode 120000 Lang/D/Munching-squares create mode 120000 Lang/D/Narcissistic-decimal-number create mode 120000 Lang/D/Natural-sorting create mode 120000 Lang/D/Nth create mode 120000 Lang/D/Odd-word-problem create mode 120000 Lang/D/Old-lady-swallowed-a-fly create mode 120000 Lang/D/Order-disjoint-list-items create mode 120000 Lang/D/Paraffins create mode 120000 Lang/D/Penneys-game create mode 120000 Lang/D/Percolation-Bond-percolation create mode 120000 Lang/D/Percolation-Mean-cluster-density create mode 120000 Lang/D/Percolation-Mean-run-density create mode 120000 Lang/D/Percolation-Site-percolation create mode 120000 Lang/D/Permutations-Rank-of-a-permutation create mode 120000 Lang/D/Pernicious-numbers create mode 120000 Lang/D/Phrase-reversals create mode 120000 Lang/D/Quickselect-algorithm create mode 120000 Lang/D/RSA-code create mode 120000 Lang/D/Rep-string create mode 120000 Lang/D/Reverse-words-in-a-string create mode 120000 Lang/D/Runge-Kutta-method create mode 120000 Lang/D/Semiprime create mode 120000 Lang/D/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/D/Solve-a-Holy-Knights-tour create mode 120000 Lang/D/Solve-a-Hopido-puzzle create mode 120000 Lang/D/Solve-a-Numbrix-puzzle create mode 120000 Lang/D/Solve-the-no-connection-puzzle create mode 120000 Lang/D/Sparkline-in-unicode create mode 120000 Lang/D/State-name-puzzle create mode 120000 Lang/D/Statistics-Basic create mode 120000 Lang/D/Stern-Brocot-sequence create mode 120000 Lang/D/String-append create mode 120000 Lang/D/String-matching create mode 120000 Lang/D/String-prepend create mode 120000 Lang/D/Sum-multiples-of-3-and-5 create mode 120000 Lang/D/The-ISAAC-Cipher create mode 120000 Lang/D/The-Twelve-Days-of-Christmas create mode 120000 Lang/D/Total-circles-area create mode 120000 Lang/D/Ulam-spiral--for-primes- create mode 120000 Lang/D/Unix-ls create mode 120000 Lang/D/Vogels-approximation-method create mode 120000 Lang/D/World-Cup-group-stage create mode 120000 Lang/D/Zero-to-the-zero-power create mode 120000 Lang/D/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Dart/Runge-Kutta-method create mode 120000 Lang/Dart/Statistics-Basic create mode 120000 Lang/Deja-Vu/Catamorphism create mode 120000 Lang/Deja-Vu/Comma-quibbling create mode 120000 Lang/Deja-Vu/Hash-join create mode 120000 Lang/Deja-Vu/Longest-increasing-subsequence create mode 120000 Lang/Deja-Vu/String-prepend create mode 120000 Lang/Deja-Vu/Sum-multiples-of-3-and-5 create mode 120000 Lang/Delphi/ABC-Problem create mode 120000 Lang/Delphi/Closures-Value-capture create mode 120000 Lang/Delphi/File-input-output create mode 120000 Lang/Delphi/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Delphi/String-matching create mode 120000 Lang/Delphi/Sum-multiples-of-3-and-5 create mode 120000 Lang/Delphi/The-ISAAC-Cipher create mode 120000 Lang/E/Amb create mode 120000 Lang/E/File-input-output create mode 120000 Lang/E/String-matching create mode 120000 Lang/Eiffel/File-input-output create mode 120000 Lang/Eiffel/Ludic-numbers create mode 120000 Lang/Eiffel/Sum-multiples-of-3-and-5 create mode 120000 Lang/Ela/Amb create mode 120000 Lang/Elena/Amb create mode 120000 Lang/Elena/Calendar---for-REAL-programmers create mode 120000 Lang/Elena/String-matching create mode 120000 Lang/Elixir/Reverse-words-in-a-string create mode 120000 Lang/Elixir/Sparkline-in-unicode create mode 120000 Lang/Elixir/String-matching create mode 120000 Lang/Emacs-Lisp/Closures-Value-capture create mode 120000 Lang/Erlang/9-billion-names-of-God-the-integer create mode 120000 Lang/Erlang/ABC-Problem create mode 120000 Lang/Erlang/AKS-test-for-primes create mode 120000 Lang/Erlang/Benfords-law create mode 120000 Lang/Erlang/CSV-data-manipulation create mode 120000 Lang/Erlang/Chinese-remainder-theorem create mode 120000 Lang/Erlang/Closures-Value-capture create mode 120000 Lang/Erlang/Comma-quibbling create mode 120000 Lang/Erlang/Currying create mode 120000 Lang/Erlang/File-input-output create mode 120000 Lang/Erlang/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Erlang/Hash-join create mode 120000 Lang/Erlang/Hello-world-Newbie create mode 120000 Lang/Erlang/Odd-word-problem create mode 120000 Lang/Erlang/String-matching create mode 120000 Lang/Erlang/Sum-multiples-of-3-and-5 create mode 120000 Lang/Erlang/World-Cup-group-stage create mode 120000 Lang/Euphoria/ABC-Problem create mode 120000 Lang/Euphoria/File-input-output create mode 120000 Lang/Euphoria/String-append create mode 120000 Lang/Euphoria/String-matching create mode 120000 Lang/F-Sharp/Runge-Kutta-method create mode 120000 Lang/FALSE/Odd-word-problem create mode 120000 Lang/FALSE/Sparkline-in-unicode create mode 120000 Lang/FBSL/ABC-Problem create mode 120000 Lang/FBSL/Find-the-last-Sunday-of-each-month create mode 120000 Lang/FBSL/String-matching create mode 120000 Lang/FBSL/Sum-multiples-of-3-and-5 create mode 120000 Lang/Factor/Amb create mode 120000 Lang/Factor/Closures-Value-capture create mode 120000 Lang/Factor/Conjugate-transpose create mode 120000 Lang/Factor/File-input-output create mode 120000 Lang/Factor/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Factor/Odd-word-problem create mode 120000 Lang/Factor/Old-lady-swallowed-a-fly create mode 120000 Lang/Factor/String-prepend create mode 120000 Lang/Factor/Zero-to-the-zero-power create mode 120000 Lang/Fantom/Closures-Value-capture create mode 120000 Lang/Fantom/String-matching create mode 120000 Lang/Forth/Benfords-law create mode 120000 Lang/Forth/CSV-data-manipulation create mode 120000 Lang/Forth/Chinese-remainder-theorem create mode 120000 Lang/Forth/Currying create mode 120000 Lang/Forth/File-input-output create mode 120000 Lang/Forth/Nth create mode 120000 Lang/Forth/Odd-word-problem create mode 120000 Lang/Forth/Old-lady-swallowed-a-fly create mode 120000 Lang/Forth/Semiprime create mode 120000 Lang/Forth/String-matching create mode 120000 Lang/Forth/Sum-multiples-of-3-and-5 create mode 120000 Lang/Forth/Unix-ls create mode 120000 Lang/Forth/Zero-to-the-zero-power create mode 120000 Lang/Fortran/ABC-Problem create mode 120000 Lang/Fortran/Benfords-law create mode 120000 Lang/Fortran/Circles-of-given-radius-through-two-points create mode 120000 Lang/Fortran/Conjugate-transpose create mode 120000 Lang/Fortran/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Fortran/Draw-a-clock create mode 120000 Lang/Fortran/File-input-output create mode 120000 Lang/Fortran/Flipping-bits-game create mode 120000 Lang/Fortran/Gaussian-elimination create mode 120000 Lang/Fortran/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Fortran/Hickerson-series-of-almost-integers create mode 120000 Lang/Fortran/Nth create mode 120000 Lang/Fortran/Percolation-Mean-run-density create mode 120000 Lang/Fortran/Percolation-Site-percolation create mode 120000 Lang/Fortran/Runge-Kutta-method create mode 120000 Lang/Fortran/Statistics-Basic create mode 120000 Lang/Fortran/Zero-to-the-zero-power create mode 120000 Lang/Frege/Old-lady-swallowed-a-fly create mode 120000 Lang/Frink/9-billion-names-of-God-the-integer create mode 120000 Lang/Frink/File-input-output create mode 120000 Lang/GAP/File-input-output create mode 120000 Lang/GML/File-input-output create mode 120000 Lang/GML/String-matching create mode 120000 Lang/GUISS/Calendar---for-REAL-programmers create mode 120000 Lang/GUISS/Draw-a-clock create mode 120000 Lang/GUISS/File-input-output create mode 120000 Lang/Gnuplot/Munching-squares create mode 120000 Lang/Go/ABC-Problem create mode 120000 Lang/Go/AKS-test-for-primes create mode 120000 Lang/Go/Almost-prime create mode 120000 Lang/Go/Amb create mode 120000 Lang/Go/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Go/Benfords-law create mode 120000 Lang/Go/Bernoulli-numbers create mode 120000 Lang/Go/Bitcoin-public-point-to-address create mode 120000 Lang/Go/CSV-data-manipulation create mode 120000 Lang/Go/Casting-out-nines create mode 120000 Lang/Go/Catamorphism create mode 120000 Lang/Go/Chinese-remainder-theorem create mode 120000 Lang/Go/Circles-of-given-radius-through-two-points create mode 120000 Lang/Go/Closures-Value-capture create mode 120000 Lang/Go/Comma-quibbling create mode 120000 Lang/Go/Conjugate-transpose create mode 120000 Lang/Go/Convert-decimal-number-to-rational create mode 120000 Lang/Go/Currying create mode 120000 Lang/Go/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Go/Draw-a-clock create mode 120000 Lang/Go/Extensible-prime-generator create mode 120000 Lang/Go/Fibonacci-word create mode 120000 Lang/Go/File-input-output create mode 120000 Lang/Go/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Go/Flipping-bits-game create mode 120000 Lang/Go/Fractran create mode 120000 Lang/Go/Gaussian-elimination create mode 120000 Lang/Go/Generate-Chess960-starting-position create mode 120000 Lang/Go/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Go/Hash-join create mode 120000 Lang/Go/Hickerson-series-of-almost-integers create mode 120000 Lang/Go/IBAN create mode 120000 Lang/Go/Integer-overflow create mode 120000 Lang/Go/Iterated-digits-squaring create mode 120000 Lang/Go/K-d-tree create mode 120000 Lang/Go/Left-factorials create mode 120000 Lang/Go/Longest-increasing-subsequence create mode 120000 Lang/Go/Ludic-numbers create mode 120000 Lang/Go/Magic-squares-of-odd-order create mode 120000 Lang/Go/Make-directory-path create mode 120000 Lang/Go/Maximum-triangle-path-sum create mode 120000 Lang/Go/Move-to-front-algorithm create mode 120000 Lang/Go/Munching-squares create mode 120000 Lang/Go/Narcissistic-decimal-number create mode 120000 Lang/Go/Natural-sorting create mode 120000 Lang/Go/Nth create mode 120000 Lang/Go/Odd-word-problem create mode 120000 Lang/Go/Order-disjoint-list-items create mode 120000 Lang/Go/Paraffins create mode 120000 Lang/Go/Parse-an-IP-Address create mode 120000 Lang/Go/Percolation-Bond-percolation create mode 120000 Lang/Go/Percolation-Site-percolation create mode 120000 Lang/Go/Permutations-Rank-of-a-permutation create mode 120000 Lang/Go/Pernicious-numbers create mode 120000 Lang/Go/Phrase-reversals create mode 120000 Lang/Go/Quickselect-algorithm create mode 120000 Lang/Go/RSA-code create mode 120000 Lang/Go/Ranking-methods create mode 120000 Lang/Go/Rep-string create mode 120000 Lang/Go/Reverse-words-in-a-string create mode 120000 Lang/Go/Runge-Kutta-method create mode 120000 Lang/Go/Semiprime create mode 120000 Lang/Go/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Go/Solve-the-no-connection-puzzle create mode 120000 Lang/Go/Sparkline-in-unicode create mode 120000 Lang/Go/State-name-puzzle create mode 120000 Lang/Go/Statistics-Basic create mode 120000 Lang/Go/Stern-Brocot-sequence create mode 120000 Lang/Go/String-append create mode 120000 Lang/Go/String-matching create mode 120000 Lang/Go/String-prepend create mode 120000 Lang/Go/Sum-multiples-of-3-and-5 create mode 120000 Lang/Go/Textonyms create mode 120000 Lang/Go/The-ISAAC-Cipher create mode 120000 Lang/Go/The-Twelve-Days-of-Christmas create mode 120000 Lang/Go/Total-circles-area create mode 120000 Lang/Go/Unix-ls create mode 120000 Lang/Go/Zero-to-the-zero-power create mode 120000 Lang/Go/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Groovy/ABC-Problem create mode 120000 Lang/Groovy/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Groovy/CSV-data-manipulation create mode 120000 Lang/Groovy/Closures-Value-capture create mode 120000 Lang/Groovy/Comma-quibbling create mode 120000 Lang/Groovy/Currying create mode 120000 Lang/Groovy/File-input-output create mode 120000 Lang/Groovy/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Groovy/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Groovy/Hash-join create mode 120000 Lang/Groovy/IBAN create mode 120000 Lang/Groovy/Phrase-reversals create mode 120000 Lang/Groovy/Reverse-words-in-a-string create mode 120000 Lang/Groovy/Sparkline-in-unicode create mode 120000 Lang/Groovy/String-matching create mode 120000 Lang/Groovy/Sum-multiples-of-3-and-5 create mode 120000 Lang/Groovy/The-Twelve-Days-of-Christmas create mode 120000 Lang/Groovy/Zero-to-the-zero-power create mode 120000 Lang/Groovy/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Haskell/9-billion-names-of-God-the-integer create mode 120000 Lang/Haskell/ABC-Problem create mode 120000 Lang/Haskell/AKS-test-for-primes create mode 120000 Lang/Haskell/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Haskell/Aliquot-sequence-classifications create mode 120000 Lang/Haskell/Almost-prime create mode 120000 Lang/Haskell/Amb create mode 120000 Lang/Haskell/Amicable-pairs create mode 120000 Lang/Haskell/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Haskell/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Haskell/Benfords-law create mode 120000 Lang/Haskell/Bernoulli-numbers create mode 120000 Lang/Haskell/CSV-data-manipulation create mode 120000 Lang/Haskell/Catamorphism create mode 120000 Lang/Haskell/Chinese-remainder-theorem create mode 120000 Lang/Haskell/Circles-of-given-radius-through-two-points create mode 120000 Lang/Haskell/Closures-Value-capture create mode 120000 Lang/Haskell/Comma-quibbling create mode 120000 Lang/Haskell/Convert-decimal-number-to-rational create mode 120000 Lang/Haskell/Currying create mode 120000 Lang/Haskell/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Haskell/Draw-a-clock create mode 120000 Lang/Haskell/Extensible-prime-generator create mode 120000 Lang/Haskell/Fibonacci-word create mode 120000 Lang/Haskell/File-input-output create mode 120000 Lang/Haskell/Flipping-bits-game create mode 120000 Lang/Haskell/Fractran create mode 120000 Lang/Haskell/Generate-Chess960-starting-position create mode 120000 Lang/Haskell/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Haskell/Hash-join create mode 120000 Lang/Haskell/Hello-world-Newbie create mode 120000 Lang/Haskell/Heronian-triangles create mode 120000 Lang/Haskell/IBAN create mode 120000 Lang/Haskell/Integer-overflow create mode 120000 Lang/Haskell/Iterated-digits-squaring create mode 120000 Lang/Haskell/K-d-tree create mode 120000 Lang/Haskell/Left-factorials create mode 120000 Lang/Haskell/Longest-increasing-subsequence create mode 120000 Lang/Haskell/Ludic-numbers create mode 120000 Lang/Haskell/Magic-squares-of-odd-order create mode 120000 Lang/Haskell/Maximum-triangle-path-sum create mode 120000 Lang/Haskell/Move-to-front-algorithm create mode 120000 Lang/Haskell/Munching-squares create mode 120000 Lang/Haskell/Narcissistic-decimal-number create mode 120000 Lang/Haskell/Nth create mode 120000 Lang/Haskell/Odd-word-problem create mode 120000 Lang/Haskell/Old-lady-swallowed-a-fly create mode 120000 Lang/Haskell/Paraffins create mode 120000 Lang/Haskell/Penneys-game create mode 120000 Lang/Haskell/Percolation-Mean-run-density create mode 120000 Lang/Haskell/Permutations-Rank-of-a-permutation create mode 120000 Lang/Haskell/Pernicious-numbers create mode 120000 Lang/Haskell/Phrase-reversals create mode 120000 Lang/Haskell/Quickselect-algorithm create mode 120000 Lang/Haskell/Ranking-methods create mode 120000 Lang/Haskell/Rep-string create mode 120000 Lang/Haskell/Reverse-words-in-a-string create mode 120000 Lang/Haskell/Runge-Kutta-method create mode 120000 Lang/Haskell/Semiprime create mode 120000 Lang/Haskell/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Haskell/Solve-a-Holy-Knights-tour create mode 120000 Lang/Haskell/Sparkline-in-unicode create mode 120000 Lang/Haskell/Stern-Brocot-sequence create mode 120000 Lang/Haskell/String-append create mode 120000 Lang/Haskell/String-matching create mode 120000 Lang/Haskell/String-prepend create mode 120000 Lang/Haskell/Sum-multiples-of-3-and-5 create mode 120000 Lang/Haskell/The-ISAAC-Cipher create mode 120000 Lang/Haskell/Total-circles-area create mode 120000 Lang/Haskell/Unix-ls create mode 120000 Lang/Haskell/Zero-to-the-zero-power create mode 120000 Lang/Haskell/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Haxe/Amb create mode 120000 Lang/Haxe/The-ISAAC-Cipher create mode 120000 Lang/HicEst/File-input-output create mode 120000 Lang/IDL/File-input-output create mode 120000 Lang/Icon/ABC-Problem create mode 120000 Lang/Icon/Almost-prime create mode 120000 Lang/Icon/Amb create mode 120000 Lang/Icon/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Icon/Benfords-law create mode 120000 Lang/Icon/Bernoulli-numbers create mode 120000 Lang/Icon/CSV-data-manipulation create mode 120000 Lang/Icon/Calendar---for-REAL-programmers create mode 120000 Lang/Icon/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Icon/Catamorphism create mode 120000 Lang/Icon/Chinese-remainder-theorem create mode 120000 Lang/Icon/Circles-of-given-radius-through-two-points create mode 120000 Lang/Icon/Closures-Value-capture create mode 120000 Lang/Icon/Combinations-and-permutations create mode 120000 Lang/Icon/Comma-quibbling create mode 120000 Lang/Icon/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Icon/Fibonacci-word create mode 120000 Lang/Icon/Fibonacci-word-fractal create mode 120000 Lang/Icon/File-input-output create mode 120000 Lang/Icon/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Icon/Fractran create mode 120000 Lang/Icon/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Icon/Left-factorials create mode 120000 Lang/Icon/Longest-increasing-subsequence create mode 120000 Lang/Icon/Ludic-numbers create mode 120000 Lang/Icon/Move-to-front-algorithm create mode 120000 Lang/Icon/Munching-squares create mode 120000 Lang/Icon/Narcissistic-decimal-number create mode 120000 Lang/Icon/Nth create mode 120000 Lang/Icon/Odd-word-problem create mode 120000 Lang/Icon/Old-lady-swallowed-a-fly create mode 120000 Lang/Icon/Order-disjoint-list-items create mode 120000 Lang/Icon/Parse-an-IP-Address create mode 120000 Lang/Icon/Percolation-Mean-run-density create mode 120000 Lang/Icon/Pernicious-numbers create mode 120000 Lang/Icon/Quickselect-algorithm create mode 120000 Lang/Icon/RSA-code create mode 120000 Lang/Icon/Rep-string create mode 120000 Lang/Icon/Reverse-words-in-a-string create mode 120000 Lang/Icon/Semiprime create mode 120000 Lang/Icon/State-name-puzzle create mode 120000 Lang/Icon/Statistics-Basic create mode 120000 Lang/Icon/String-append create mode 120000 Lang/Icon/String-prepend create mode 120000 Lang/Icon/Sum-multiples-of-3-and-5 create mode 120000 Lang/Icon/The-Twelve-Days-of-Christmas create mode 120000 Lang/Icon/Zero-to-the-zero-power create mode 120000 Lang/Io/Currying create mode 120000 Lang/Io/File-input-output create mode 120000 Lang/J/9-billion-names-of-God-the-integer create mode 120000 Lang/J/ABC-Problem create mode 120000 Lang/J/AKS-test-for-primes create mode 120000 Lang/J/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/J/Aliquot-sequence-classifications create mode 120000 Lang/J/Almost-prime create mode 120000 Lang/J/Amb create mode 120000 Lang/J/Amicable-pairs create mode 120000 Lang/J/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/J/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/J/Benfords-law create mode 120000 Lang/J/Bernoulli-numbers create mode 120000 Lang/J/CSV-data-manipulation create mode 120000 Lang/J/Calendar---for-REAL-programmers create mode 120000 Lang/J/Casting-out-nines create mode 120000 Lang/J/Catalan-numbers-Pascals-triangle create mode 120000 Lang/J/Catamorphism create mode 120000 Lang/J/Chinese-remainder-theorem create mode 120000 Lang/J/Circles-of-given-radius-through-two-points create mode 120000 Lang/J/Closures-Value-capture create mode 120000 Lang/J/Combinations-and-permutations create mode 120000 Lang/J/Comma-quibbling create mode 120000 Lang/J/Conjugate-transpose create mode 120000 Lang/J/Convert-decimal-number-to-rational create mode 120000 Lang/J/Currying create mode 120000 Lang/J/Digital-root-Multiplicative-digital-root create mode 120000 Lang/J/Draw-a-clock create mode 120000 Lang/J/Extensible-prime-generator create mode 120000 Lang/J/Fibonacci-word create mode 120000 Lang/J/Fibonacci-word-fractal create mode 120000 Lang/J/File-input-output create mode 120000 Lang/J/Find-the-last-Sunday-of-each-month create mode 120000 Lang/J/Flipping-bits-game create mode 120000 Lang/J/Fractran create mode 120000 Lang/J/Gaussian-elimination create mode 120000 Lang/J/Generate-Chess960-starting-position create mode 120000 Lang/J/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/J/Hash-join create mode 120000 Lang/J/Hello-world-Newbie create mode 120000 Lang/J/Heronian-triangles create mode 120000 Lang/J/Hickerson-series-of-almost-integers create mode 120000 Lang/J/IBAN create mode 120000 Lang/J/Integer-overflow create mode 120000 Lang/J/Iterated-digits-squaring create mode 120000 Lang/J/K-d-tree create mode 120000 Lang/J/Left-factorials create mode 120000 Lang/J/Longest-increasing-subsequence create mode 120000 Lang/J/Ludic-numbers create mode 120000 Lang/J/Magic-squares-of-odd-order create mode 120000 Lang/J/Maximum-triangle-path-sum create mode 120000 Lang/J/Move-to-front-algorithm create mode 120000 Lang/J/Munching-squares create mode 120000 Lang/J/Narcissistic-decimal-number create mode 120000 Lang/J/Natural-sorting create mode 120000 Lang/J/Nth create mode 120000 Lang/J/Odd-word-problem create mode 120000 Lang/J/Old-lady-swallowed-a-fly create mode 120000 Lang/J/Order-disjoint-list-items create mode 120000 Lang/J/Paraffins create mode 120000 Lang/J/Parse-an-IP-Address create mode 120000 Lang/J/Penneys-game create mode 120000 Lang/J/Percolation-Mean-cluster-density create mode 120000 Lang/J/Percolation-Mean-run-density create mode 120000 Lang/J/Percolation-Site-percolation create mode 120000 Lang/J/Permutations-Rank-of-a-permutation create mode 120000 Lang/J/Pernicious-numbers create mode 120000 Lang/J/Phrase-reversals create mode 120000 Lang/J/Quickselect-algorithm create mode 120000 Lang/J/RSA-code create mode 120000 Lang/J/Ranking-methods create mode 120000 Lang/J/Rep-string create mode 120000 Lang/J/Reverse-words-in-a-string create mode 120000 Lang/J/Runge-Kutta-method create mode 120000 Lang/J/Semiprime create mode 120000 Lang/J/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/J/Solve-a-Holy-Knights-tour create mode 120000 Lang/J/Solve-the-no-connection-puzzle create mode 120000 Lang/J/Sparkline-in-unicode create mode 120000 Lang/J/State-name-puzzle create mode 120000 Lang/J/Statistics-Basic create mode 120000 Lang/J/Stern-Brocot-sequence create mode 120000 Lang/J/String-append create mode 120000 Lang/J/String-matching create mode 120000 Lang/J/String-prepend create mode 120000 Lang/J/Sum-multiples-of-3-and-5 create mode 120000 Lang/J/Textonyms create mode 120000 Lang/J/The-Twelve-Days-of-Christmas create mode 120000 Lang/J/Total-circles-area create mode 120000 Lang/J/Ulam-spiral--for-primes- create mode 120000 Lang/J/Unix-ls create mode 120000 Lang/J/World-Cup-group-stage create mode 120000 Lang/J/Zero-to-the-zero-power create mode 120000 Lang/J/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Java/ABC-Problem create mode 120000 Lang/Java/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Java/Benfords-law create mode 120000 Lang/Java/CSV-data-manipulation create mode 120000 Lang/Java/Catamorphism create mode 120000 Lang/Java/Closures-Value-capture create mode 120000 Lang/Java/Comma-quibbling create mode 120000 Lang/Java/Currying create mode 120000 Lang/Java/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Java/Draw-a-clock create mode 120000 Lang/Java/Fibonacci-word create mode 120000 Lang/Java/File-input-output create mode 120000 Lang/Java/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Java/Fractran create mode 120000 Lang/Java/Generate-Chess960-starting-position create mode 120000 Lang/Java/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Java/Heronian-triangles create mode 120000 Lang/Java/IBAN create mode 120000 Lang/Java/Integer-overflow create mode 120000 Lang/Java/Iterated-digits-squaring create mode 120000 Lang/Java/Left-factorials create mode 120000 Lang/Java/Longest-increasing-subsequence create mode 120000 Lang/Java/Ludic-numbers create mode 120000 Lang/Java/Magic-squares-of-odd-order create mode 120000 Lang/Java/Make-directory-path create mode 120000 Lang/Java/Maximum-triangle-path-sum create mode 120000 Lang/Java/Move-to-front-algorithm create mode 120000 Lang/Java/Munching-squares create mode 120000 Lang/Java/Narcissistic-decimal-number create mode 120000 Lang/Java/Nth create mode 120000 Lang/Java/Odd-word-problem create mode 120000 Lang/Java/Old-lady-swallowed-a-fly create mode 120000 Lang/Java/Order-disjoint-list-items create mode 120000 Lang/Java/Parse-an-IP-Address create mode 120000 Lang/Java/Penneys-game create mode 120000 Lang/Java/Permutations-Rank-of-a-permutation create mode 120000 Lang/Java/Pernicious-numbers create mode 120000 Lang/Java/Phrase-reversals create mode 120000 Lang/Java/Quickselect-algorithm create mode 120000 Lang/Java/Ranking-methods create mode 120000 Lang/Java/Rep-string create mode 120000 Lang/Java/Reverse-words-in-a-string create mode 120000 Lang/Java/Semiprime create mode 120000 Lang/Java/Sparkline-in-unicode create mode 120000 Lang/Java/State-name-puzzle create mode 120000 Lang/Java/Stern-Brocot-sequence create mode 120000 Lang/Java/String-append create mode 120000 Lang/Java/String-matching create mode 120000 Lang/Java/String-prepend create mode 120000 Lang/Java/Sum-multiples-of-3-and-5 create mode 120000 Lang/Java/The-ISAAC-Cipher create mode 120000 Lang/Java/The-Twelve-Days-of-Christmas create mode 120000 Lang/Java/Ulam-spiral--for-primes- create mode 120000 Lang/Java/Vogels-approximation-method create mode 120000 Lang/Java/World-Cup-group-stage create mode 120000 Lang/Java/Zero-to-the-zero-power create mode 120000 Lang/Java/Zhang-Suen-thinning-algorithm create mode 120000 Lang/JavaScript/9-billion-names-of-God-the-integer create mode 120000 Lang/JavaScript/ABC-Problem create mode 120000 Lang/JavaScript/AKS-test-for-primes create mode 120000 Lang/JavaScript/Amb create mode 120000 Lang/JavaScript/Catamorphism create mode 120000 Lang/JavaScript/Closures-Value-capture create mode 120000 Lang/JavaScript/Comma-quibbling create mode 120000 Lang/JavaScript/Currying create mode 120000 Lang/JavaScript/Draw-a-clock create mode 120000 Lang/JavaScript/File-input-output create mode 120000 Lang/JavaScript/Fractran create mode 120000 Lang/JavaScript/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/JavaScript/Heronian-triangles create mode 120000 Lang/JavaScript/Longest-increasing-subsequence create mode 120000 Lang/JavaScript/Make-directory-path create mode 120000 Lang/JavaScript/Move-to-front-algorithm create mode 120000 Lang/JavaScript/Runge-Kutta-method create mode 120000 Lang/JavaScript/String-append create mode 120000 Lang/JavaScript/String-matching create mode 120000 Lang/JavaScript/The-Twelve-Days-of-Christmas create mode 120000 Lang/JavaScript/Zero-to-the-zero-power create mode 120000 Lang/Julia/ABC-Problem create mode 120000 Lang/Julia/Almost-prime create mode 120000 Lang/Julia/Benfords-law create mode 120000 Lang/Julia/Casting-out-nines create mode 120000 Lang/Julia/Closures-Value-capture create mode 120000 Lang/Julia/Comma-quibbling create mode 120000 Lang/Julia/Conjugate-transpose create mode 120000 Lang/Julia/Convert-decimal-number-to-rational create mode 120000 Lang/Julia/File-input-output create mode 120000 Lang/Julia/Gaussian-elimination create mode 120000 Lang/Julia/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Julia/Iterated-digits-squaring create mode 120000 Lang/Julia/Left-factorials create mode 120000 Lang/Julia/Reverse-words-in-a-string create mode 120000 Lang/Julia/Runge-Kutta-method create mode 120000 Lang/Julia/Semiprime create mode 120000 Lang/Julia/String-append create mode 120000 Lang/Julia/String-matching create mode 120000 Lang/Julia/String-prepend create mode 120000 Lang/Julia/Sum-multiples-of-3-and-5 create mode 120000 Lang/Julia/Total-circles-area create mode 120000 Lang/K/File-input-output create mode 120000 Lang/K/String-matching create mode 120000 Lang/LOLCODE/Catamorphism create mode 120000 Lang/LOLCODE/The-Twelve-Days-of-Christmas create mode 120000 Lang/Lang5/File-input-output create mode 120000 Lang/Lang5/String-matching create mode 120000 Lang/Liberty-BASIC/Benfords-law create mode 120000 Lang/Liberty-BASIC/Convert-decimal-number-to-rational create mode 120000 Lang/Liberty-BASIC/Draw-a-clock create mode 120000 Lang/Liberty-BASIC/File-input-output create mode 120000 Lang/Liberty-BASIC/Munching-squares create mode 120000 Lang/Liberty-BASIC/Statistics-Basic create mode 120000 Lang/Liberty-BASIC/String-matching create mode 120000 Lang/Limbo/Sum-multiples-of-3-and-5 create mode 120000 Lang/Lisaac/File-input-output create mode 120000 Lang/Locomotive-Basic/Draw-a-clock create mode 120000 Lang/Locomotive-Basic/Hello-world-Newbie create mode 120000 Lang/Logo/ABC-Problem create mode 120000 Lang/Logo/Comma-quibbling create mode 120000 Lang/Logo/Fibonacci-word-fractal create mode 120000 Lang/Logo/File-input-output create mode 120000 Lang/Logo/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Logo/String-matching create mode 120000 Lang/Logo/The-Twelve-Days-of-Christmas create mode 120000 Lang/Logtalk/Catamorphism create mode 120000 Lang/Logtalk/Closures-Value-capture create mode 120000 Lang/Lua/Amb create mode 120000 Lang/Lua/Benfords-law create mode 120000 Lang/Lua/CSV-data-manipulation create mode 120000 Lang/Lua/Closures-Value-capture create mode 120000 Lang/Lua/File-input-output create mode 120000 Lang/Lua/Iterated-digits-squaring create mode 120000 Lang/Lua/Longest-increasing-subsequence create mode 120000 Lang/Lua/Reverse-words-in-a-string create mode 120000 Lang/Lua/String-matching create mode 120000 Lang/Lua/String-prepend create mode 120000 Lang/Lua/The-Twelve-Days-of-Christmas create mode 120000 Lang/MATLAB/ABC-Problem create mode 120000 Lang/MATLAB/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/MATLAB/CSV-data-manipulation create mode 120000 Lang/MATLAB/Catalan-numbers-Pascals-triangle create mode 120000 Lang/MATLAB/Convert-decimal-number-to-rational create mode 120000 Lang/MATLAB/Draw-a-clock create mode 120000 Lang/MATLAB/Flipping-bits-game create mode 120000 Lang/MATLAB/Gaussian-elimination create mode 120000 Lang/MATLAB/IBAN create mode 120000 Lang/MATLAB/Move-to-front-algorithm create mode 120000 Lang/MATLAB/Munching-squares create mode 120000 Lang/MATLAB/Narcissistic-decimal-number create mode 120000 Lang/MATLAB/Nth create mode 120000 Lang/MATLAB/Reverse-words-in-a-string create mode 120000 Lang/MATLAB/Runge-Kutta-method create mode 120000 Lang/MATLAB/Statistics-Basic create mode 120000 Lang/MATLAB/String-matching create mode 120000 Lang/MATLAB/Sum-multiples-of-3-and-5 create mode 120000 Lang/MATLAB/Total-circles-area create mode 120000 Lang/MAXScript/ABC-Problem create mode 120000 Lang/MAXScript/Comma-quibbling create mode 120000 Lang/MAXScript/File-input-output create mode 120000 Lang/Maple/AKS-test-for-primes create mode 120000 Lang/Maple/Bernoulli-numbers create mode 120000 Lang/Maple/CSV-data-manipulation create mode 120000 Lang/Maple/Catamorphism create mode 120000 Lang/Maple/Chinese-remainder-theorem create mode 120000 Lang/Maple/Closures-Value-capture create mode 120000 Lang/Maple/Comma-quibbling create mode 120000 Lang/Maple/Conjugate-transpose create mode 120000 Lang/Maple/Convert-decimal-number-to-rational create mode 120000 Lang/Maple/Rep-string create mode 120000 Lang/Maple/String-matching create mode 120000 Lang/Maple/Sum-multiples-of-3-and-5 create mode 120000 Lang/Maple/Zero-to-the-zero-power create mode 120000 Lang/Mathematica/9-billion-names-of-God-the-integer create mode 120000 Lang/Mathematica/ABC-Problem create mode 120000 Lang/Mathematica/AKS-test-for-primes create mode 120000 Lang/Mathematica/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Mathematica/Almost-prime create mode 120000 Lang/Mathematica/Amb create mode 120000 Lang/Mathematica/Amicable-pairs create mode 120000 Lang/Mathematica/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Mathematica/Benfords-law create mode 120000 Lang/Mathematica/Bernoulli-numbers create mode 120000 Lang/Mathematica/CSV-data-manipulation create mode 120000 Lang/Mathematica/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Mathematica/Catamorphism create mode 120000 Lang/Mathematica/Chinese-remainder-theorem create mode 120000 Lang/Mathematica/Closures-Value-capture create mode 120000 Lang/Mathematica/Combinations-and-permutations create mode 120000 Lang/Mathematica/Comma-quibbling create mode 120000 Lang/Mathematica/Conjugate-transpose create mode 120000 Lang/Mathematica/Convert-decimal-number-to-rational create mode 120000 Lang/Mathematica/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Mathematica/Draw-a-clock create mode 120000 Lang/Mathematica/Extensible-prime-generator create mode 120000 Lang/Mathematica/Fibonacci-word create mode 120000 Lang/Mathematica/Fibonacci-word-fractal create mode 120000 Lang/Mathematica/File-input-output create mode 120000 Lang/Mathematica/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Mathematica/Fractran create mode 120000 Lang/Mathematica/Gaussian-elimination create mode 120000 Lang/Mathematica/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Mathematica/Hash-join create mode 120000 Lang/Mathematica/Hickerson-series-of-almost-integers create mode 120000 Lang/Mathematica/IBAN create mode 120000 Lang/Mathematica/Iterated-digits-squaring create mode 120000 Lang/Mathematica/Left-factorials create mode 120000 Lang/Mathematica/Longest-increasing-subsequence create mode 120000 Lang/Mathematica/Ludic-numbers create mode 120000 Lang/Mathematica/Magic-squares-of-odd-order create mode 120000 Lang/Mathematica/Make-directory-path create mode 120000 Lang/Mathematica/Maximum-triangle-path-sum create mode 120000 Lang/Mathematica/Move-to-front-algorithm create mode 120000 Lang/Mathematica/Munching-squares create mode 120000 Lang/Mathematica/Nth create mode 120000 Lang/Mathematica/Paraffins create mode 120000 Lang/Mathematica/Permutations-Rank-of-a-permutation create mode 120000 Lang/Mathematica/Pernicious-numbers create mode 120000 Lang/Mathematica/Phrase-reversals create mode 120000 Lang/Mathematica/Rep-string create mode 120000 Lang/Mathematica/Reverse-words-in-a-string create mode 120000 Lang/Mathematica/Runge-Kutta-method create mode 120000 Lang/Mathematica/Semiprime create mode 120000 Lang/Mathematica/Sparkline-in-unicode create mode 120000 Lang/Mathematica/State-name-puzzle create mode 120000 Lang/Mathematica/Statistics-Basic create mode 120000 Lang/Mathematica/String-append create mode 120000 Lang/Mathematica/String-matching create mode 120000 Lang/Mathematica/String-prepend create mode 120000 Lang/Mathematica/Sum-multiples-of-3-and-5 create mode 120000 Lang/Mathematica/The-Twelve-Days-of-Christmas create mode 120000 Lang/Mathematica/Total-circles-area create mode 120000 Lang/Mathematica/Unix-ls create mode 120000 Lang/Mathematica/Zero-to-the-zero-power create mode 120000 Lang/Mathematica/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Maxima/Catamorphism create mode 120000 Lang/Maxima/Circles-of-given-radius-through-two-points create mode 120000 Lang/Maxima/Magic-squares-of-odd-order create mode 120000 Lang/Maxima/Runge-Kutta-method create mode 120000 Lang/Maxima/Sum-multiples-of-3-and-5 create mode 120000 Lang/Mercury/Amb create mode 120000 Lang/Mercury/File-input-output create mode 120000 Lang/Mercury/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Mercury/String-prepend create mode 120000 Lang/Modula-3/File-input-output create mode 120000 Lang/Nemerle/Catamorphism create mode 120000 Lang/Nemerle/Closures-Value-capture create mode 120000 Lang/Nemerle/Currying create mode 120000 Lang/NetRexx/Amb create mode 120000 Lang/NetRexx/Benfords-law create mode 120000 Lang/NetRexx/CSV-data-manipulation create mode 120000 Lang/NetRexx/Comma-quibbling create mode 120000 Lang/NetRexx/Convert-decimal-number-to-rational create mode 120000 Lang/NetRexx/Draw-a-clock create mode 120000 Lang/NetRexx/File-input-output create mode 120000 Lang/NetRexx/Quickselect-algorithm create mode 120000 Lang/NetRexx/Rep-string create mode 120000 Lang/NetRexx/Sparkline-in-unicode create mode 120000 Lang/NetRexx/String-append create mode 120000 Lang/NetRexx/String-matching create mode 120000 Lang/NetRexx/String-prepend create mode 120000 Lang/NetRexx/Sum-multiples-of-3-and-5 create mode 120000 Lang/NetRexx/Zero-to-the-zero-power create mode 120000 Lang/NewLISP/String-append create mode 120000 Lang/NewLISP/String-matching create mode 120000 Lang/NewLISP/String-prepend create mode 120000 Lang/OCaml/9-billion-names-of-God-the-integer create mode 120000 Lang/OCaml/ABC-Problem create mode 120000 Lang/OCaml/Amb create mode 120000 Lang/OCaml/Catamorphism create mode 120000 Lang/OCaml/Chinese-remainder-theorem create mode 120000 Lang/OCaml/Closures-Value-capture create mode 120000 Lang/OCaml/Currying create mode 120000 Lang/OCaml/Draw-a-clock create mode 120000 Lang/OCaml/File-input-output create mode 120000 Lang/OCaml/Find-the-last-Sunday-of-each-month create mode 120000 Lang/OCaml/Gaussian-elimination create mode 120000 Lang/OCaml/Hash-join create mode 120000 Lang/OCaml/Hello-world-Newbie create mode 120000 Lang/OCaml/Longest-increasing-subsequence create mode 120000 Lang/OCaml/Munching-squares create mode 120000 Lang/OCaml/Odd-word-problem create mode 120000 Lang/OCaml/Old-lady-swallowed-a-fly create mode 120000 Lang/OCaml/Quickselect-algorithm create mode 120000 Lang/OCaml/Reverse-words-in-a-string create mode 120000 Lang/OCaml/Runge-Kutta-method create mode 120000 Lang/OCaml/String-append create mode 120000 Lang/OCaml/String-matching create mode 120000 Lang/OCaml/Unix-ls create mode 120000 Lang/Oberon-2/ABC-Problem create mode 120000 Lang/Oberon-2/Catamorphism create mode 120000 Lang/Oberon-2/Hash-join create mode 120000 Lang/Oberon-2/IBAN create mode 120000 Lang/Oberon-2/Iterated-digits-squaring create mode 120000 Lang/Objeck/Almost-prime create mode 120000 Lang/Objeck/Casting-out-nines create mode 120000 Lang/Objeck/File-input-output create mode 120000 Lang/Objeck/Generate-Chess960-starting-position create mode 120000 Lang/Objeck/Reverse-words-in-a-string create mode 120000 Lang/Objeck/Semiprime create mode 120000 Lang/Objeck/String-append create mode 120000 Lang/Objeck/String-matching create mode 120000 Lang/Objeck/The-Twelve-Days-of-Christmas create mode 120000 Lang/Object-Pascal/File-input-output create mode 120000 Lang/Objective-C/Closures-Value-capture create mode 120000 Lang/Objective-C/File-input-output create mode 120000 Lang/Objective-C/Longest-increasing-subsequence create mode 120000 Lang/Objective-C/String-matching create mode 120000 Lang/Octave/File-input-output create mode 120000 Lang/Octave/Munching-squares create mode 120000 Lang/Octave/Runge-Kutta-method create mode 120000 Lang/OpenEdge-Progress/Amb create mode 120000 Lang/OpenEdge-Progress/File-input-output create mode 120000 Lang/OxygenBasic/String-matching create mode 120000 Lang/Oz/Amb create mode 120000 Lang/Oz/File-input-output create mode 120000 Lang/PARI-GP/AKS-test-for-primes create mode 120000 Lang/PARI-GP/Almost-prime create mode 120000 Lang/PARI-GP/Amb create mode 120000 Lang/PARI-GP/Amicable-pairs create mode 120000 Lang/PARI-GP/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/PARI-GP/Benfords-law create mode 120000 Lang/PARI-GP/Bernoulli-numbers create mode 120000 Lang/PARI-GP/Casting-out-nines create mode 120000 Lang/PARI-GP/Catalan-numbers-Pascals-triangle create mode 120000 Lang/PARI-GP/Catamorphism create mode 120000 Lang/PARI-GP/Chinese-remainder-theorem create mode 120000 Lang/PARI-GP/Circles-of-given-radius-through-two-points create mode 120000 Lang/PARI-GP/Closures-Value-capture create mode 120000 Lang/PARI-GP/Comma-quibbling create mode 120000 Lang/PARI-GP/Conjugate-transpose create mode 120000 Lang/PARI-GP/Convert-decimal-number-to-rational create mode 120000 Lang/PARI-GP/Currying create mode 120000 Lang/PARI-GP/Fibonacci-word create mode 120000 Lang/PARI-GP/File-input-output create mode 120000 Lang/PARI-GP/Gaussian-elimination create mode 120000 Lang/PARI-GP/Hello-world-Newbie create mode 120000 Lang/PARI-GP/Hickerson-series-of-almost-integers create mode 120000 Lang/PARI-GP/Left-factorials create mode 120000 Lang/PARI-GP/Machine-code create mode 120000 Lang/PARI-GP/Maximum-triangle-path-sum create mode 120000 Lang/PARI-GP/Nth create mode 120000 Lang/PARI-GP/Permutations-Rank-of-a-permutation create mode 120000 Lang/PARI-GP/Pernicious-numbers create mode 120000 Lang/PARI-GP/Quickselect-algorithm create mode 120000 Lang/PARI-GP/Rep-string create mode 120000 Lang/PARI-GP/Runge-Kutta-method create mode 120000 Lang/PARI-GP/Semiprime create mode 120000 Lang/PARI-GP/Statistics-Basic create mode 120000 Lang/PARI-GP/String-append create mode 120000 Lang/PARI-GP/String-matching create mode 120000 Lang/PARI-GP/String-prepend create mode 120000 Lang/PARI-GP/Sum-multiples-of-3-and-5 create mode 120000 Lang/PARI-GP/Unix-ls create mode 120000 Lang/PARI-GP/Zero-to-the-zero-power create mode 120000 Lang/PHP/ABC-Problem create mode 120000 Lang/PHP/CSV-data-manipulation create mode 120000 Lang/PHP/Calendar---for-REAL-programmers create mode 120000 Lang/PHP/Closures-Value-capture create mode 120000 Lang/PHP/Comma-quibbling create mode 120000 Lang/PHP/File-input-output create mode 120000 Lang/PHP/Gaussian-elimination create mode 120000 Lang/PHP/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/PHP/Hash-join create mode 120000 Lang/PHP/Longest-increasing-subsequence create mode 120000 Lang/PHP/Munching-squares create mode 120000 Lang/PHP/Nth create mode 120000 Lang/PHP/Odd-word-problem create mode 120000 Lang/PHP/Old-lady-swallowed-a-fly create mode 120000 Lang/PHP/Phrase-reversals create mode 120000 Lang/PHP/String-matching create mode 120000 Lang/PHP/The-Twelve-Days-of-Christmas create mode 120000 Lang/PHP/Zero-to-the-zero-power create mode 120000 Lang/PL-I/ABC-Problem create mode 120000 Lang/PL-I/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/PL-I/Amb create mode 120000 Lang/PL-I/Amicable-pairs create mode 120000 Lang/PL-I/Benfords-law create mode 120000 Lang/PL-I/Bernoulli-numbers create mode 120000 Lang/PL-I/CSV-data-manipulation create mode 120000 Lang/PL-I/Calendar---for-REAL-programmers create mode 120000 Lang/PL-I/Circles-of-given-radius-through-two-points create mode 120000 Lang/PL-I/Comma-quibbling create mode 120000 Lang/PL-I/Conjugate-transpose create mode 120000 Lang/PL-I/Convert-decimal-number-to-rational create mode 120000 Lang/PL-I/Digital-root-Multiplicative-digital-root create mode 120000 Lang/PL-I/Fibonacci-word create mode 120000 Lang/PL-I/File-input-output create mode 120000 Lang/PL-I/Flipping-bits-game create mode 120000 Lang/PL-I/Gaussian-elimination create mode 120000 Lang/PL-I/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/PL-I/Hickerson-series-of-almost-integers create mode 120000 Lang/PL-I/Left-factorials create mode 120000 Lang/PL-I/Ludic-numbers create mode 120000 Lang/PL-I/Magic-squares-of-odd-order create mode 120000 Lang/PL-I/Move-to-front-algorithm create mode 120000 Lang/PL-I/Munching-squares create mode 120000 Lang/PL-I/Nth create mode 120000 Lang/PL-I/Odd-word-problem create mode 120000 Lang/PL-I/Quickselect-algorithm create mode 120000 Lang/PL-I/Rep-string create mode 120000 Lang/PL-I/Reverse-words-in-a-string create mode 120000 Lang/PL-I/Runge-Kutta-method create mode 120000 Lang/PL-I/Semiprime create mode 120000 Lang/PL-I/Statistics-Basic create mode 120000 Lang/PL-I/String-append create mode 120000 Lang/PL-I/String-matching create mode 120000 Lang/PL-I/String-prepend create mode 120000 Lang/PL-I/Sum-multiples-of-3-and-5 create mode 120000 Lang/PL-I/Zero-to-the-zero-power create mode 120000 Lang/PL-I/Zhang-Suen-thinning-algorithm create mode 120000 Lang/PL-pgSQL/Benfords-law create mode 120000 Lang/Pascal/AKS-test-for-primes create mode 120000 Lang/Pascal/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Pascal/Almost-prime create mode 120000 Lang/Pascal/Amicable-pairs create mode 120000 Lang/Pascal/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Pascal/Catamorphism create mode 120000 Lang/Pascal/Extensible-prime-generator create mode 120000 Lang/Pascal/Fibonacci-word create mode 120000 Lang/Pascal/Iterated-digits-squaring create mode 120000 Lang/Pascal/Machine-code create mode 120000 Lang/Pascal/Maximum-triangle-path-sum create mode 120000 Lang/Pascal/Narcissistic-decimal-number create mode 120000 Lang/Pascal/Paraffins create mode 120000 Lang/Pascal/Pernicious-numbers create mode 120000 Lang/Pascal/Runge-Kutta-method create mode 120000 Lang/Pascal/Semiprime create mode 120000 Lang/Pascal/String-append create mode 120000 Lang/Pascal/String-prepend create mode 120000 Lang/Pascal/Sum-multiples-of-3-and-5 create mode 120000 Lang/Pascal/The-ISAAC-Cipher create mode 120000 Lang/Perl-6/9-billion-names-of-God-the-integer create mode 120000 Lang/Perl-6/ABC-Problem create mode 120000 Lang/Perl-6/AKS-test-for-primes create mode 120000 Lang/Perl-6/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Perl-6/Aliquot-sequence-classifications create mode 120000 Lang/Perl-6/Almost-prime create mode 120000 Lang/Perl-6/Amb create mode 120000 Lang/Perl-6/Amicable-pairs create mode 120000 Lang/Perl-6/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Perl-6/Benfords-law create mode 120000 Lang/Perl-6/Bernoulli-numbers create mode 120000 Lang/Perl-6/Bitcoin-public-point-to-address create mode 120000 Lang/Perl-6/CSV-data-manipulation create mode 120000 Lang/Perl-6/Calendar---for-REAL-programmers create mode 120000 Lang/Perl-6/Casting-out-nines create mode 120000 Lang/Perl-6/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Perl-6/Catamorphism create mode 120000 Lang/Perl-6/Chinese-remainder-theorem create mode 120000 Lang/Perl-6/Circles-of-given-radius-through-two-points create mode 120000 Lang/Perl-6/Closures-Value-capture create mode 120000 Lang/Perl-6/Combinations-and-permutations create mode 120000 Lang/Perl-6/Comma-quibbling create mode 120000 Lang/Perl-6/Convert-decimal-number-to-rational create mode 120000 Lang/Perl-6/Currying create mode 120000 Lang/Perl-6/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Perl-6/Draw-a-clock create mode 120000 Lang/Perl-6/Extensible-prime-generator create mode 120000 Lang/Perl-6/Fibonacci-word create mode 120000 Lang/Perl-6/Fibonacci-word-fractal create mode 120000 Lang/Perl-6/File-input-output create mode 120000 Lang/Perl-6/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Perl-6/Flipping-bits-game create mode 120000 Lang/Perl-6/Fractran create mode 120000 Lang/Perl-6/Gaussian-elimination create mode 120000 Lang/Perl-6/Generate-Chess960-starting-position create mode 120000 Lang/Perl-6/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Perl-6/Hash-join create mode 120000 Lang/Perl-6/Heronian-triangles create mode 120000 Lang/Perl-6/Hickerson-series-of-almost-integers create mode 120000 Lang/Perl-6/IBAN create mode 120000 Lang/Perl-6/Iterated-digits-squaring create mode 120000 Lang/Perl-6/K-d-tree create mode 120000 Lang/Perl-6/Left-factorials create mode 120000 Lang/Perl-6/Longest-increasing-subsequence create mode 120000 Lang/Perl-6/Ludic-numbers create mode 120000 Lang/Perl-6/Magic-squares-of-odd-order create mode 120000 Lang/Perl-6/Make-directory-path create mode 120000 Lang/Perl-6/Maximum-triangle-path-sum create mode 120000 Lang/Perl-6/Move-to-front-algorithm create mode 120000 Lang/Perl-6/Munching-squares create mode 120000 Lang/Perl-6/Narcissistic-decimal-number create mode 120000 Lang/Perl-6/Natural-sorting create mode 120000 Lang/Perl-6/Nth create mode 120000 Lang/Perl-6/Odd-word-problem create mode 120000 Lang/Perl-6/Old-lady-swallowed-a-fly create mode 120000 Lang/Perl-6/Order-disjoint-list-items create mode 120000 Lang/Perl-6/Paraffins create mode 120000 Lang/Perl-6/Parse-an-IP-Address create mode 120000 Lang/Perl-6/Penneys-game create mode 120000 Lang/Perl-6/Percolation-Mean-run-density create mode 120000 Lang/Perl-6/Pernicious-numbers create mode 120000 Lang/Perl-6/Phrase-reversals create mode 120000 Lang/Perl-6/Quickselect-algorithm create mode 120000 Lang/Perl-6/RSA-code create mode 120000 Lang/Perl-6/Ranking-methods create mode 120000 Lang/Perl-6/Rep-string create mode 120000 Lang/Perl-6/Reverse-words-in-a-string create mode 120000 Lang/Perl-6/Runge-Kutta-method create mode 120000 Lang/Perl-6/Semiprime create mode 120000 Lang/Perl-6/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Perl-6/Solve-a-Holy-Knights-tour create mode 120000 Lang/Perl-6/Solve-a-Hopido-puzzle create mode 120000 Lang/Perl-6/Solve-a-Numbrix-puzzle create mode 120000 Lang/Perl-6/Solve-the-no-connection-puzzle create mode 120000 Lang/Perl-6/Sparkline-in-unicode create mode 120000 Lang/Perl-6/State-name-puzzle create mode 120000 Lang/Perl-6/Statistics-Basic create mode 120000 Lang/Perl-6/Stern-Brocot-sequence create mode 120000 Lang/Perl-6/String-append create mode 120000 Lang/Perl-6/String-matching create mode 120000 Lang/Perl-6/String-prepend create mode 120000 Lang/Perl-6/Sum-multiples-of-3-and-5 create mode 120000 Lang/Perl-6/Textonyms create mode 120000 Lang/Perl-6/The-Twelve-Days-of-Christmas create mode 120000 Lang/Perl-6/Total-circles-area create mode 120000 Lang/Perl-6/Ulam-spiral--for-primes- create mode 120000 Lang/Perl-6/Unix-ls create mode 120000 Lang/Perl-6/World-Cup-group-stage create mode 120000 Lang/Perl-6/Zero-to-the-zero-power create mode 120000 Lang/Perl-6/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Perl/9-billion-names-of-God-the-integer create mode 120000 Lang/Perl/ABC-Problem create mode 120000 Lang/Perl/AKS-test-for-primes create mode 120000 Lang/Perl/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Perl/Aliquot-sequence-classifications create mode 120000 Lang/Perl/Almost-prime create mode 120000 Lang/Perl/Amb create mode 120000 Lang/Perl/Amicable-pairs create mode 120000 Lang/Perl/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Perl/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Perl/Benfords-law create mode 120000 Lang/Perl/Bernoulli-numbers create mode 120000 Lang/Perl/Bitcoin-public-point-to-address create mode 120000 Lang/Perl/CSV-data-manipulation create mode 120000 Lang/Perl/Calendar---for-REAL-programmers create mode 120000 Lang/Perl/Casting-out-nines create mode 120000 Lang/Perl/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Perl/Catamorphism create mode 120000 Lang/Perl/Chinese-remainder-theorem create mode 120000 Lang/Perl/Closures-Value-capture create mode 120000 Lang/Perl/Combinations-and-permutations create mode 120000 Lang/Perl/Comma-quibbling create mode 120000 Lang/Perl/Convert-decimal-number-to-rational create mode 120000 Lang/Perl/Currying create mode 120000 Lang/Perl/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Perl/Draw-a-clock create mode 120000 Lang/Perl/Extensible-prime-generator create mode 120000 Lang/Perl/Fibonacci-word create mode 120000 Lang/Perl/Fibonacci-word-fractal create mode 120000 Lang/Perl/File-input-output create mode 120000 Lang/Perl/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Perl/Flipping-bits-game create mode 120000 Lang/Perl/Fractran create mode 120000 Lang/Perl/Gaussian-elimination create mode 120000 Lang/Perl/Generate-Chess960-starting-position create mode 120000 Lang/Perl/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Perl/Hash-join create mode 120000 Lang/Perl/Hello-world-Newbie create mode 120000 Lang/Perl/Heronian-triangles create mode 120000 Lang/Perl/Hickerson-series-of-almost-integers create mode 120000 Lang/Perl/IBAN create mode 120000 Lang/Perl/Integer-overflow create mode 120000 Lang/Perl/Iterated-digits-squaring create mode 120000 Lang/Perl/Left-factorials create mode 120000 Lang/Perl/Longest-increasing-subsequence create mode 120000 Lang/Perl/Ludic-numbers create mode 120000 Lang/Perl/Maximum-triangle-path-sum create mode 120000 Lang/Perl/Move-to-front-algorithm create mode 120000 Lang/Perl/Munching-squares create mode 120000 Lang/Perl/Narcissistic-decimal-number create mode 120000 Lang/Perl/Natural-sorting create mode 120000 Lang/Perl/Nth create mode 120000 Lang/Perl/Odd-word-problem create mode 120000 Lang/Perl/Old-lady-swallowed-a-fly create mode 120000 Lang/Perl/Order-disjoint-list-items create mode 120000 Lang/Perl/Paraffins create mode 120000 Lang/Perl/Parse-an-IP-Address create mode 120000 Lang/Perl/Percolation-Mean-run-density create mode 120000 Lang/Perl/Pernicious-numbers create mode 120000 Lang/Perl/Phrase-reversals create mode 120000 Lang/Perl/Quickselect-algorithm create mode 120000 Lang/Perl/Rep-string create mode 120000 Lang/Perl/Reverse-words-in-a-string create mode 120000 Lang/Perl/Rosetta-Code-Find-bare-lang-tags create mode 120000 Lang/Perl/Runge-Kutta-method create mode 120000 Lang/Perl/Semiprime create mode 120000 Lang/Perl/Sparkline-in-unicode create mode 120000 Lang/Perl/State-name-puzzle create mode 120000 Lang/Perl/Statistics-Basic create mode 120000 Lang/Perl/Stern-Brocot-sequence create mode 120000 Lang/Perl/String-append create mode 120000 Lang/Perl/String-matching create mode 120000 Lang/Perl/String-prepend create mode 120000 Lang/Perl/Sum-multiples-of-3-and-5 create mode 120000 Lang/Perl/Textonyms create mode 120000 Lang/Perl/The-ISAAC-Cipher create mode 120000 Lang/Perl/The-Twelve-Days-of-Christmas create mode 120000 Lang/Perl/Ulam-spiral--for-primes- create mode 120000 Lang/Perl/Zero-to-the-zero-power create mode 120000 Lang/PicoLisp/9-billion-names-of-God-the-integer create mode 120000 Lang/PicoLisp/ABC-Problem create mode 120000 Lang/PicoLisp/AKS-test-for-primes create mode 120000 Lang/PicoLisp/Almost-prime create mode 120000 Lang/PicoLisp/Amb create mode 120000 Lang/PicoLisp/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/PicoLisp/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/PicoLisp/Bernoulli-numbers create mode 120000 Lang/PicoLisp/CSV-data-manipulation create mode 120000 Lang/PicoLisp/Calendar---for-REAL-programmers create mode 120000 Lang/PicoLisp/Casting-out-nines create mode 120000 Lang/PicoLisp/Catalan-numbers-Pascals-triangle create mode 120000 Lang/PicoLisp/Catamorphism create mode 120000 Lang/PicoLisp/Chinese-remainder-theorem create mode 120000 Lang/PicoLisp/Closures-Value-capture create mode 120000 Lang/PicoLisp/Comma-quibbling create mode 120000 Lang/PicoLisp/Draw-a-clock create mode 120000 Lang/PicoLisp/File-input-output create mode 120000 Lang/PicoLisp/Find-the-last-Sunday-of-each-month create mode 120000 Lang/PicoLisp/Generate-Chess960-starting-position create mode 120000 Lang/PicoLisp/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/PicoLisp/IBAN create mode 120000 Lang/PicoLisp/Ludic-numbers create mode 120000 Lang/PicoLisp/Narcissistic-decimal-number create mode 120000 Lang/PicoLisp/Natural-sorting create mode 120000 Lang/PicoLisp/Nth create mode 120000 Lang/PicoLisp/Odd-word-problem create mode 120000 Lang/PicoLisp/Old-lady-swallowed-a-fly create mode 120000 Lang/PicoLisp/Parse-an-IP-Address create mode 120000 Lang/PicoLisp/RSA-code create mode 120000 Lang/PicoLisp/Semiprime create mode 120000 Lang/PicoLisp/State-name-puzzle create mode 120000 Lang/PicoLisp/Statistics-Basic create mode 120000 Lang/PicoLisp/String-append create mode 120000 Lang/PicoLisp/String-matching create mode 120000 Lang/PicoLisp/String-prepend create mode 120000 Lang/PicoLisp/Sum-multiples-of-3-and-5 create mode 120000 Lang/PicoLisp/The-ISAAC-Cipher create mode 120000 Lang/PicoLisp/The-Twelve-Days-of-Christmas create mode 120000 Lang/Pike/Closures-Value-capture create mode 120000 Lang/Pike/Paraffins create mode 120000 Lang/Pop11/File-input-output create mode 120000 Lang/PowerBASIC/ABC-Problem create mode 120000 Lang/PowerShell/File-input-output create mode 120000 Lang/PowerShell/Heronian-triangles create mode 120000 Lang/PowerShell/String-matching create mode 120000 Lang/PowerShell/Sum-multiples-of-3-and-5 create mode 120000 Lang/PowerShell/The-Twelve-Days-of-Christmas create mode 120000 Lang/PowerShell/Zero-to-the-zero-power create mode 120000 Lang/Prolog/ABC-Problem create mode 120000 Lang/Prolog/AKS-test-for-primes create mode 120000 Lang/Prolog/Almost-prime create mode 120000 Lang/Prolog/Amb create mode 120000 Lang/Prolog/Benfords-law create mode 120000 Lang/Prolog/CSV-data-manipulation create mode 120000 Lang/Prolog/Catamorphism create mode 120000 Lang/Prolog/Closures-Value-capture create mode 120000 Lang/Prolog/Comma-quibbling create mode 120000 Lang/Prolog/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Prolog/Longest-increasing-subsequence create mode 120000 Lang/Prolog/Maximum-triangle-path-sum create mode 120000 Lang/Prolog/Munching-squares create mode 120000 Lang/Prolog/Nth create mode 120000 Lang/Prolog/Odd-word-problem create mode 120000 Lang/Prolog/Rep-string create mode 120000 Lang/Prolog/Solve-the-no-connection-puzzle create mode 120000 Lang/Prolog/State-name-puzzle create mode 120000 Lang/Prolog/String-prepend create mode 120000 Lang/Prolog/Sum-multiples-of-3-and-5 create mode 120000 Lang/PureBasic/Amb create mode 120000 Lang/PureBasic/Draw-a-clock create mode 120000 Lang/PureBasic/File-input-output create mode 120000 Lang/PureBasic/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/PureBasic/Machine-code create mode 120000 Lang/PureBasic/Munching-squares create mode 120000 Lang/PureBasic/Odd-word-problem create mode 120000 Lang/PureBasic/Statistics-Basic create mode 120000 Lang/PureBasic/String-append create mode 120000 Lang/PureBasic/String-matching create mode 120000 Lang/PureBasic/String-prepend create mode 120000 Lang/Python/9-billion-names-of-God-the-integer create mode 120000 Lang/Python/ABC-Problem create mode 120000 Lang/Python/AKS-test-for-primes create mode 120000 Lang/Python/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Python/Aliquot-sequence-classifications create mode 120000 Lang/Python/Almost-prime create mode 120000 Lang/Python/Amb create mode 120000 Lang/Python/Amicable-pairs create mode 120000 Lang/Python/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Python/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Python/Benfords-law create mode 120000 Lang/Python/Bernoulli-numbers create mode 120000 Lang/Python/CSV-data-manipulation create mode 120000 Lang/Python/Casting-out-nines create mode 120000 Lang/Python/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Python/Catamorphism create mode 120000 Lang/Python/Chinese-remainder-theorem create mode 120000 Lang/Python/Circles-of-given-radius-through-two-points create mode 120000 Lang/Python/Closures-Value-capture create mode 120000 Lang/Python/Combinations-and-permutations create mode 120000 Lang/Python/Comma-quibbling create mode 120000 Lang/Python/Conjugate-transpose create mode 120000 Lang/Python/Convert-decimal-number-to-rational create mode 120000 Lang/Python/Currying create mode 120000 Lang/Python/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Python/Draw-a-clock create mode 120000 Lang/Python/Extensible-prime-generator create mode 120000 Lang/Python/Fibonacci-word create mode 120000 Lang/Python/Fibonacci-word-fractal create mode 120000 Lang/Python/File-input-output create mode 120000 Lang/Python/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Python/Flipping-bits-game create mode 120000 Lang/Python/Fractran create mode 120000 Lang/Python/Gaussian-elimination create mode 120000 Lang/Python/Generate-Chess960-starting-position create mode 120000 Lang/Python/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Python/Hash-join create mode 120000 Lang/Python/Hello-world-Newbie create mode 120000 Lang/Python/Heronian-triangles create mode 120000 Lang/Python/Hickerson-series-of-almost-integers create mode 120000 Lang/Python/IBAN create mode 120000 Lang/Python/Integer-overflow create mode 120000 Lang/Python/Iterated-digits-squaring create mode 120000 Lang/Python/K-d-tree create mode 120000 Lang/Python/Left-factorials create mode 120000 Lang/Python/Longest-increasing-subsequence create mode 120000 Lang/Python/Ludic-numbers create mode 120000 Lang/Python/Machine-code create mode 120000 Lang/Python/Magic-squares-of-odd-order create mode 120000 Lang/Python/Make-directory-path create mode 120000 Lang/Python/Maximum-triangle-path-sum create mode 120000 Lang/Python/Move-to-front-algorithm create mode 120000 Lang/Python/Munching-squares create mode 120000 Lang/Python/Narcissistic-decimal-number create mode 120000 Lang/Python/Natural-sorting create mode 120000 Lang/Python/Nth create mode 120000 Lang/Python/Odd-word-problem create mode 120000 Lang/Python/Old-lady-swallowed-a-fly create mode 120000 Lang/Python/Order-disjoint-list-items create mode 120000 Lang/Python/Paraffins create mode 120000 Lang/Python/Parse-an-IP-Address create mode 120000 Lang/Python/Penneys-game create mode 120000 Lang/Python/Percolation-Bond-percolation create mode 120000 Lang/Python/Percolation-Mean-cluster-density create mode 120000 Lang/Python/Percolation-Mean-run-density create mode 120000 Lang/Python/Percolation-Site-percolation create mode 120000 Lang/Python/Permutations-Rank-of-a-permutation create mode 120000 Lang/Python/Pernicious-numbers create mode 120000 Lang/Python/Phrase-reversals create mode 120000 Lang/Python/Quickselect-algorithm create mode 120000 Lang/Python/RSA-code create mode 120000 Lang/Python/Ranking-methods create mode 120000 Lang/Python/Rep-string create mode 120000 Lang/Python/Reverse-words-in-a-string create mode 120000 Lang/Python/Runge-Kutta-method create mode 120000 Lang/Python/Semiprime create mode 120000 Lang/Python/Solve-the-no-connection-puzzle create mode 120000 Lang/Python/Sparkline-in-unicode create mode 120000 Lang/Python/State-name-puzzle create mode 120000 Lang/Python/Statistics-Basic create mode 120000 Lang/Python/Stern-Brocot-sequence create mode 120000 Lang/Python/String-append create mode 120000 Lang/Python/String-matching create mode 120000 Lang/Python/String-prepend create mode 120000 Lang/Python/Sum-multiples-of-3-and-5 create mode 120000 Lang/Python/Textonyms create mode 120000 Lang/Python/The-ISAAC-Cipher create mode 120000 Lang/Python/The-Twelve-Days-of-Christmas create mode 120000 Lang/Python/Total-circles-area create mode 120000 Lang/Python/Ulam-spiral--for-primes- create mode 120000 Lang/Python/Unix-ls create mode 120000 Lang/Python/Vogels-approximation-method create mode 120000 Lang/Python/World-Cup-group-stage create mode 120000 Lang/Python/Zero-to-the-zero-power create mode 120000 Lang/Python/Zhang-Suen-thinning-algorithm create mode 120000 Lang/R/ABC-Problem create mode 120000 Lang/R/Amb create mode 120000 Lang/R/Benfords-law create mode 120000 Lang/R/CSV-data-manipulation create mode 120000 Lang/R/Chinese-remainder-theorem create mode 120000 Lang/R/Closures-Value-capture create mode 120000 Lang/R/Fibonacci-word create mode 120000 Lang/R/File-input-output create mode 120000 Lang/R/Nth create mode 120000 Lang/R/Sum-multiples-of-3-and-5 create mode 120000 Lang/REALbasic/File-input-output create mode 120000 Lang/REBOL/Comma-quibbling create mode 120000 Lang/REBOL/File-input-output create mode 120000 Lang/REBOL/Find-the-last-Sunday-of-each-month create mode 120000 Lang/REXX/9-billion-names-of-God-the-integer create mode 120000 Lang/REXX/ABC-Problem create mode 120000 Lang/REXX/AKS-test-for-primes create mode 120000 Lang/REXX/Aliquot-sequence-classifications create mode 120000 Lang/REXX/Almost-prime create mode 120000 Lang/REXX/Amb create mode 120000 Lang/REXX/Amicable-pairs create mode 120000 Lang/REXX/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/REXX/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/REXX/Benfords-law create mode 120000 Lang/REXX/Bernoulli-numbers create mode 120000 Lang/REXX/CSV-data-manipulation create mode 120000 Lang/REXX/Calendar---for-REAL-programmers create mode 120000 Lang/REXX/Casting-out-nines create mode 120000 Lang/REXX/Catalan-numbers-Pascals-triangle create mode 120000 Lang/REXX/Catamorphism create mode 120000 Lang/REXX/Chinese-remainder-theorem create mode 120000 Lang/REXX/Circles-of-given-radius-through-two-points create mode 120000 Lang/REXX/Closures-Value-capture create mode 120000 Lang/REXX/Combinations-and-permutations create mode 120000 Lang/REXX/Comma-quibbling create mode 120000 Lang/REXX/Conjugate-transpose create mode 120000 Lang/REXX/Convert-decimal-number-to-rational create mode 120000 Lang/REXX/Currying create mode 120000 Lang/REXX/Digital-root-Multiplicative-digital-root create mode 120000 Lang/REXX/Draw-a-clock create mode 120000 Lang/REXX/Extensible-prime-generator create mode 120000 Lang/REXX/Fibonacci-word create mode 120000 Lang/REXX/Fibonacci-word-fractal create mode 120000 Lang/REXX/File-input-output create mode 120000 Lang/REXX/Find-the-last-Sunday-of-each-month create mode 120000 Lang/REXX/Flipping-bits-game create mode 120000 Lang/REXX/Fractran create mode 120000 Lang/REXX/Gaussian-elimination create mode 120000 Lang/REXX/Generate-Chess960-starting-position create mode 120000 Lang/REXX/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/REXX/Hash-join create mode 120000 Lang/REXX/Hello-world-Newbie create mode 120000 Lang/REXX/Heronian-triangles create mode 120000 Lang/REXX/Hickerson-series-of-almost-integers create mode 120000 Lang/REXX/IBAN create mode 120000 Lang/REXX/Integer-overflow create mode 120000 Lang/REXX/Iterated-digits-squaring create mode 120000 Lang/REXX/Left-factorials create mode 120000 Lang/REXX/Ludic-numbers create mode 120000 Lang/REXX/Magic-squares-of-odd-order create mode 120000 Lang/REXX/Make-directory-path create mode 120000 Lang/REXX/Maximum-triangle-path-sum create mode 120000 Lang/REXX/Move-to-front-algorithm create mode 120000 Lang/REXX/Narcissistic-decimal-number create mode 120000 Lang/REXX/Nth create mode 120000 Lang/REXX/Odd-word-problem create mode 120000 Lang/REXX/Old-lady-swallowed-a-fly create mode 120000 Lang/REXX/Order-disjoint-list-items create mode 120000 Lang/REXX/Paraffins create mode 120000 Lang/REXX/Parse-an-IP-Address create mode 120000 Lang/REXX/Penneys-game create mode 120000 Lang/REXX/Permutations-Rank-of-a-permutation create mode 120000 Lang/REXX/Pernicious-numbers create mode 120000 Lang/REXX/Phrase-reversals create mode 120000 Lang/REXX/Quickselect-algorithm create mode 120000 Lang/REXX/Rep-string create mode 120000 Lang/REXX/Reverse-words-in-a-string create mode 120000 Lang/REXX/Runge-Kutta-method create mode 120000 Lang/REXX/Semiprime create mode 120000 Lang/REXX/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/REXX/Solve-a-Holy-Knights-tour create mode 120000 Lang/REXX/Solve-a-Hopido-puzzle create mode 120000 Lang/REXX/Solve-a-Numbrix-puzzle create mode 120000 Lang/REXX/Solve-the-no-connection-puzzle create mode 120000 Lang/REXX/Sparkline-in-unicode create mode 120000 Lang/REXX/State-name-puzzle create mode 120000 Lang/REXX/Statistics-Basic create mode 120000 Lang/REXX/Stern-Brocot-sequence create mode 120000 Lang/REXX/String-append create mode 120000 Lang/REXX/String-matching create mode 120000 Lang/REXX/String-prepend create mode 120000 Lang/REXX/Sum-multiples-of-3-and-5 create mode 120000 Lang/REXX/Textonyms create mode 120000 Lang/REXX/The-ISAAC-Cipher create mode 120000 Lang/REXX/The-Twelve-Days-of-Christmas create mode 120000 Lang/REXX/Total-circles-area create mode 120000 Lang/REXX/Ulam-spiral--for-primes- create mode 120000 Lang/REXX/Unix-ls create mode 120000 Lang/REXX/Zero-to-the-zero-power create mode 120000 Lang/REXX/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Racket/9-billion-names-of-God-the-integer create mode 120000 Lang/Racket/ABC-Problem create mode 120000 Lang/Racket/AKS-test-for-primes create mode 120000 Lang/Racket/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Racket/Aliquot-sequence-classifications create mode 120000 Lang/Racket/Almost-prime create mode 120000 Lang/Racket/Amb create mode 120000 Lang/Racket/Amicable-pairs create mode 120000 Lang/Racket/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Racket/Benfords-law create mode 120000 Lang/Racket/Bernoulli-numbers create mode 120000 Lang/Racket/Bitcoin-public-point-to-address create mode 120000 Lang/Racket/CSV-data-manipulation create mode 120000 Lang/Racket/Calendar---for-REAL-programmers create mode 120000 Lang/Racket/Casting-out-nines create mode 120000 Lang/Racket/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Racket/Catamorphism create mode 120000 Lang/Racket/Chinese-remainder-theorem create mode 120000 Lang/Racket/Circles-of-given-radius-through-two-points create mode 120000 Lang/Racket/Closures-Value-capture create mode 120000 Lang/Racket/Combinations-and-permutations create mode 120000 Lang/Racket/Comma-quibbling create mode 120000 Lang/Racket/Conjugate-transpose create mode 120000 Lang/Racket/Convert-decimal-number-to-rational create mode 120000 Lang/Racket/Currying create mode 120000 Lang/Racket/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Racket/Draw-a-clock create mode 120000 Lang/Racket/Extensible-prime-generator create mode 120000 Lang/Racket/Fibonacci-word create mode 120000 Lang/Racket/Fibonacci-word-fractal create mode 120000 Lang/Racket/File-input-output create mode 120000 Lang/Racket/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Racket/Flipping-bits-game create mode 120000 Lang/Racket/Fractran create mode 120000 Lang/Racket/Gaussian-elimination create mode 120000 Lang/Racket/Generate-Chess960-starting-position create mode 120000 Lang/Racket/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Racket/Hash-join create mode 120000 Lang/Racket/Heronian-triangles create mode 120000 Lang/Racket/Hickerson-series-of-almost-integers create mode 120000 Lang/Racket/IBAN create mode 120000 Lang/Racket/Iterated-digits-squaring create mode 120000 Lang/Racket/K-d-tree create mode 120000 Lang/Racket/Left-factorials create mode 120000 Lang/Racket/Longest-increasing-subsequence create mode 120000 Lang/Racket/Ludic-numbers create mode 120000 Lang/Racket/Magic-squares-of-odd-order create mode 120000 Lang/Racket/Make-directory-path create mode 120000 Lang/Racket/Maximum-triangle-path-sum create mode 120000 Lang/Racket/Move-to-front-algorithm create mode 120000 Lang/Racket/Munching-squares create mode 120000 Lang/Racket/Narcissistic-decimal-number create mode 120000 Lang/Racket/Natural-sorting create mode 120000 Lang/Racket/Nth create mode 120000 Lang/Racket/Odd-word-problem create mode 120000 Lang/Racket/Old-lady-swallowed-a-fly create mode 120000 Lang/Racket/Order-disjoint-list-items create mode 120000 Lang/Racket/Paraffins create mode 120000 Lang/Racket/Parse-an-IP-Address create mode 120000 Lang/Racket/Penneys-game create mode 120000 Lang/Racket/Percolation-Bond-percolation create mode 120000 Lang/Racket/Percolation-Mean-cluster-density create mode 120000 Lang/Racket/Percolation-Mean-run-density create mode 120000 Lang/Racket/Percolation-Site-percolation create mode 120000 Lang/Racket/Permutations-Rank-of-a-permutation create mode 120000 Lang/Racket/Pernicious-numbers create mode 120000 Lang/Racket/Phrase-reversals create mode 120000 Lang/Racket/Quickselect-algorithm create mode 120000 Lang/Racket/RSA-code create mode 120000 Lang/Racket/Ranking-methods create mode 120000 Lang/Racket/Rep-string create mode 120000 Lang/Racket/Reverse-words-in-a-string create mode 120000 Lang/Racket/Runge-Kutta-method create mode 120000 Lang/Racket/Semiprime create mode 120000 Lang/Racket/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Racket/Solve-a-Holy-Knights-tour create mode 120000 Lang/Racket/Solve-a-Hopido-puzzle create mode 120000 Lang/Racket/Solve-a-Numbrix-puzzle create mode 120000 Lang/Racket/Solve-the-no-connection-puzzle create mode 120000 Lang/Racket/Sparkline-in-unicode create mode 120000 Lang/Racket/State-name-puzzle create mode 120000 Lang/Racket/Statistics-Basic create mode 120000 Lang/Racket/Stern-Brocot-sequence create mode 120000 Lang/Racket/String-append create mode 120000 Lang/Racket/String-matching create mode 120000 Lang/Racket/String-prepend create mode 120000 Lang/Racket/Sum-multiples-of-3-and-5 create mode 120000 Lang/Racket/The-ISAAC-Cipher create mode 120000 Lang/Racket/The-Twelve-Days-of-Christmas create mode 120000 Lang/Racket/Ulam-spiral--for-primes- create mode 120000 Lang/Racket/Unix-ls create mode 120000 Lang/Racket/Vogels-approximation-method create mode 120000 Lang/Racket/World-Cup-group-stage create mode 120000 Lang/Racket/Zero-to-the-zero-power create mode 120000 Lang/Racket/Zhang-Suen-thinning-algorithm create mode 120000 Lang/RapidQ/ABC-Problem create mode 120000 Lang/RapidQ/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/RapidQ/File-input-output create mode 120000 Lang/Raven/File-input-output create mode 120000 Lang/Retro/File-input-output create mode 120000 Lang/Retro/String-matching create mode 120000 Lang/Ruby/9-billion-names-of-God-the-integer create mode 120000 Lang/Ruby/ABC-Problem create mode 120000 Lang/Ruby/AKS-test-for-primes create mode 120000 Lang/Ruby/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Ruby/Aliquot-sequence-classifications create mode 120000 Lang/Ruby/Almost-prime create mode 120000 Lang/Ruby/Amb create mode 120000 Lang/Ruby/Amicable-pairs create mode 120000 Lang/Ruby/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Ruby/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Ruby/Benfords-law create mode 120000 Lang/Ruby/Bernoulli-numbers create mode 120000 Lang/Ruby/Bitcoin-public-point-to-address create mode 120000 Lang/Ruby/CSV-data-manipulation create mode 120000 Lang/Ruby/Calendar---for-REAL-programmers create mode 120000 Lang/Ruby/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Ruby/Catamorphism create mode 120000 Lang/Ruby/Chinese-remainder-theorem create mode 120000 Lang/Ruby/Circles-of-given-radius-through-two-points create mode 120000 Lang/Ruby/Closures-Value-capture create mode 120000 Lang/Ruby/Combinations-and-permutations create mode 120000 Lang/Ruby/Comma-quibbling create mode 120000 Lang/Ruby/Conjugate-transpose create mode 120000 Lang/Ruby/Convert-decimal-number-to-rational create mode 120000 Lang/Ruby/Currying create mode 120000 Lang/Ruby/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Ruby/Draw-a-clock create mode 120000 Lang/Ruby/Extensible-prime-generator create mode 120000 Lang/Ruby/Fibonacci-word create mode 120000 Lang/Ruby/Fibonacci-word-fractal create mode 120000 Lang/Ruby/File-input-output create mode 120000 Lang/Ruby/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Ruby/Flipping-bits-game create mode 120000 Lang/Ruby/Fractran create mode 120000 Lang/Ruby/Gaussian-elimination create mode 120000 Lang/Ruby/Generate-Chess960-starting-position create mode 120000 Lang/Ruby/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Ruby/Hash-join create mode 120000 Lang/Ruby/Heronian-triangles create mode 120000 Lang/Ruby/Hickerson-series-of-almost-integers create mode 120000 Lang/Ruby/IBAN create mode 120000 Lang/Ruby/Integer-overflow create mode 120000 Lang/Ruby/Iterated-digits-squaring create mode 120000 Lang/Ruby/Left-factorials create mode 120000 Lang/Ruby/Longest-increasing-subsequence create mode 120000 Lang/Ruby/Ludic-numbers create mode 120000 Lang/Ruby/Magic-squares-of-odd-order create mode 120000 Lang/Ruby/Make-directory-path create mode 120000 Lang/Ruby/Maximum-triangle-path-sum create mode 120000 Lang/Ruby/Move-to-front-algorithm create mode 120000 Lang/Ruby/Munching-squares create mode 120000 Lang/Ruby/Narcissistic-decimal-number create mode 120000 Lang/Ruby/Natural-sorting create mode 120000 Lang/Ruby/Nth create mode 120000 Lang/Ruby/Odd-word-problem create mode 120000 Lang/Ruby/Old-lady-swallowed-a-fly create mode 120000 Lang/Ruby/Order-disjoint-list-items create mode 120000 Lang/Ruby/Paraffins create mode 120000 Lang/Ruby/Parse-an-IP-Address create mode 120000 Lang/Ruby/Penneys-game create mode 120000 Lang/Ruby/Permutations-Rank-of-a-permutation create mode 120000 Lang/Ruby/Pernicious-numbers create mode 120000 Lang/Ruby/Phrase-reversals create mode 120000 Lang/Ruby/Quickselect-algorithm create mode 120000 Lang/Ruby/Ranking-methods create mode 120000 Lang/Ruby/Rep-string create mode 120000 Lang/Ruby/Reverse-words-in-a-string create mode 120000 Lang/Ruby/Runge-Kutta-method create mode 120000 Lang/Ruby/Semiprime create mode 120000 Lang/Ruby/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Ruby/Solve-a-Holy-Knights-tour create mode 120000 Lang/Ruby/Solve-a-Hopido-puzzle create mode 120000 Lang/Ruby/Solve-a-Numbrix-puzzle create mode 120000 Lang/Ruby/Solve-the-no-connection-puzzle create mode 120000 Lang/Ruby/Sparkline-in-unicode create mode 120000 Lang/Ruby/State-name-puzzle create mode 120000 Lang/Ruby/Statistics-Basic create mode 120000 Lang/Ruby/Stern-Brocot-sequence create mode 120000 Lang/Ruby/String-append create mode 120000 Lang/Ruby/String-matching create mode 120000 Lang/Ruby/String-prepend create mode 120000 Lang/Ruby/Sum-multiples-of-3-and-5 create mode 120000 Lang/Ruby/Textonyms create mode 120000 Lang/Ruby/The-Twelve-Days-of-Christmas create mode 120000 Lang/Ruby/Total-circles-area create mode 120000 Lang/Ruby/Unix-ls create mode 120000 Lang/Ruby/Vogels-approximation-method create mode 120000 Lang/Ruby/World-Cup-group-stage create mode 120000 Lang/Ruby/Zero-to-the-zero-power create mode 120000 Lang/Ruby/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Run-BASIC/Benfords-law create mode 120000 Lang/Run-BASIC/CSV-data-manipulation create mode 120000 Lang/Run-BASIC/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Run-BASIC/Catamorphism create mode 120000 Lang/Run-BASIC/Comma-quibbling create mode 120000 Lang/Run-BASIC/Draw-a-clock create mode 120000 Lang/Run-BASIC/File-input-output create mode 120000 Lang/Run-BASIC/Munching-squares create mode 120000 Lang/Run-BASIC/Odd-word-problem create mode 120000 Lang/Run-BASIC/Runge-Kutta-method create mode 120000 Lang/Run-BASIC/String-matching create mode 120000 Lang/Run-BASIC/Sum-multiples-of-3-and-5 create mode 120000 Lang/Rust/ABC-Problem create mode 120000 Lang/Rust/AKS-test-for-primes create mode 120000 Lang/Rust/Almost-prime create mode 120000 Lang/Rust/Circles-of-given-radius-through-two-points create mode 120000 Lang/Rust/Closures-Value-capture create mode 120000 Lang/Rust/Comma-quibbling create mode 120000 Lang/Rust/Currying create mode 120000 Lang/Rust/File-input-output create mode 120000 Lang/Rust/Hello-world-Newbie create mode 120000 Lang/Rust/Magic-squares-of-odd-order create mode 120000 Lang/Rust/Nth create mode 120000 Lang/Rust/The-Twelve-Days-of-Christmas create mode 120000 Lang/Rust/Unix-ls create mode 120000 Lang/Rust/Zero-to-the-zero-power create mode 120000 Lang/SETL/Amb create mode 120000 Lang/SNOBOL4/File-input-output create mode 120000 Lang/SQL/Benfords-law create mode 120000 Lang/SQL/Hash-join create mode 120000 Lang/Scala/9-billion-names-of-God-the-integer create mode 120000 Lang/Scala/ABC-Problem create mode 120000 Lang/Scala/AKS-test-for-primes create mode 120000 Lang/Scala/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Scala/Aliquot-sequence-classifications create mode 120000 Lang/Scala/Almost-prime create mode 120000 Lang/Scala/Amb create mode 120000 Lang/Scala/Amicable-pairs create mode 120000 Lang/Scala/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Scala/Benfords-law create mode 120000 Lang/Scala/CSV-data-manipulation create mode 120000 Lang/Scala/Closures-Value-capture create mode 120000 Lang/Scala/Comma-quibbling create mode 120000 Lang/Scala/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Scala/Draw-a-clock create mode 120000 Lang/Scala/Fibonacci-word create mode 120000 Lang/Scala/Fibonacci-word-fractal create mode 120000 Lang/Scala/File-input-output create mode 120000 Lang/Scala/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Scala/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Scala/Hash-join create mode 120000 Lang/Scala/Hello-world-Newbie create mode 120000 Lang/Scala/IBAN create mode 120000 Lang/Scala/Integer-overflow create mode 120000 Lang/Scala/K-d-tree create mode 120000 Lang/Scala/Longest-increasing-subsequence create mode 120000 Lang/Scala/Make-directory-path create mode 120000 Lang/Scala/Maximum-triangle-path-sum create mode 120000 Lang/Scala/Munching-squares create mode 120000 Lang/Scala/Narcissistic-decimal-number create mode 120000 Lang/Scala/Natural-sorting create mode 120000 Lang/Scala/Nth create mode 120000 Lang/Scala/Odd-word-problem create mode 120000 Lang/Scala/Old-lady-swallowed-a-fly create mode 120000 Lang/Scala/Order-disjoint-list-items create mode 120000 Lang/Scala/Pernicious-numbers create mode 120000 Lang/Scala/Quickselect-algorithm create mode 120000 Lang/Scala/Ranking-methods create mode 120000 Lang/Scala/Rep-string create mode 120000 Lang/Scala/Reverse-words-in-a-string create mode 120000 Lang/Scala/Semiprime create mode 120000 Lang/Scala/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Scala/Sparkline-in-unicode create mode 120000 Lang/Scala/State-name-puzzle create mode 120000 Lang/Scala/Statistics-Basic create mode 120000 Lang/Scala/String-append create mode 120000 Lang/Scala/String-matching create mode 120000 Lang/Scala/String-prepend create mode 120000 Lang/Scala/Sum-multiples-of-3-and-5 create mode 120000 Lang/Scala/Zero-to-the-zero-power create mode 120000 Lang/Scheme/Amb create mode 120000 Lang/Scheme/Closures-Value-capture create mode 120000 Lang/Scheme/File-input-output create mode 120000 Lang/Scheme/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Scheme/Hash-join create mode 120000 Lang/Scheme/Longest-increasing-subsequence create mode 120000 Lang/Scheme/Odd-word-problem create mode 120000 Lang/Scheme/Reverse-words-in-a-string create mode 120000 Lang/Scheme/Sum-multiples-of-3-and-5 create mode 120000 Lang/Scheme/Zero-to-the-zero-power create mode 120000 Lang/Scilab/AKS-test-for-primes create mode 120000 Lang/Scilab/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Seed7/ABC-Problem create mode 120000 Lang/Seed7/AKS-test-for-primes create mode 120000 Lang/Seed7/Amb create mode 120000 Lang/Seed7/CSV-data-manipulation create mode 120000 Lang/Seed7/Calendar---for-REAL-programmers create mode 120000 Lang/Seed7/Casting-out-nines create mode 120000 Lang/Seed7/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Seed7/Chinese-remainder-theorem create mode 120000 Lang/Seed7/Circles-of-given-radius-through-two-points create mode 120000 Lang/Seed7/Comma-quibbling create mode 120000 Lang/Seed7/Convert-decimal-number-to-rational create mode 120000 Lang/Seed7/Draw-a-clock create mode 120000 Lang/Seed7/Extensible-prime-generator create mode 120000 Lang/Seed7/Fibonacci-word create mode 120000 Lang/Seed7/File-input-output create mode 120000 Lang/Seed7/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Seed7/Fractran create mode 120000 Lang/Seed7/Generate-Chess960-starting-position create mode 120000 Lang/Seed7/Hickerson-series-of-almost-integers create mode 120000 Lang/Seed7/IBAN create mode 120000 Lang/Seed7/Integer-overflow create mode 120000 Lang/Seed7/Left-factorials create mode 120000 Lang/Seed7/Ludic-numbers create mode 120000 Lang/Seed7/Magic-squares-of-odd-order create mode 120000 Lang/Seed7/Nth create mode 120000 Lang/Seed7/Odd-word-problem create mode 120000 Lang/Seed7/Old-lady-swallowed-a-fly create mode 120000 Lang/Seed7/Paraffins create mode 120000 Lang/Seed7/RSA-code create mode 120000 Lang/Seed7/Rep-string create mode 120000 Lang/Seed7/Reverse-words-in-a-string create mode 120000 Lang/Seed7/Semiprime create mode 120000 Lang/Seed7/Sparkline-in-unicode create mode 120000 Lang/Seed7/String-append create mode 120000 Lang/Seed7/String-matching create mode 120000 Lang/Seed7/String-prepend create mode 120000 Lang/Seed7/Sum-multiples-of-3-and-5 create mode 120000 Lang/Seed7/The-Twelve-Days-of-Christmas create mode 120000 Lang/Seed7/Zero-to-the-zero-power create mode 120000 Lang/Slate/File-input-output create mode 120000 Lang/Smalltalk/ABC-Problem create mode 120000 Lang/Smalltalk/Closures-Value-capture create mode 120000 Lang/Smalltalk/File-input-output create mode 120000 Lang/Smalltalk/Reverse-words-in-a-string create mode 120000 Lang/Smalltalk/String-matching create mode 120000 Lang/Smalltalk/Zero-to-the-zero-power create mode 120000 Lang/Standard-ML/Catamorphism create mode 120000 Lang/Standard-ML/Comma-quibbling create mode 120000 Lang/Standard-ML/Currying create mode 120000 Lang/Standard-ML/File-input-output create mode 120000 Lang/Standard-ML/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Standard-ML/Longest-increasing-subsequence create mode 120000 Lang/Standard-ML/Quickselect-algorithm create mode 120000 Lang/Standard-ML/Runge-Kutta-method create mode 120000 Lang/Standard-ML/String-matching create mode 120000 Lang/TI-83-BASIC/Catalan-numbers-Pascals-triangle create mode 120000 Lang/TI-83-BASIC/Hello-world-Newbie create mode 120000 Lang/TI-83-BASIC/Munching-squares create mode 120000 Lang/TUSCRIPT/ABC-Problem create mode 120000 Lang/TUSCRIPT/Amb create mode 120000 Lang/TUSCRIPT/CSV-data-manipulation create mode 120000 Lang/TUSCRIPT/Odd-word-problem create mode 120000 Lang/TUSCRIPT/String-matching create mode 120000 Lang/TXR/ABC-Problem create mode 120000 Lang/TXR/Amb create mode 120000 Lang/TXR/Hash-join create mode 120000 Lang/TXR/Old-lady-swallowed-a-fly create mode 120000 Lang/TXR/String-matching create mode 120000 Lang/Tcl/9-billion-names-of-God-the-integer create mode 120000 Lang/Tcl/ABC-Problem create mode 120000 Lang/Tcl/AKS-test-for-primes create mode 120000 Lang/Tcl/Almost-prime create mode 120000 Lang/Tcl/Amb create mode 120000 Lang/Tcl/Amicable-pairs create mode 120000 Lang/Tcl/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Tcl/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Tcl/Benfords-law create mode 120000 Lang/Tcl/Bernoulli-numbers create mode 120000 Lang/Tcl/Bitcoin-public-point-to-address create mode 120000 Lang/Tcl/CSV-data-manipulation create mode 120000 Lang/Tcl/Calendar---for-REAL-programmers create mode 120000 Lang/Tcl/Casting-out-nines create mode 120000 Lang/Tcl/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Tcl/Catamorphism create mode 120000 Lang/Tcl/Chinese-remainder-theorem create mode 120000 Lang/Tcl/Circles-of-given-radius-through-two-points create mode 120000 Lang/Tcl/Closures-Value-capture create mode 120000 Lang/Tcl/Combinations-and-permutations create mode 120000 Lang/Tcl/Comma-quibbling create mode 120000 Lang/Tcl/Conjugate-transpose create mode 120000 Lang/Tcl/Convert-decimal-number-to-rational create mode 120000 Lang/Tcl/Currying create mode 120000 Lang/Tcl/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Tcl/Draw-a-clock create mode 120000 Lang/Tcl/Extensible-prime-generator create mode 120000 Lang/Tcl/Fibonacci-word create mode 120000 Lang/Tcl/Fibonacci-word-fractal create mode 120000 Lang/Tcl/File-input-output create mode 120000 Lang/Tcl/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Tcl/Flipping-bits-game create mode 120000 Lang/Tcl/Fractran create mode 120000 Lang/Tcl/Gaussian-elimination create mode 120000 Lang/Tcl/Generate-Chess960-starting-position create mode 120000 Lang/Tcl/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Tcl/Hash-join create mode 120000 Lang/Tcl/Hello-world-Newbie create mode 120000 Lang/Tcl/Hickerson-series-of-almost-integers create mode 120000 Lang/Tcl/IBAN create mode 120000 Lang/Tcl/Integer-overflow create mode 120000 Lang/Tcl/Iterated-digits-squaring create mode 120000 Lang/Tcl/K-d-tree create mode 120000 Lang/Tcl/Left-factorials create mode 120000 Lang/Tcl/Longest-increasing-subsequence create mode 120000 Lang/Tcl/Ludic-numbers create mode 120000 Lang/Tcl/Machine-code create mode 120000 Lang/Tcl/Magic-squares-of-odd-order create mode 120000 Lang/Tcl/Make-directory-path create mode 120000 Lang/Tcl/Maximum-triangle-path-sum create mode 120000 Lang/Tcl/Move-to-front-algorithm create mode 120000 Lang/Tcl/Munching-squares create mode 120000 Lang/Tcl/Narcissistic-decimal-number create mode 120000 Lang/Tcl/Natural-sorting create mode 120000 Lang/Tcl/Nth create mode 120000 Lang/Tcl/Odd-word-problem create mode 120000 Lang/Tcl/Old-lady-swallowed-a-fly create mode 120000 Lang/Tcl/Order-disjoint-list-items create mode 120000 Lang/Tcl/Paraffins create mode 120000 Lang/Tcl/Parse-an-IP-Address create mode 120000 Lang/Tcl/Penneys-game create mode 120000 Lang/Tcl/Percolation-Bond-percolation create mode 120000 Lang/Tcl/Percolation-Mean-cluster-density create mode 120000 Lang/Tcl/Percolation-Mean-run-density create mode 120000 Lang/Tcl/Percolation-Site-percolation create mode 120000 Lang/Tcl/Permutations-Rank-of-a-permutation create mode 120000 Lang/Tcl/Pernicious-numbers create mode 120000 Lang/Tcl/Phrase-reversals create mode 120000 Lang/Tcl/Quickselect-algorithm create mode 120000 Lang/Tcl/RSA-code create mode 120000 Lang/Tcl/Ranking-methods create mode 120000 Lang/Tcl/Rep-string create mode 120000 Lang/Tcl/Reverse-words-in-a-string create mode 120000 Lang/Tcl/Runge-Kutta-method create mode 120000 Lang/Tcl/Semiprime create mode 120000 Lang/Tcl/Sequence-of-primes-by-Trial-Division create mode 120000 Lang/Tcl/Solve-a-Holy-Knights-tour create mode 120000 Lang/Tcl/Solve-a-Hopido-puzzle create mode 120000 Lang/Tcl/Solve-the-no-connection-puzzle create mode 120000 Lang/Tcl/Sparkline-in-unicode create mode 120000 Lang/Tcl/State-name-puzzle create mode 120000 Lang/Tcl/Statistics-Basic create mode 120000 Lang/Tcl/String-append create mode 120000 Lang/Tcl/String-matching create mode 120000 Lang/Tcl/String-prepend create mode 120000 Lang/Tcl/Sum-multiples-of-3-and-5 create mode 120000 Lang/Tcl/The-ISAAC-Cipher create mode 120000 Lang/Tcl/The-Twelve-Days-of-Christmas create mode 120000 Lang/Tcl/Total-circles-area create mode 120000 Lang/Tcl/Unix-ls create mode 120000 Lang/Tcl/Vogels-approximation-method create mode 120000 Lang/Tcl/World-Cup-group-stage create mode 120000 Lang/Tcl/Zero-to-the-zero-power create mode 120000 Lang/Tcl/Zhang-Suen-thinning-algorithm create mode 120000 Lang/Toka/File-input-output create mode 120000 Lang/UNIX-Shell/ABC-Problem create mode 120000 Lang/UNIX-Shell/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/UNIX-Shell/CSV-data-manipulation create mode 120000 Lang/UNIX-Shell/Comma-quibbling create mode 120000 Lang/UNIX-Shell/File-input-output create mode 120000 Lang/UNIX-Shell/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/UNIX-Shell/IBAN create mode 120000 Lang/UNIX-Shell/Make-directory-path create mode 120000 Lang/UNIX-Shell/Narcissistic-decimal-number create mode 120000 Lang/UNIX-Shell/Penneys-game create mode 120000 Lang/UNIX-Shell/Phrase-reversals create mode 120000 Lang/UNIX-Shell/Rep-string create mode 120000 Lang/UNIX-Shell/Reverse-words-in-a-string create mode 120000 Lang/Ursala/File-input-output create mode 120000 Lang/VBA/String-append create mode 120000 Lang/VBA/String-prepend create mode 120000 Lang/VBScript/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/VBScript/Amb create mode 120000 Lang/VBScript/Amicable-pairs create mode 120000 Lang/VBScript/Catalan-numbers-Pascals-triangle create mode 120000 Lang/VBScript/File-input-output create mode 120000 Lang/VBScript/Find-the-last-Sunday-of-each-month create mode 120000 Lang/VBScript/Stern-Brocot-sequence create mode 120000 Lang/VBScript/Textonyms create mode 120000 Lang/Vedit-macro-language/CSV-data-manipulation create mode 120000 Lang/Vedit-macro-language/Calendar---for-REAL-programmers create mode 120000 Lang/Vedit-macro-language/File-input-output create mode 120000 Lang/Vim-Script/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Visual-Basic-.NET/File-input-output create mode 120000 Lang/Visual-Basic/Catalan-numbers-Pascals-triangle create mode 120000 Lang/X86-Assembly/Calendar---for-REAL-programmers create mode 120000 Lang/XPL0/Circles-of-given-radius-through-two-points create mode 120000 Lang/XPL0/Comma-quibbling create mode 120000 Lang/XPL0/File-input-output create mode 120000 Lang/XPL0/Munching-squares create mode 120000 Lang/XPL0/Solve-the-no-connection-puzzle create mode 120000 Lang/XPL0/String-matching create mode 120000 Lang/XPL0/Sum-multiples-of-3-and-5 create mode 120000 Lang/ZX-Spectrum-Basic/Hello-world-Newbie create mode 100644 Task/9-billion-names-of-God-the-integer/00DESCRIPTION create mode 100644 Task/9-billion-names-of-God-the-integer/AutoHotkey/9-billion-names-of-god-the-integer.ahk create mode 100644 Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-1.cpp create mode 100644 Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-2.cpp create mode 100644 Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-3.cpp create mode 100644 Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-4.cpp create mode 100644 Task/9-billion-names-of-God-the-integer/C/9-billion-names-of-god-the-integer.c create mode 100644 Task/9-billion-names-of-God-the-integer/Common-Lisp/9-billion-names-of-god-the-integer.lisp create mode 100644 Task/9-billion-names-of-God-the-integer/D/9-billion-names-of-god-the-integer-1.d create mode 100644 Task/9-billion-names-of-God-the-integer/D/9-billion-names-of-god-the-integer-2.d create mode 100644 Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl create mode 100644 Task/9-billion-names-of-God-the-integer/Frink/9-billion-names-of-god-the-integer.frink create mode 100644 Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-1.hs create mode 100644 Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-2.hs create mode 100644 Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-1.j create mode 100644 Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-2.j create mode 100644 Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-3.j create mode 100644 Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-4.j create mode 100644 Task/9-billion-names-of-God-the-integer/JavaScript/9-billion-names-of-god-the-integer.js create mode 100644 Task/9-billion-names-of-God-the-integer/Mathematica/9-billion-names-of-god-the-integer-1.math create mode 100644 Task/9-billion-names-of-God-the-integer/Mathematica/9-billion-names-of-god-the-integer-2.math create mode 100644 Task/9-billion-names-of-God-the-integer/Mathematica/9-billion-names-of-god-the-integer-3.math create mode 100644 Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml create mode 100644 Task/9-billion-names-of-God-the-integer/Perl-6/9-billion-names-of-god-the-integer.pl6 create mode 100644 Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-1.pl create mode 100644 Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-2.pl create mode 100644 Task/9-billion-names-of-God-the-integer/PicoLisp/9-billion-names-of-god-the-integer.l create mode 100644 Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-1.py create mode 100644 Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-2.py create mode 100644 Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-3.py create mode 100644 Task/9-billion-names-of-God-the-integer/README create mode 100644 Task/9-billion-names-of-God-the-integer/REXX/9-billion-names-of-god-the-integer.rexx create mode 100644 Task/9-billion-names-of-God-the-integer/Racket/9-billion-names-of-god-the-integer.rkt create mode 100644 Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-1.rb create mode 100644 Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-2.rb create mode 100644 Task/9-billion-names-of-God-the-integer/Scala/9-billion-names-of-god-the-integer-1.scala create mode 100644 Task/9-billion-names-of-God-the-integer/Scala/9-billion-names-of-god-the-integer-2.scala create mode 100644 Task/9-billion-names-of-God-the-integer/Tcl/9-billion-names-of-god-the-integer.tcl create mode 100644 Task/ABC-Problem/00DESCRIPTION create mode 100644 Task/ABC-Problem/Ada/abc-problem.ada create mode 100644 Task/ABC-Problem/AutoHotkey/abc-problem-1.ahk create mode 100644 Task/ABC-Problem/AutoHotkey/abc-problem-2.ahk create mode 100644 Task/ABC-Problem/BBC-BASIC/abc-problem.bbc create mode 100644 Task/ABC-Problem/Batch-File/abc-problem.bat create mode 100644 Task/ABC-Problem/Bracmat/abc-problem.bracmat create mode 100644 Task/ABC-Problem/C++/abc-problem.cpp create mode 100644 Task/ABC-Problem/C-sharp/abc-problem.cs create mode 100644 Task/ABC-Problem/C/abc-problem.c create mode 100644 Task/ABC-Problem/Clojure/abc-problem.clj create mode 100644 Task/ABC-Problem/CoffeeScript/abc-problem.coffee create mode 100644 Task/ABC-Problem/Common-Lisp/abc-problem.lisp create mode 100644 Task/ABC-Problem/D/abc-problem-1.d create mode 100644 Task/ABC-Problem/D/abc-problem-2.d create mode 100644 Task/ABC-Problem/D/abc-problem-3.d create mode 100644 Task/ABC-Problem/D/abc-problem-4.d create mode 100644 Task/ABC-Problem/Delphi/abc-problem.delphi create mode 100644 Task/ABC-Problem/Erlang/abc-problem.erl create mode 100644 Task/ABC-Problem/Euphoria/abc-problem.euphoria create mode 100644 Task/ABC-Problem/FBSL/abc-problem.fbsl create mode 100644 Task/ABC-Problem/Fortran/abc-problem.f create mode 100644 Task/ABC-Problem/Go/abc-problem.go create mode 100644 Task/ABC-Problem/Groovy/abc-problem-1.groovy create mode 100644 Task/ABC-Problem/Groovy/abc-problem-2.groovy create mode 100644 Task/ABC-Problem/Haskell/abc-problem.hs create mode 100644 Task/ABC-Problem/Icon/abc-problem.icon create mode 100644 Task/ABC-Problem/J/abc-problem-1.j create mode 100644 Task/ABC-Problem/J/abc-problem-2.j create mode 100644 Task/ABC-Problem/J/abc-problem-3.j create mode 100644 Task/ABC-Problem/J/abc-problem-4.j create mode 100644 Task/ABC-Problem/J/abc-problem-5.j create mode 100644 Task/ABC-Problem/Java/abc-problem.java create mode 100644 Task/ABC-Problem/JavaScript/abc-problem.js create mode 100644 Task/ABC-Problem/Julia/abc-problem.julia create mode 100644 Task/ABC-Problem/Logo/abc-problem.logo create mode 100644 Task/ABC-Problem/MATLAB/abc-problem.m create mode 100644 Task/ABC-Problem/MAXScript/abc-problem-1.max create mode 100644 Task/ABC-Problem/MAXScript/abc-problem-2.max create mode 100644 Task/ABC-Problem/MAXScript/abc-problem-3.max create mode 100644 Task/ABC-Problem/MAXScript/abc-problem-4.max create mode 100644 Task/ABC-Problem/Mathematica/abc-problem.math create mode 100644 Task/ABC-Problem/OCaml/abc-problem.ocaml create mode 100644 Task/ABC-Problem/Oberon-2/abc-problem.oberon-2 create mode 100644 Task/ABC-Problem/PHP/abc-problem.php create mode 100644 Task/ABC-Problem/PL-I/abc-problem-1.pli create mode 100644 Task/ABC-Problem/PL-I/abc-problem-2.pli create mode 100644 Task/ABC-Problem/Perl-6/abc-problem.pl6 create mode 100644 Task/ABC-Problem/Perl/abc-problem-1.pl create mode 100644 Task/ABC-Problem/Perl/abc-problem-2.pl create mode 100644 Task/ABC-Problem/PicoLisp/abc-problem.l create mode 100644 Task/ABC-Problem/PowerBASIC/abc-problem.powerbasic create mode 100644 Task/ABC-Problem/Prolog/abc-problem.pro create mode 100644 Task/ABC-Problem/Python/abc-problem-1.py create mode 100644 Task/ABC-Problem/Python/abc-problem-2.py create mode 100644 Task/ABC-Problem/Python/abc-problem-3.py create mode 100644 Task/ABC-Problem/R/abc-problem-1.r create mode 100644 Task/ABC-Problem/R/abc-problem-2.r create mode 100644 Task/ABC-Problem/README create mode 100644 Task/ABC-Problem/REXX/abc-problem-1.rexx create mode 100644 Task/ABC-Problem/REXX/abc-problem-2.rexx create mode 100644 Task/ABC-Problem/Racket/abc-problem.rkt create mode 100644 Task/ABC-Problem/RapidQ/abc-problem.rapidq create mode 100644 Task/ABC-Problem/Ruby/abc-problem.rb create mode 100644 Task/ABC-Problem/Rust/abc-problem.rust create mode 100644 Task/ABC-Problem/Scala/abc-problem.scala create mode 100644 Task/ABC-Problem/Seed7/abc-problem.seed7 create mode 100644 Task/ABC-Problem/Smalltalk/abc-problem.st create mode 100644 Task/ABC-Problem/TUSCRIPT/abc-problem.tu create mode 100644 Task/ABC-Problem/TXR/abc-problem.txr create mode 100644 Task/ABC-Problem/Tcl/abc-problem.tcl create mode 100644 Task/ABC-Problem/UNIX-Shell/abc-problem.sh create mode 100644 Task/AKS-test-for-primes/00DESCRIPTION create mode 100644 Task/AKS-test-for-primes/00META.yaml create mode 100644 Task/AKS-test-for-primes/AutoHotkey/aks-test-for-primes.ahk create mode 100644 Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-1.bracmat create mode 100644 Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-2.bracmat create mode 100644 Task/AKS-test-for-primes/C/aks-test-for-primes.c create mode 100644 Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj create mode 100644 Task/AKS-test-for-primes/CoffeeScript/aks-test-for-primes.coffee create mode 100644 Task/AKS-test-for-primes/Common-Lisp/aks-test-for-primes.lisp create mode 100644 Task/AKS-test-for-primes/D/aks-test-for-primes.d create mode 100644 Task/AKS-test-for-primes/Erlang/aks-test-for-primes.erl create mode 100644 Task/AKS-test-for-primes/Go/aks-test-for-primes.go create mode 100644 Task/AKS-test-for-primes/Haskell/aks-test-for-primes.hs create mode 100644 Task/AKS-test-for-primes/J/aks-test-for-primes-1.j create mode 100644 Task/AKS-test-for-primes/J/aks-test-for-primes-2.j create mode 100644 Task/AKS-test-for-primes/JavaScript/aks-test-for-primes.js create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-1.maple create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-2.maple create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-3.maple create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-4.maple create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-5.maple create mode 100644 Task/AKS-test-for-primes/Maple/aks-test-for-primes-6.maple create mode 100644 Task/AKS-test-for-primes/Mathematica/aks-test-for-primes.math create mode 100644 Task/AKS-test-for-primes/PARI-GP/aks-test-for-primes.pari create mode 100644 Task/AKS-test-for-primes/Pascal/aks-test-for-primes.pascal create mode 100644 Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-1.pl6 create mode 100644 Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-2.pl6 create mode 100644 Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-3.pl6 create mode 100644 Task/AKS-test-for-primes/Perl/aks-test-for-primes.pl create mode 100644 Task/AKS-test-for-primes/PicoLisp/aks-test-for-primes.l create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-1.pro create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-2.pro create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-3.pro create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-4.pro create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-5.pro create mode 100644 Task/AKS-test-for-primes/Prolog/aks-test-for-primes-6.pro create mode 100644 Task/AKS-test-for-primes/Python/aks-test-for-primes-1.py create mode 100644 Task/AKS-test-for-primes/Python/aks-test-for-primes-2.py create mode 100644 Task/AKS-test-for-primes/README create mode 100644 Task/AKS-test-for-primes/REXX/aks-test-for-primes-1.rexx create mode 100644 Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx create mode 100644 Task/AKS-test-for-primes/Racket/aks-test-for-primes.rkt create mode 100644 Task/AKS-test-for-primes/Ruby/aks-test-for-primes-1.rb create mode 100644 Task/AKS-test-for-primes/Ruby/aks-test-for-primes-2.rb create mode 100644 Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust create mode 100644 Task/AKS-test-for-primes/Rust/aks-test-for-primes-2.rust create mode 100644 Task/AKS-test-for-primes/Scala/aks-test-for-primes.scala create mode 100644 Task/AKS-test-for-primes/Scilab/aks-test-for-primes.scilab create mode 100644 Task/AKS-test-for-primes/Seed7/aks-test-for-primes.seed7 create mode 100644 Task/AKS-test-for-primes/Tcl/aks-test-for-primes.tcl create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/AutoHotkey/abundant,-deficient-and-perfect-number-classifications.ahk create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/D/abundant,-deficient-and-perfect-number-classifications.d create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-1.j create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-2.j create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-3.j create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-4.j create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-5.j create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Mathematica/abundant,-deficient-and-perfect-number-classifications.math create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/PL-I/abundant,-deficient-and-perfect-number-classifications.pli create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Pascal/abundant,-deficient-and-perfect-number-classifications.pascal create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Perl-6/abundant,-deficient-and-perfect-number-classifications.pl6 create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-1.pl create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-2.pl create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/README create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Racket/abundant,-deficient-and-perfect-number-classifications.rkt create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Ruby/abundant,-deficient-and-perfect-number-classifications.rb create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Scala/abundant,-deficient-and-perfect-number-classifications.scala create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/VBScript/abundant,-deficient-and-perfect-number-classifications.vb create mode 100644 Task/Aliquot-sequence-classifications/00DESCRIPTION create mode 100644 Task/Aliquot-sequence-classifications/D/aliquot-sequence-classifications.d create mode 100644 Task/Aliquot-sequence-classifications/Haskell/aliquot-sequence-classifications.hs create mode 100644 Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-1.j create mode 100644 Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-2.j create mode 100644 Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 create mode 100644 Task/Aliquot-sequence-classifications/Perl/aliquot-sequence-classifications.pl create mode 100644 Task/Aliquot-sequence-classifications/Python/aliquot-sequence-classifications.py create mode 100644 Task/Aliquot-sequence-classifications/README create mode 100644 Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx create mode 100644 Task/Aliquot-sequence-classifications/Racket/aliquot-sequence-classifications.rkt create mode 100644 Task/Aliquot-sequence-classifications/Ruby/aliquot-sequence-classifications.rb create mode 100644 Task/Aliquot-sequence-classifications/Scala/aliquot-sequence-classifications.scala create mode 100644 Task/Almost-prime/00DESCRIPTION create mode 100644 Task/Almost-prime/00META.yaml create mode 100644 Task/Almost-prime/Ada/almost-prime.ada create mode 100644 Task/Almost-prime/AutoHotkey/almost-prime.ahk create mode 100644 Task/Almost-prime/C-sharp/almost-prime.cs create mode 100644 Task/Almost-prime/C/almost-prime.c create mode 100644 Task/Almost-prime/Common-Lisp/almost-prime.lisp create mode 100644 Task/Almost-prime/D/almost-prime.d create mode 100644 Task/Almost-prime/Go/almost-prime.go create mode 100644 Task/Almost-prime/Haskell/almost-prime.hs create mode 100644 Task/Almost-prime/Icon/almost-prime.icon create mode 100644 Task/Almost-prime/J/almost-prime.j create mode 100644 Task/Almost-prime/Julia/almost-prime.julia create mode 100644 Task/Almost-prime/Mathematica/almost-prime.math create mode 100644 Task/Almost-prime/Objeck/almost-prime.objeck create mode 100644 Task/Almost-prime/PARI-GP/almost-prime.pari create mode 100644 Task/Almost-prime/Pascal/almost-prime.pascal create mode 100644 Task/Almost-prime/Perl-6/almost-prime-1.pl6 create mode 100644 Task/Almost-prime/Perl-6/almost-prime-2.pl6 create mode 100644 Task/Almost-prime/Perl/almost-prime-1.pl create mode 100644 Task/Almost-prime/Perl/almost-prime-2.pl create mode 100644 Task/Almost-prime/PicoLisp/almost-prime.l create mode 100644 Task/Almost-prime/Prolog/almost-prime-1.pro create mode 100644 Task/Almost-prime/Prolog/almost-prime-2.pro create mode 100644 Task/Almost-prime/Prolog/almost-prime-3.pro create mode 100644 Task/Almost-prime/Python/almost-prime.py create mode 100644 Task/Almost-prime/README create mode 100644 Task/Almost-prime/REXX/almost-prime-1.rexx create mode 100644 Task/Almost-prime/REXX/almost-prime-2.rexx create mode 100644 Task/Almost-prime/Racket/almost-prime.rkt create mode 100644 Task/Almost-prime/Ruby/almost-prime-1.rb create mode 100644 Task/Almost-prime/Ruby/almost-prime-2.rb create mode 100644 Task/Almost-prime/Rust/almost-prime.rust create mode 100644 Task/Almost-prime/Scala/almost-prime.scala create mode 100644 Task/Almost-prime/Tcl/almost-prime.tcl create mode 100644 Task/Amb/00DESCRIPTION create mode 100644 Task/Amb/ALGOL-68/amb.alg create mode 100644 Task/Amb/Ada/amb.ada create mode 100644 Task/Amb/AutoHotkey/amb.ahk create mode 100644 Task/Amb/Bracmat/amb.bracmat create mode 100644 Task/Amb/C-sharp/amb-1.cs create mode 100644 Task/Amb/C-sharp/amb-2.cs create mode 100644 Task/Amb/C/amb.c create mode 100644 Task/Amb/Clojure/amb.clj create mode 100644 Task/Amb/Common-Lisp/amb-1.lisp create mode 100644 Task/Amb/Common-Lisp/amb-2.lisp create mode 100644 Task/Amb/D/amb.d create mode 100644 Task/Amb/E/amb-1.e create mode 100644 Task/Amb/E/amb-2.e create mode 100644 Task/Amb/Ela/amb-1.ela create mode 100644 Task/Amb/Ela/amb-2.ela create mode 100644 Task/Amb/Elena/amb.elena create mode 100644 Task/Amb/Factor/amb.factor create mode 100644 Task/Amb/Go/amb-1.go create mode 100644 Task/Amb/Go/amb-2.go create mode 100644 Task/Amb/Haskell/amb.hs create mode 100644 Task/Amb/Haxe/amb.haxe create mode 100644 Task/Amb/Icon/amb.icon create mode 100644 Task/Amb/J/amb-1.j create mode 100644 Task/Amb/J/amb-2.j create mode 100644 Task/Amb/J/amb-3.j create mode 100644 Task/Amb/JavaScript/amb.js create mode 100644 Task/Amb/Lua/amb-1.lua create mode 100644 Task/Amb/Lua/amb-2.lua create mode 100644 Task/Amb/Mathematica/amb-1.math create mode 100644 Task/Amb/Mathematica/amb-2.math create mode 100644 Task/Amb/Mathematica/amb-3.math create mode 100644 Task/Amb/Mercury/amb-1.mercury create mode 100644 Task/Amb/Mercury/amb-2.mercury create mode 100644 Task/Amb/NetRexx/amb.netrexx create mode 100644 Task/Amb/OCaml/amb-1.ocaml create mode 100644 Task/Amb/OCaml/amb-2.ocaml create mode 100644 Task/Amb/OpenEdge-Progress/amb.openedge create mode 100644 Task/Amb/Oz/amb.oz create mode 100644 Task/Amb/PARI-GP/amb.pari create mode 100644 Task/Amb/PL-I/amb.pli create mode 100644 Task/Amb/Perl-6/amb-1.pl6 create mode 100644 Task/Amb/Perl-6/amb-2.pl6 create mode 100644 Task/Amb/Perl/amb-1.pl create mode 100644 Task/Amb/Perl/amb-2.pl create mode 100644 Task/Amb/PicoLisp/amb.l create mode 100644 Task/Amb/Prolog/amb.pro create mode 100644 Task/Amb/PureBasic/amb.purebasic create mode 100644 Task/Amb/Python/amb.py create mode 100644 Task/Amb/R/amb-1.r create mode 100644 Task/Amb/R/amb-2.r create mode 100644 Task/Amb/README create mode 100644 Task/Amb/REXX/amb-1.rexx create mode 100644 Task/Amb/REXX/amb-2.rexx create mode 100644 Task/Amb/Racket/amb.rkt create mode 100644 Task/Amb/Ruby/amb.rb create mode 100644 Task/Amb/SETL/amb-1.setl create mode 100644 Task/Amb/SETL/amb-2.setl create mode 100644 Task/Amb/Scala/amb.scala create mode 100644 Task/Amb/Scheme/amb.ss create mode 100644 Task/Amb/Seed7/amb.seed7 create mode 100644 Task/Amb/TUSCRIPT/amb.tu create mode 100644 Task/Amb/TXR/amb-1.txr create mode 100644 Task/Amb/TXR/amb-2.txr create mode 100644 Task/Amb/Tcl/amb-1.tcl create mode 100644 Task/Amb/Tcl/amb-2.tcl create mode 100644 Task/Amb/VBScript/amb-1.vb create mode 100644 Task/Amb/VBScript/amb-2.vb create mode 100644 Task/Amicable-pairs/00DESCRIPTION create mode 100644 Task/Amicable-pairs/AutoHotkey/amicable-pairs.ahk create mode 100644 Task/Amicable-pairs/C/amicable-pairs.c create mode 100644 Task/Amicable-pairs/D/amicable-pairs.d create mode 100644 Task/Amicable-pairs/Haskell/amicable-pairs.hs create mode 100644 Task/Amicable-pairs/J/amicable-pairs-1.j create mode 100644 Task/Amicable-pairs/J/amicable-pairs-2.j create mode 100644 Task/Amicable-pairs/Mathematica/amicable-pairs.math create mode 100644 Task/Amicable-pairs/PARI-GP/amicable-pairs.pari create mode 100644 Task/Amicable-pairs/PL-I/amicable-pairs.pli create mode 100644 Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal create mode 100644 Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal create mode 100644 Task/Amicable-pairs/Perl-6/amicable-pairs.pl6 create mode 100644 Task/Amicable-pairs/Perl/amicable-pairs.pl create mode 100644 Task/Amicable-pairs/Python/amicable-pairs.py create mode 100644 Task/Amicable-pairs/README create mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-1.rexx create mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-2.rexx create mode 100644 Task/Amicable-pairs/Racket/amicable-pairs.rkt create mode 100644 Task/Amicable-pairs/Ruby/amicable-pairs.rb create mode 100644 Task/Amicable-pairs/Scala/amicable-pairs.scala create mode 100644 Task/Amicable-pairs/Tcl/amicable-pairs.tcl create mode 100644 Task/Amicable-pairs/VBScript/amicable-pairs.vb create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/00DESCRIPTION rename Task/{File-IO => Append-a-record-to-the-end-of-a-text-file}/00META.yaml (100%) create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/C/append-a-record-to-the-end-of-a-text-file.c create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Go/append-a-record-to-the-end-of-a-text-file.go create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-1.groovy create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-2.groovy create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-1.hs create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-2.hs create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Icon/append-a-record-to-the-end-of-a-text-file.icon create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/J/append-a-record-to-the-end-of-a-text-file.j create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/MATLAB/append-a-record-to-the-end-of-a-text-file.m create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Perl/append-a-record-to-the-end-of-a-text-file.pl create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PicoLisp/append-a-record-to-the-end-of-a-text-file.l create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/README create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-1.rapidq create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-2.rapidq create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Ruby/append-a-record-to-the-end-of-a-text-file.rb create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Scala/append-a-record-to-the-end-of-a-text-file.scala create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Tcl/append-a-record-to-the-end-of-a-text-file.tcl create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/UNIX-Shell/append-a-record-to-the-end-of-a-text-file.sh create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/00DESCRIPTION create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/C++/arithmetic-geometric-mean-calculate-pi.cpp create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/C/arithmetic-geometric-mean-calculate-pi.c create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Haskell/arithmetic-geometric-mean-calculate-pi.hs create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/J/arithmetic-geometric-mean-calculate-pi.j create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Mathematica/arithmetic-geometric-mean-calculate-pi.math create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/PARI-GP/arithmetic-geometric-mean-calculate-pi.pari create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Perl-6/arithmetic-geometric-mean-calculate-pi.pl6 create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-1.pl create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-2.pl create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/PicoLisp/arithmetic-geometric-mean-calculate-pi.l create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Python/arithmetic-geometric-mean-calculate-pi.py create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/README create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-3.rexx create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Racket/arithmetic-geometric-mean-calculate-pi.rkt create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Ruby/arithmetic-geometric-mean-calculate-pi.rb create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Tcl/arithmetic-geometric-mean-calculate-pi.tcl create mode 100644 Task/Benfords-law/00DESCRIPTION create mode 100644 Task/Benfords-law/AWK/benfords-law.awk create mode 100644 Task/Benfords-law/Ada/benfords-law-1.ada create mode 100644 Task/Benfords-law/Ada/benfords-law-2.ada create mode 100644 Task/Benfords-law/Aime/benfords-law.aime create mode 100644 Task/Benfords-law/AutoHotkey/benfords-law.ahk create mode 100644 Task/Benfords-law/C++/benfords-law.cpp create mode 100644 Task/Benfords-law/C/benfords-law.c create mode 100644 Task/Benfords-law/CoffeeScript/benfords-law.coffee create mode 100644 Task/Benfords-law/Common-Lisp/benfords-law.lisp create mode 100644 Task/Benfords-law/D/benfords-law-1.d create mode 100644 Task/Benfords-law/D/benfords-law-2.d create mode 100644 Task/Benfords-law/Erlang/benfords-law.erl create mode 100644 Task/Benfords-law/Forth/benfords-law.fth create mode 100644 Task/Benfords-law/Fortran/benfords-law-1.f create mode 100644 Task/Benfords-law/Fortran/benfords-law-2.f create mode 100644 Task/Benfords-law/Go/benfords-law.go create mode 100644 Task/Benfords-law/Haskell/benfords-law.hs create mode 100644 Task/Benfords-law/Icon/benfords-law.icon create mode 100644 Task/Benfords-law/J/benfords-law.j create mode 100644 Task/Benfords-law/Java/benfords-law.java create mode 100644 Task/Benfords-law/Julia/benfords-law.julia create mode 100644 Task/Benfords-law/Liberty-BASIC/benfords-law.liberty create mode 100644 Task/Benfords-law/Lua/benfords-law.lua create mode 100644 Task/Benfords-law/Mathematica/benfords-law.math create mode 100644 Task/Benfords-law/NetRexx/benfords-law.netrexx create mode 100644 Task/Benfords-law/PARI-GP/benfords-law.pari create mode 100644 Task/Benfords-law/PL-I/benfords-law.pli create mode 100644 Task/Benfords-law/PL-pgSQL/benfords-law.sql create mode 100644 Task/Benfords-law/Perl-6/benfords-law.pl6 create mode 100644 Task/Benfords-law/Perl/benfords-law.pl create mode 100644 Task/Benfords-law/Prolog/benfords-law.pro create mode 100644 Task/Benfords-law/Python/benfords-law.py create mode 100644 Task/Benfords-law/R/benfords-law.r create mode 100644 Task/Benfords-law/README create mode 100644 Task/Benfords-law/REXX/benfords-law.rexx create mode 100644 Task/Benfords-law/Racket/benfords-law.rkt create mode 100644 Task/Benfords-law/Ruby/benfords-law.rb create mode 100644 Task/Benfords-law/Run-BASIC/benfords-law.run create mode 100644 Task/Benfords-law/SQL/benfords-law.sql create mode 100644 Task/Benfords-law/Scala/benfords-law.scala create mode 100644 Task/Benfords-law/Tcl/benfords-law-1.tcl create mode 100644 Task/Benfords-law/Tcl/benfords-law-2.tcl create mode 100644 Task/Bernoulli-numbers/00DESCRIPTION create mode 100644 Task/Bernoulli-numbers/00META.yaml create mode 100644 Task/Bernoulli-numbers/C/bernoulli-numbers.c create mode 100644 Task/Bernoulli-numbers/Common-Lisp/bernoulli-numbers.lisp create mode 100644 Task/Bernoulli-numbers/D/bernoulli-numbers.d create mode 100644 Task/Bernoulli-numbers/Go/bernoulli-numbers.go create mode 100644 Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs create mode 100644 Task/Bernoulli-numbers/Icon/bernoulli-numbers.icon create mode 100644 Task/Bernoulli-numbers/J/bernoulli-numbers-1.j create mode 100644 Task/Bernoulli-numbers/J/bernoulli-numbers-2.j create mode 100644 Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple create mode 100644 Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-1.math create mode 100644 Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-2.math create mode 100644 Task/Bernoulli-numbers/PARI-GP/bernoulli-numbers.pari create mode 100644 Task/Bernoulli-numbers/PL-I/bernoulli-numbers.pli create mode 100644 Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-1.pl6 create mode 100644 Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-2.pl6 create mode 100644 Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 create mode 100644 Task/Bernoulli-numbers/Perl/bernoulli-numbers-1.pl create mode 100644 Task/Bernoulli-numbers/Perl/bernoulli-numbers-2.pl create mode 100644 Task/Bernoulli-numbers/Perl/bernoulli-numbers-3.pl create mode 100644 Task/Bernoulli-numbers/PicoLisp/bernoulli-numbers.l create mode 100644 Task/Bernoulli-numbers/Python/bernoulli-numbers-1.py create mode 100644 Task/Bernoulli-numbers/Python/bernoulli-numbers-2.py create mode 100644 Task/Bernoulli-numbers/README create mode 100644 Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx create mode 100644 Task/Bernoulli-numbers/Racket/bernoulli-numbers.rkt create mode 100644 Task/Bernoulli-numbers/Ruby/bernoulli-numbers.rb create mode 100644 Task/Bernoulli-numbers/Tcl/bernoulli-numbers.tcl create mode 100644 Task/Bitcoin-public-point-to-address/00DESCRIPTION create mode 100644 Task/Bitcoin-public-point-to-address/C/bitcoin-public-point-to-address.c create mode 100644 Task/Bitcoin-public-point-to-address/D/bitcoin-public-point-to-address.d create mode 100644 Task/Bitcoin-public-point-to-address/Go/bitcoin-public-point-to-address.go create mode 100644 Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 create mode 100644 Task/Bitcoin-public-point-to-address/Perl/bitcoin-public-point-to-address.pl create mode 100644 Task/Bitcoin-public-point-to-address/README create mode 100644 Task/Bitcoin-public-point-to-address/Racket/bitcoin-public-point-to-address.rkt create mode 100644 Task/Bitcoin-public-point-to-address/Ruby/bitcoin-public-point-to-address.rb create mode 100644 Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-1.tcl create mode 100644 Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-2.tcl create mode 100644 Task/CSV-data-manipulation/00DESCRIPTION create mode 100644 Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk create mode 100644 Task/CSV-data-manipulation/AutoHotkey/csv-data-manipulation.ahk create mode 100644 Task/CSV-data-manipulation/C++/csv-data-manipulation.cpp create mode 100644 Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs create mode 100644 Task/CSV-data-manipulation/Clojure/csv-data-manipulation.clj create mode 100644 Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp create mode 100644 Task/CSV-data-manipulation/D/csv-data-manipulation.d create mode 100644 Task/CSV-data-manipulation/Erlang/csv-data-manipulation.erl create mode 100644 Task/CSV-data-manipulation/Forth/csv-data-manipulation.fth create mode 100644 Task/CSV-data-manipulation/Go/csv-data-manipulation.go create mode 100644 Task/CSV-data-manipulation/Groovy/csv-data-manipulation.groovy create mode 100644 Task/CSV-data-manipulation/Haskell/csv-data-manipulation.hs create mode 100644 Task/CSV-data-manipulation/Icon/csv-data-manipulation.icon create mode 100644 Task/CSV-data-manipulation/J/csv-data-manipulation-1.j create mode 100644 Task/CSV-data-manipulation/J/csv-data-manipulation-2.j create mode 100644 Task/CSV-data-manipulation/J/csv-data-manipulation-3.j create mode 100644 Task/CSV-data-manipulation/J/csv-data-manipulation-4.j create mode 100644 Task/CSV-data-manipulation/Java/csv-data-manipulation-1.java create mode 100644 Task/CSV-data-manipulation/Java/csv-data-manipulation-2.java create mode 100644 Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua create mode 100644 Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m create mode 100644 Task/CSV-data-manipulation/Maple/csv-data-manipulation-1.maple create mode 100644 Task/CSV-data-manipulation/Maple/csv-data-manipulation-2.maple create mode 100644 Task/CSV-data-manipulation/Mathematica/csv-data-manipulation.math create mode 100644 Task/CSV-data-manipulation/NetRexx/csv-data-manipulation.netrexx create mode 100644 Task/CSV-data-manipulation/PHP/csv-data-manipulation.php create mode 100644 Task/CSV-data-manipulation/PL-I/csv-data-manipulation.pli create mode 100644 Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 create mode 100644 Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 create mode 100644 Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl create mode 100644 Task/CSV-data-manipulation/Perl/csv-data-manipulation-2.pl create mode 100644 Task/CSV-data-manipulation/PicoLisp/csv-data-manipulation.l create mode 100644 Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro create mode 100644 Task/CSV-data-manipulation/Python/csv-data-manipulation.py create mode 100644 Task/CSV-data-manipulation/R/csv-data-manipulation-1.r create mode 100644 Task/CSV-data-manipulation/R/csv-data-manipulation-2.r create mode 100644 Task/CSV-data-manipulation/README create mode 100644 Task/CSV-data-manipulation/REXX/csv-data-manipulation.rexx create mode 100644 Task/CSV-data-manipulation/Racket/csv-data-manipulation-1.rkt create mode 100644 Task/CSV-data-manipulation/Racket/csv-data-manipulation-2.rkt create mode 100644 Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb create mode 100644 Task/CSV-data-manipulation/Run-BASIC/csv-data-manipulation.run create mode 100644 Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala create mode 100644 Task/CSV-data-manipulation/Seed7/csv-data-manipulation.seed7 create mode 100644 Task/CSV-data-manipulation/TUSCRIPT/csv-data-manipulation.tu create mode 100644 Task/CSV-data-manipulation/Tcl/csv-data-manipulation.tcl create mode 100644 Task/CSV-data-manipulation/UNIX-Shell/csv-data-manipulation.sh create mode 100644 Task/CSV-data-manipulation/Vedit-macro-language/csv-data-manipulation.vedit create mode 100644 Task/Calendar---for-REAL-programmers/00DESCRIPTION create mode 100644 Task/Calendar---for-REAL-programmers/00META.yaml create mode 100644 Task/Calendar---for-REAL-programmers/ALGOL-68/calendar---for-real-programmers.alg create mode 100644 Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.ada create mode 100644 Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk create mode 100644 Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk create mode 100644 Task/Calendar---for-REAL-programmers/BBC-BASIC/calendar---for-real-programmers.bbc create mode 100644 Task/Calendar---for-REAL-programmers/D/calendar---for-real-programmers.d create mode 100644 Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena create mode 100644 Task/Calendar---for-REAL-programmers/GUISS/calendar---for-real-programmers.guiss create mode 100644 Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon create mode 100644 Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon create mode 100644 Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-1.j create mode 100644 Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-2.j create mode 100644 Task/Calendar---for-REAL-programmers/PHP/calendar---for-real-programmers.php create mode 100644 Task/Calendar---for-REAL-programmers/PL-I/calendar---for-real-programmers.pli create mode 100644 Task/Calendar---for-REAL-programmers/Perl-6/calendar---for-real-programmers.pl6 create mode 100644 Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-1.pl create mode 100644 Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-2.pl create mode 100644 Task/Calendar---for-REAL-programmers/PicoLisp/calendar---for-real-programmers.l create mode 100644 Task/Calendar---for-REAL-programmers/README create mode 100644 Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx create mode 100644 Task/Calendar---for-REAL-programmers/Racket/calendar---for-real-programmers.rkt create mode 100644 Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-1.rb create mode 100644 Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-2.rb create mode 100644 Task/Calendar---for-REAL-programmers/Seed7/calendar---for-real-programmers.seed7 create mode 100644 Task/Calendar---for-REAL-programmers/Tcl/calendar---for-real-programmers.tcl create mode 100644 Task/Calendar---for-REAL-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit create mode 100644 Task/Calendar---for-REAL-programmers/X86-Assembly/calendar---for-real-programmers.x86 create mode 100644 Task/Casting-out-nines/00DESCRIPTION create mode 100644 Task/Casting-out-nines/00META.yaml create mode 100644 Task/Casting-out-nines/C++/casting-out-nines-1.cpp create mode 100644 Task/Casting-out-nines/C++/casting-out-nines-2.cpp create mode 100644 Task/Casting-out-nines/C++/casting-out-nines-3.cpp create mode 100644 Task/Casting-out-nines/C++/casting-out-nines-4.cpp create mode 100644 Task/Casting-out-nines/C++/casting-out-nines-5.cpp create mode 100644 Task/Casting-out-nines/Common-Lisp/casting-out-nines.lisp create mode 100644 Task/Casting-out-nines/D/casting-out-nines.d create mode 100644 Task/Casting-out-nines/Go/casting-out-nines.go create mode 100644 Task/Casting-out-nines/J/casting-out-nines-1.j create mode 100644 Task/Casting-out-nines/J/casting-out-nines-2.j create mode 100644 Task/Casting-out-nines/J/casting-out-nines-3.j create mode 100644 Task/Casting-out-nines/J/casting-out-nines-4.j create mode 100644 Task/Casting-out-nines/J/casting-out-nines-5.j create mode 100644 Task/Casting-out-nines/J/casting-out-nines-6.j create mode 100644 Task/Casting-out-nines/Julia/casting-out-nines.julia create mode 100644 Task/Casting-out-nines/Objeck/casting-out-nines.objeck create mode 100644 Task/Casting-out-nines/PARI-GP/casting-out-nines.pari create mode 100644 Task/Casting-out-nines/Perl-6/casting-out-nines.pl6 create mode 100644 Task/Casting-out-nines/Perl/casting-out-nines.pl create mode 100644 Task/Casting-out-nines/PicoLisp/casting-out-nines.l create mode 100644 Task/Casting-out-nines/Python/casting-out-nines.py create mode 100644 Task/Casting-out-nines/README create mode 100644 Task/Casting-out-nines/REXX/casting-out-nines.rexx create mode 100644 Task/Casting-out-nines/Racket/casting-out-nines.rkt create mode 100644 Task/Casting-out-nines/Seed7/casting-out-nines.seed7 create mode 100644 Task/Casting-out-nines/Tcl/casting-out-nines.tcl create mode 100644 Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION create mode 100644 Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 create mode 100644 Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada create mode 100644 Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk create mode 100644 Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat create mode 100644 Task/Catalan-numbers-Pascals-triangle/C++/catalan-numbers-pascals-triangle.cpp create mode 100644 Task/Catalan-numbers-Pascals-triangle/D/catalan-numbers-pascals-triangle.d create mode 100644 Task/Catalan-numbers-Pascals-triangle/Icon/catalan-numbers-pascals-triangle.icon create mode 100644 Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-1.j create mode 100644 Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-2.j create mode 100644 Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-3.j create mode 100644 Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m create mode 100644 Task/Catalan-numbers-Pascals-triangle/Mathematica/catalan-numbers-pascals-triangle.math create mode 100644 Task/Catalan-numbers-Pascals-triangle/PARI-GP/catalan-numbers-pascals-triangle.pari create mode 100644 Task/Catalan-numbers-Pascals-triangle/Pascal/catalan-numbers-pascals-triangle.pascal create mode 100644 Task/Catalan-numbers-Pascals-triangle/Perl-6/catalan-numbers-pascals-triangle.pl6 create mode 100644 Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-1.pl create mode 100644 Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-2.pl create mode 100644 Task/Catalan-numbers-Pascals-triangle/PicoLisp/catalan-numbers-pascals-triangle.l create mode 100644 Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py create mode 100644 Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-2.py create mode 100644 Task/Catalan-numbers-Pascals-triangle/README create mode 100644 Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx create mode 100644 Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx create mode 100644 Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx create mode 100644 Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-4.rexx create mode 100644 Task/Catalan-numbers-Pascals-triangle/Racket/catalan-numbers-pascals-triangle.rkt create mode 100644 Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb create mode 100644 Task/Catalan-numbers-Pascals-triangle/Run-BASIC/catalan-numbers-pascals-triangle.run create mode 100644 Task/Catalan-numbers-Pascals-triangle/Scilab/catalan-numbers-pascals-triangle.scilab create mode 100644 Task/Catalan-numbers-Pascals-triangle/Seed7/catalan-numbers-pascals-triangle.seed7 create mode 100644 Task/Catalan-numbers-Pascals-triangle/TI-83-BASIC/catalan-numbers-pascals-triangle.ti-83 create mode 100644 Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl create mode 100644 Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vb create mode 100644 Task/Catalan-numbers-Pascals-triangle/Visual-Basic/catalan-numbers-pascals-triangle.vb create mode 100644 Task/Catamorphism/00DESCRIPTION create mode 100644 Task/Catamorphism/Ada/catamorphism.ada create mode 100644 Task/Catamorphism/Bracmat/catamorphism.bracmat create mode 100644 Task/Catamorphism/C++/catamorphism.cpp create mode 100644 Task/Catamorphism/C-sharp/catamorphism.cs create mode 100644 Task/Catamorphism/C/catamorphism.c create mode 100644 Task/Catamorphism/Clojure/catamorphism.clj create mode 100644 Task/Catamorphism/Common-Lisp/catamorphism.lisp create mode 100644 Task/Catamorphism/D/catamorphism.d create mode 100644 Task/Catamorphism/Deja-Vu/catamorphism.djv create mode 100644 Task/Catamorphism/Go/catamorphism.go create mode 100644 Task/Catamorphism/Haskell/catamorphism.hs create mode 100644 Task/Catamorphism/Icon/catamorphism.icon create mode 100644 Task/Catamorphism/J/catamorphism-1.j create mode 100644 Task/Catamorphism/J/catamorphism-2.j create mode 100644 Task/Catamorphism/Java/catamorphism.java create mode 100644 Task/Catamorphism/JavaScript/catamorphism.js create mode 100644 Task/Catamorphism/LOLCODE/catamorphism.lol create mode 100644 Task/Catamorphism/Logtalk/catamorphism.logtalk create mode 100644 Task/Catamorphism/Maple/catamorphism-1.maple create mode 100644 Task/Catamorphism/Maple/catamorphism-2.maple create mode 100644 Task/Catamorphism/Mathematica/catamorphism.math create mode 100644 Task/Catamorphism/Maxima/catamorphism-1.maxima create mode 100644 Task/Catamorphism/Maxima/catamorphism-2.maxima create mode 100644 Task/Catamorphism/Nemerle/catamorphism.nemerle create mode 100644 Task/Catamorphism/OCaml/catamorphism.ocaml create mode 100644 Task/Catamorphism/Oberon-2/catamorphism.oberon-2 create mode 100644 Task/Catamorphism/PARI-GP/catamorphism-1.pari create mode 100644 Task/Catamorphism/PARI-GP/catamorphism-2.pari create mode 100644 Task/Catamorphism/Pascal/catamorphism.pascal create mode 100644 Task/Catamorphism/Perl-6/catamorphism-1.pl6 create mode 100644 Task/Catamorphism/Perl-6/catamorphism-2.pl6 create mode 100644 Task/Catamorphism/Perl/catamorphism.pl create mode 100644 Task/Catamorphism/PicoLisp/catamorphism.l create mode 100644 Task/Catamorphism/Prolog/catamorphism.pro create mode 100644 Task/Catamorphism/Python/catamorphism-1.py create mode 100644 Task/Catamorphism/Python/catamorphism-2.py create mode 100644 Task/Catamorphism/README create mode 100644 Task/Catamorphism/REXX/catamorphism.rexx create mode 100644 Task/Catamorphism/Racket/catamorphism.rkt create mode 100644 Task/Catamorphism/Ruby/catamorphism-1.rb create mode 100644 Task/Catamorphism/Ruby/catamorphism-2.rb create mode 100644 Task/Catamorphism/Run-BASIC/catamorphism.run create mode 100644 Task/Catamorphism/Standard-ML/catamorphism.ml create mode 100644 Task/Catamorphism/Tcl/catamorphism-1.tcl create mode 100644 Task/Catamorphism/Tcl/catamorphism-2.tcl create mode 100644 Task/Catamorphism/Tcl/catamorphism-3.tcl delete mode 100644 Task/Character-matching/D/character-matching.d delete mode 100644 Task/Character-matching/Elena/character-matching.elena delete mode 100644 Task/Character-matching/Perl/character-matching.pl delete mode 100644 Task/Character-matching/README delete mode 100644 Task/Character-matching/REXX/character-matching.rexx create mode 100644 Task/Chinese-remainder-theorem/00DESCRIPTION create mode 100644 Task/Chinese-remainder-theorem/Ada/chinese-remainder-theorem.ada create mode 100644 Task/Chinese-remainder-theorem/Bracmat/chinese-remainder-theorem.bracmat create mode 100644 Task/Chinese-remainder-theorem/C/chinese-remainder-theorem.c create mode 100644 Task/Chinese-remainder-theorem/Common-Lisp/chinese-remainder-theorem.lisp create mode 100644 Task/Chinese-remainder-theorem/D/chinese-remainder-theorem.d create mode 100644 Task/Chinese-remainder-theorem/Erlang/chinese-remainder-theorem.erl create mode 100644 Task/Chinese-remainder-theorem/Forth/chinese-remainder-theorem.fth create mode 100644 Task/Chinese-remainder-theorem/Go/chinese-remainder-theorem.go create mode 100644 Task/Chinese-remainder-theorem/Haskell/chinese-remainder-theorem.hs create mode 100644 Task/Chinese-remainder-theorem/Icon/chinese-remainder-theorem.icon create mode 100644 Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-1.j create mode 100644 Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-2.j create mode 100644 Task/Chinese-remainder-theorem/Maple/chinese-remainder-theorem.maple create mode 100644 Task/Chinese-remainder-theorem/Mathematica/chinese-remainder-theorem.math create mode 100644 Task/Chinese-remainder-theorem/OCaml/chinese-remainder-theorem.ocaml create mode 100644 Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-1.pari create mode 100644 Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-2.pari create mode 100644 Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-3.pari create mode 100644 Task/Chinese-remainder-theorem/Perl-6/chinese-remainder-theorem.pl6 create mode 100644 Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-1.pl create mode 100644 Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-2.pl create mode 100644 Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl create mode 100644 Task/Chinese-remainder-theorem/PicoLisp/chinese-remainder-theorem.l create mode 100644 Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py create mode 100644 Task/Chinese-remainder-theorem/R/chinese-remainder-theorem.r create mode 100644 Task/Chinese-remainder-theorem/README create mode 100644 Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx create mode 100644 Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx create mode 100644 Task/Chinese-remainder-theorem/Racket/chinese-remainder-theorem.rkt create mode 100644 Task/Chinese-remainder-theorem/Ruby/chinese-remainder-theorem.rb create mode 100644 Task/Chinese-remainder-theorem/Seed7/chinese-remainder-theorem.seed7 create mode 100644 Task/Chinese-remainder-theorem/Tcl/chinese-remainder-theorem.tcl create mode 100644 Task/Circles-of-given-radius-through-two-points/00DESCRIPTION create mode 100644 Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-1.ahk create mode 100644 Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-2.ahk create mode 100644 Task/Circles-of-given-radius-through-two-points/BASIC/circles-of-given-radius-through-two-points.basic create mode 100644 Task/Circles-of-given-radius-through-two-points/C/circles-of-given-radius-through-two-points.c create mode 100644 Task/Circles-of-given-radius-through-two-points/D/circles-of-given-radius-through-two-points.d create mode 100644 Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f create mode 100644 Task/Circles-of-given-radius-through-two-points/Go/circles-of-given-radius-through-two-points.go create mode 100644 Task/Circles-of-given-radius-through-two-points/Haskell/circles-of-given-radius-through-two-points.hs create mode 100644 Task/Circles-of-given-radius-through-two-points/Icon/circles-of-given-radius-through-two-points.icon create mode 100644 Task/Circles-of-given-radius-through-two-points/J/circles-of-given-radius-through-two-points.j create mode 100644 Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-1.maxima create mode 100644 Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-2.maxima create mode 100644 Task/Circles-of-given-radius-through-two-points/PARI-GP/circles-of-given-radius-through-two-points.pari create mode 100644 Task/Circles-of-given-radius-through-two-points/PL-I/circles-of-given-radius-through-two-points.pli create mode 100644 Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-1.pl6 create mode 100644 Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-2.pl6 create mode 100644 Task/Circles-of-given-radius-through-two-points/Python/circles-of-given-radius-through-two-points.py create mode 100644 Task/Circles-of-given-radius-through-two-points/README create mode 100644 Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx create mode 100644 Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-1.rkt create mode 100644 Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-2.rkt create mode 100644 Task/Circles-of-given-radius-through-two-points/Ruby/circles-of-given-radius-through-two-points.rb create mode 100644 Task/Circles-of-given-radius-through-two-points/Rust/circles-of-given-radius-through-two-points.rust create mode 100644 Task/Circles-of-given-radius-through-two-points/Seed7/circles-of-given-radius-through-two-points.seed7 create mode 100644 Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-1.tcl create mode 100644 Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-2.tcl create mode 100644 Task/Circles-of-given-radius-through-two-points/XPL0/circles-of-given-radius-through-two-points.xpl0 create mode 100644 Task/Closures-Value-capture/00DESCRIPTION create mode 100644 Task/Closures-Value-capture/ALGOL-68/closures-value-capture.alg create mode 100644 Task/Closures-Value-capture/Ada/closures-value-capture.ada create mode 100644 Task/Closures-Value-capture/Axiom/closures-value-capture-1.axiom create mode 100644 Task/Closures-Value-capture/Axiom/closures-value-capture-2.axiom create mode 100644 Task/Closures-Value-capture/Axiom/closures-value-capture-3.axiom create mode 100644 Task/Closures-Value-capture/Babel/closures-value-capture-1.pb create mode 100644 Task/Closures-Value-capture/Babel/closures-value-capture-2.pb create mode 100644 Task/Closures-Value-capture/Bracmat/closures-value-capture.bracmat create mode 100644 Task/Closures-Value-capture/C++/closures-value-capture.cpp create mode 100644 Task/Closures-Value-capture/C/closures-value-capture-1.c create mode 100644 Task/Closures-Value-capture/C/closures-value-capture-2.c create mode 100644 Task/Closures-Value-capture/C/closures-value-capture-3.c create mode 100644 Task/Closures-Value-capture/CoffeeScript/closures-value-capture.coffee create mode 100644 Task/Closures-Value-capture/Common-Lisp/closures-value-capture.lisp create mode 100644 Task/Closures-Value-capture/D/closures-value-capture-1.d create mode 100644 Task/Closures-Value-capture/D/closures-value-capture-2.d create mode 100644 Task/Closures-Value-capture/Delphi/closures-value-capture.delphi create mode 100644 Task/Closures-Value-capture/Emacs-Lisp/closures-value-capture.l create mode 100644 Task/Closures-Value-capture/Erlang/closures-value-capture.erl create mode 100644 Task/Closures-Value-capture/Factor/closures-value-capture-1.factor create mode 100644 Task/Closures-Value-capture/Factor/closures-value-capture-2.factor create mode 100644 Task/Closures-Value-capture/Fantom/closures-value-capture.fantom create mode 100644 Task/Closures-Value-capture/Go/closures-value-capture.go create mode 100644 Task/Closures-Value-capture/Groovy/closures-value-capture-1.groovy create mode 100644 Task/Closures-Value-capture/Groovy/closures-value-capture-2.groovy create mode 100644 Task/Closures-Value-capture/Haskell/closures-value-capture-1.hs create mode 100644 Task/Closures-Value-capture/Haskell/closures-value-capture-2.hs create mode 100644 Task/Closures-Value-capture/Haskell/closures-value-capture-3.hs create mode 100644 Task/Closures-Value-capture/Haskell/closures-value-capture-4.hs create mode 100644 Task/Closures-Value-capture/Icon/closures-value-capture.icon create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-1.j create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-2.j create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-3.j create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-4.j create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-5.j create mode 100644 Task/Closures-Value-capture/J/closures-value-capture-6.j create mode 100644 Task/Closures-Value-capture/Java/closures-value-capture-1.java create mode 100644 Task/Closures-Value-capture/Java/closures-value-capture-2.java create mode 100644 Task/Closures-Value-capture/JavaScript/closures-value-capture-1.js create mode 100644 Task/Closures-Value-capture/JavaScript/closures-value-capture-2.js create mode 100644 Task/Closures-Value-capture/Julia/closures-value-capture.julia create mode 100644 Task/Closures-Value-capture/Logtalk/closures-value-capture-1.logtalk create mode 100644 Task/Closures-Value-capture/Logtalk/closures-value-capture-2.logtalk create mode 100644 Task/Closures-Value-capture/Lua/closures-value-capture.lua create mode 100644 Task/Closures-Value-capture/Maple/closures-value-capture.maple create mode 100644 Task/Closures-Value-capture/Mathematica/closures-value-capture.math create mode 100644 Task/Closures-Value-capture/Nemerle/closures-value-capture.nemerle create mode 100644 Task/Closures-Value-capture/OCaml/closures-value-capture.ocaml create mode 100644 Task/Closures-Value-capture/Objective-C/closures-value-capture.m create mode 100644 Task/Closures-Value-capture/PARI-GP/closures-value-capture.pari create mode 100644 Task/Closures-Value-capture/PHP/closures-value-capture-1.php create mode 100644 Task/Closures-Value-capture/PHP/closures-value-capture-2.php create mode 100644 Task/Closures-Value-capture/Perl-6/closures-value-capture-1.pl6 create mode 100644 Task/Closures-Value-capture/Perl-6/closures-value-capture-2.pl6 create mode 100644 Task/Closures-Value-capture/Perl/closures-value-capture.pl create mode 100644 Task/Closures-Value-capture/PicoLisp/closures-value-capture.l create mode 100644 Task/Closures-Value-capture/Pike/closures-value-capture.pike create mode 100644 Task/Closures-Value-capture/Prolog/closures-value-capture.pro create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-1.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-2.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-3.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-4.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-5.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-6.py create mode 100644 Task/Closures-Value-capture/Python/closures-value-capture-7.py create mode 100644 Task/Closures-Value-capture/R/closures-value-capture-1.r create mode 100644 Task/Closures-Value-capture/R/closures-value-capture-2.r create mode 100644 Task/Closures-Value-capture/R/closures-value-capture-3.r create mode 100644 Task/Closures-Value-capture/README create mode 100644 Task/Closures-Value-capture/REXX/closures-value-capture.rexx create mode 100644 Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt create mode 100644 Task/Closures-Value-capture/Racket/closures-value-capture-2.rkt create mode 100644 Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb create mode 100644 Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb create mode 100644 Task/Closures-Value-capture/Rust/closures-value-capture.rust create mode 100644 Task/Closures-Value-capture/Scala/closures-value-capture.scala create mode 100644 Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss create mode 100644 Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss create mode 100644 Task/Closures-Value-capture/Smalltalk/closures-value-capture.st create mode 100644 Task/Closures-Value-capture/Tcl/closures-value-capture.tcl create mode 100644 Task/Combinations-and-permutations/00DESCRIPTION create mode 100644 Task/Combinations-and-permutations/00META.yaml create mode 100644 Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-1.alg create mode 100644 Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-2.alg create mode 100644 Task/Combinations-and-permutations/Bracmat/combinations-and-permutations.bracmat create mode 100644 Task/Combinations-and-permutations/C/combinations-and-permutations.c create mode 100644 Task/Combinations-and-permutations/D/combinations-and-permutations.d create mode 100644 Task/Combinations-and-permutations/Icon/combinations-and-permutations.icon create mode 100644 Task/Combinations-and-permutations/J/combinations-and-permutations-1.j create mode 100644 Task/Combinations-and-permutations/J/combinations-and-permutations-2.j create mode 100644 Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-1.math create mode 100644 Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-2.math create mode 100644 Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 create mode 100644 Task/Combinations-and-permutations/Perl/combinations-and-permutations.pl create mode 100644 Task/Combinations-and-permutations/Python/combinations-and-permutations.py create mode 100644 Task/Combinations-and-permutations/README create mode 100644 Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx create mode 100644 Task/Combinations-and-permutations/Racket/combinations-and-permutations.rkt create mode 100644 Task/Combinations-and-permutations/Ruby/combinations-and-permutations.rb create mode 100644 Task/Combinations-and-permutations/Tcl/combinations-and-permutations-1.tcl create mode 100644 Task/Combinations-and-permutations/Tcl/combinations-and-permutations-2.tcl create mode 100644 Task/Comma-quibbling/00DESCRIPTION create mode 100644 Task/Comma-quibbling/AWK/comma-quibbling.awk create mode 100644 Task/Comma-quibbling/Ada/comma-quibbling.ada create mode 100644 Task/Comma-quibbling/AutoHotkey/comma-quibbling.ahk create mode 100644 Task/Comma-quibbling/C++/comma-quibbling.cpp create mode 100644 Task/Comma-quibbling/C/comma-quibbling.c create mode 100644 Task/Comma-quibbling/COBOL/comma-quibbling.cobol create mode 100644 Task/Comma-quibbling/Clojure/comma-quibbling.clj create mode 100644 Task/Comma-quibbling/CoffeeScript/comma-quibbling.coffee create mode 100644 Task/Comma-quibbling/Common-Lisp/comma-quibbling.lisp create mode 100644 Task/Comma-quibbling/D/comma-quibbling-1.d create mode 100644 Task/Comma-quibbling/D/comma-quibbling-2.d create mode 100644 Task/Comma-quibbling/Deja-Vu/comma-quibbling.djv create mode 100644 Task/Comma-quibbling/Erlang/comma-quibbling.erl create mode 100644 Task/Comma-quibbling/Go/comma-quibbling.go create mode 100644 Task/Comma-quibbling/Groovy/comma-quibbling-1.groovy create mode 100644 Task/Comma-quibbling/Groovy/comma-quibbling-2.groovy create mode 100644 Task/Comma-quibbling/Haskell/comma-quibbling.hs create mode 100644 Task/Comma-quibbling/Icon/comma-quibbling.icon create mode 100644 Task/Comma-quibbling/J/comma-quibbling-1.j create mode 100644 Task/Comma-quibbling/J/comma-quibbling-2.j create mode 100644 Task/Comma-quibbling/J/comma-quibbling-3.j create mode 100644 Task/Comma-quibbling/Java/comma-quibbling.java create mode 100644 Task/Comma-quibbling/JavaScript/comma-quibbling.js create mode 100644 Task/Comma-quibbling/Julia/comma-quibbling.julia create mode 100644 Task/Comma-quibbling/Logo/comma-quibbling.logo create mode 100644 Task/Comma-quibbling/MAXScript/comma-quibbling-1.max create mode 100644 Task/Comma-quibbling/MAXScript/comma-quibbling-2.max create mode 100644 Task/Comma-quibbling/Maple/comma-quibbling-1.maple create mode 100644 Task/Comma-quibbling/Maple/comma-quibbling-2.maple create mode 100644 Task/Comma-quibbling/Mathematica/comma-quibbling.math create mode 100644 Task/Comma-quibbling/NetRexx/comma-quibbling.netrexx create mode 100644 Task/Comma-quibbling/PARI-GP/comma-quibbling.pari create mode 100644 Task/Comma-quibbling/PHP/comma-quibbling.php create mode 100644 Task/Comma-quibbling/PL-I/comma-quibbling.pli create mode 100644 Task/Comma-quibbling/Perl-6/comma-quibbling.pl6 create mode 100644 Task/Comma-quibbling/Perl/comma-quibbling-1.pl create mode 100644 Task/Comma-quibbling/Perl/comma-quibbling-2.pl create mode 100644 Task/Comma-quibbling/PicoLisp/comma-quibbling.l create mode 100644 Task/Comma-quibbling/Prolog/comma-quibbling-1.pro create mode 100644 Task/Comma-quibbling/Prolog/comma-quibbling-2.pro create mode 100644 Task/Comma-quibbling/Python/comma-quibbling-1.py create mode 100644 Task/Comma-quibbling/Python/comma-quibbling-2.py create mode 100644 Task/Comma-quibbling/Python/comma-quibbling-3.py create mode 100644 Task/Comma-quibbling/README create mode 100644 Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol create mode 100644 Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol create mode 100644 Task/Comma-quibbling/REXX/comma-quibbling-1.rexx create mode 100644 Task/Comma-quibbling/REXX/comma-quibbling-2.rexx create mode 100644 Task/Comma-quibbling/REXX/comma-quibbling-3.rexx create mode 100644 Task/Comma-quibbling/Racket/comma-quibbling.rkt create mode 100644 Task/Comma-quibbling/Ruby/comma-quibbling.rb create mode 100644 Task/Comma-quibbling/Run-BASIC/comma-quibbling.run create mode 100644 Task/Comma-quibbling/Rust/comma-quibbling.rust create mode 100644 Task/Comma-quibbling/Scala/comma-quibbling.scala create mode 100644 Task/Comma-quibbling/Seed7/comma-quibbling.seed7 create mode 100644 Task/Comma-quibbling/Standard-ML/comma-quibbling.ml create mode 100644 Task/Comma-quibbling/Tcl/comma-quibbling.tcl create mode 100644 Task/Comma-quibbling/UNIX-Shell/comma-quibbling.sh create mode 100644 Task/Comma-quibbling/XPL0/comma-quibbling.xpl0 create mode 100644 Task/Conjugate-transpose/00DESCRIPTION create mode 100644 Task/Conjugate-transpose/00META.yaml create mode 100644 Task/Conjugate-transpose/Ada/conjugate-transpose.ada create mode 100644 Task/Conjugate-transpose/C/conjugate-transpose.c create mode 100644 Task/Conjugate-transpose/D/conjugate-transpose-1.d create mode 100644 Task/Conjugate-transpose/D/conjugate-transpose-2.d create mode 100644 Task/Conjugate-transpose/Factor/conjugate-transpose.factor create mode 100644 Task/Conjugate-transpose/Fortran/conjugate-transpose.f create mode 100644 Task/Conjugate-transpose/Go/conjugate-transpose.go create mode 100644 Task/Conjugate-transpose/J/conjugate-transpose-1.j create mode 100644 Task/Conjugate-transpose/J/conjugate-transpose-2.j create mode 100644 Task/Conjugate-transpose/J/conjugate-transpose-3.j create mode 100644 Task/Conjugate-transpose/Julia/conjugate-transpose-1.julia create mode 100644 Task/Conjugate-transpose/Julia/conjugate-transpose-2.julia create mode 100644 Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia create mode 100644 Task/Conjugate-transpose/Maple/conjugate-transpose.maple create mode 100644 Task/Conjugate-transpose/Mathematica/conjugate-transpose.math create mode 100644 Task/Conjugate-transpose/PARI-GP/conjugate-transpose.pari create mode 100644 Task/Conjugate-transpose/PL-I/conjugate-transpose.pli create mode 100644 Task/Conjugate-transpose/Python/conjugate-transpose.py create mode 100644 Task/Conjugate-transpose/README create mode 100644 Task/Conjugate-transpose/REXX/conjugate-transpose.rexx create mode 100644 Task/Conjugate-transpose/Racket/conjugate-transpose-1.rkt create mode 100644 Task/Conjugate-transpose/Racket/conjugate-transpose-2.rkt create mode 100644 Task/Conjugate-transpose/Racket/conjugate-transpose-3.rkt create mode 100644 Task/Conjugate-transpose/Ruby/conjugate-transpose.rb create mode 100644 Task/Conjugate-transpose/Tcl/conjugate-transpose-1.tcl create mode 100644 Task/Conjugate-transpose/Tcl/conjugate-transpose-2.tcl create mode 100644 Task/Convert-decimal-number-to-rational/00DESCRIPTION create mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-1.ada create mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-2.ada create mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-3.ada create mode 100644 Task/Convert-decimal-number-to-rational/AutoHotkey/convert-decimal-number-to-rational.ahk create mode 100644 Task/Convert-decimal-number-to-rational/Bracmat/convert-decimal-number-to-rational.bracmat create mode 100644 Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-1.c create mode 100644 Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-2.c create mode 100644 Task/Convert-decimal-number-to-rational/D/convert-decimal-number-to-rational.d create mode 100644 Task/Convert-decimal-number-to-rational/Go/convert-decimal-number-to-rational.go create mode 100644 Task/Convert-decimal-number-to-rational/Haskell/convert-decimal-number-to-rational.hs create mode 100644 Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-1.j create mode 100644 Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-2.j create mode 100644 Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-3.j create mode 100644 Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-4.j create mode 100644 Task/Convert-decimal-number-to-rational/Julia/convert-decimal-number-to-rational.julia create mode 100644 Task/Convert-decimal-number-to-rational/Liberty-BASIC/convert-decimal-number-to-rational.liberty create mode 100644 Task/Convert-decimal-number-to-rational/MATLAB/convert-decimal-number-to-rational.m create mode 100644 Task/Convert-decimal-number-to-rational/Maple/convert-decimal-number-to-rational.maple create mode 100644 Task/Convert-decimal-number-to-rational/Mathematica/convert-decimal-number-to-rational.math create mode 100644 Task/Convert-decimal-number-to-rational/NetRexx/convert-decimal-number-to-rational.netrexx create mode 100644 Task/Convert-decimal-number-to-rational/PARI-GP/convert-decimal-number-to-rational.pari create mode 100644 Task/Convert-decimal-number-to-rational/PL-I/convert-decimal-number-to-rational.pli create mode 100644 Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-1.pl6 create mode 100644 Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-2.pl6 create mode 100644 Task/Convert-decimal-number-to-rational/Perl/convert-decimal-number-to-rational.pl create mode 100644 Task/Convert-decimal-number-to-rational/Python/convert-decimal-number-to-rational.py create mode 100644 Task/Convert-decimal-number-to-rational/README create mode 100644 Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-1.rexx create mode 100644 Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-2.rexx create mode 100644 Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx create mode 100644 Task/Convert-decimal-number-to-rational/Racket/convert-decimal-number-to-rational.rkt create mode 100644 Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-1.rb create mode 100644 Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb create mode 100644 Task/Convert-decimal-number-to-rational/Seed7/convert-decimal-number-to-rational.seed7 create mode 100644 Task/Convert-decimal-number-to-rational/Tcl/convert-decimal-number-to-rational.tcl create mode 100644 Task/Currying/00DESCRIPTION create mode 100644 Task/Currying/ALGOL-68/currying.alg create mode 100644 Task/Currying/C-sharp/currying.cs create mode 100644 Task/Currying/Common-Lisp/currying-1.lisp create mode 100644 Task/Currying/Common-Lisp/currying-2.lisp create mode 100644 Task/Currying/D/currying.d create mode 100644 Task/Currying/Erlang/currying.erl create mode 100644 Task/Currying/Forth/currying.fth create mode 100644 Task/Currying/Go/currying.go create mode 100644 Task/Currying/Groovy/currying-1.groovy create mode 100644 Task/Currying/Groovy/currying-2.groovy create mode 100644 Task/Currying/Haskell/currying-1.hs create mode 100644 Task/Currying/Haskell/currying-2.hs create mode 100644 Task/Currying/Haskell/currying-3.hs create mode 100644 Task/Currying/Haskell/currying-4.hs create mode 100644 Task/Currying/Haskell/currying-5.hs create mode 100644 Task/Currying/Haskell/currying-6.hs create mode 100644 Task/Currying/Io/currying.io create mode 100644 Task/Currying/J/currying.j create mode 100644 Task/Currying/Java/currying.java create mode 100644 Task/Currying/JavaScript/currying.js create mode 100644 Task/Currying/Nemerle/currying.nemerle create mode 100644 Task/Currying/OCaml/currying-1.ocaml create mode 100644 Task/Currying/OCaml/currying-2.ocaml create mode 100644 Task/Currying/PARI-GP/currying.pari create mode 100644 Task/Currying/Perl-6/currying.pl6 create mode 100644 Task/Currying/Perl/currying.pl create mode 100644 Task/Currying/Python/currying-1.py create mode 100644 Task/Currying/Python/currying-2.py create mode 100644 Task/Currying/README create mode 100644 Task/Currying/REXX/currying-1.rexx create mode 100644 Task/Currying/REXX/currying-2.rexx create mode 100644 Task/Currying/Racket/currying-1.rkt create mode 100644 Task/Currying/Racket/currying-2.rkt create mode 100644 Task/Currying/Ruby/currying.rb create mode 100644 Task/Currying/Rust/currying.rust create mode 100644 Task/Currying/Standard-ML/currying-1.ml create mode 100644 Task/Currying/Standard-ML/currying-2.ml create mode 100644 Task/Currying/Tcl/currying.tcl create mode 100644 Task/Digital-root-Multiplicative-digital-root/00DESCRIPTION create mode 100644 Task/Digital-root-Multiplicative-digital-root/00META.yaml create mode 100644 Task/Digital-root-Multiplicative-digital-root/ALGOL-68/digital-root-multiplicative-digital-root.alg create mode 100644 Task/Digital-root-Multiplicative-digital-root/AWK/digital-root-multiplicative-digital-root.awk create mode 100644 Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada create mode 100644 Task/Digital-root-Multiplicative-digital-root/Bracmat/digital-root-multiplicative-digital-root.bracmat create mode 100644 Task/Digital-root-Multiplicative-digital-root/C++/digital-root-multiplicative-digital-root.cpp create mode 100644 Task/Digital-root-Multiplicative-digital-root/C/digital-root-multiplicative-digital-root.c create mode 100644 Task/Digital-root-Multiplicative-digital-root/Common-Lisp/digital-root-multiplicative-digital-root.lisp create mode 100644 Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-1.d create mode 100644 Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-2.d create mode 100644 Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-3.d create mode 100644 Task/Digital-root-Multiplicative-digital-root/Fortran/digital-root-multiplicative-digital-root.f create mode 100644 Task/Digital-root-Multiplicative-digital-root/Go/digital-root-multiplicative-digital-root.go create mode 100644 Task/Digital-root-Multiplicative-digital-root/Haskell/digital-root-multiplicative-digital-root.hs create mode 100644 Task/Digital-root-Multiplicative-digital-root/Icon/digital-root-multiplicative-digital-root.icon create mode 100644 Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-1.j create mode 100644 Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-2.j create mode 100644 Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-3.j create mode 100644 Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-4.j create mode 100644 Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-5.j create mode 100644 Task/Digital-root-Multiplicative-digital-root/Java/digital-root-multiplicative-digital-root.java create mode 100644 Task/Digital-root-Multiplicative-digital-root/Mathematica/digital-root-multiplicative-digital-root.math create mode 100644 Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-1.pli create mode 100644 Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-2.pli create mode 100644 Task/Digital-root-Multiplicative-digital-root/Perl-6/digital-root-multiplicative-digital-root.pl6 create mode 100644 Task/Digital-root-Multiplicative-digital-root/Perl/digital-root-multiplicative-digital-root.pl create mode 100644 Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-1.py create mode 100644 Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-2.py create mode 100644 Task/Digital-root-Multiplicative-digital-root/README create mode 100644 Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx create mode 100644 Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx create mode 100644 Task/Digital-root-Multiplicative-digital-root/Racket/digital-root-multiplicative-digital-root.rkt create mode 100644 Task/Digital-root-Multiplicative-digital-root/Ruby/digital-root-multiplicative-digital-root.rb create mode 100644 Task/Digital-root-Multiplicative-digital-root/Scala/digital-root-multiplicative-digital-root.scala create mode 100644 Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-1.tcl create mode 100644 Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-2.tcl create mode 100644 Task/Draw-a-clock/00DESCRIPTION create mode 100644 Task/Draw-a-clock/AWK/draw-a-clock.awk create mode 100644 Task/Draw-a-clock/ActionScript/draw-a-clock.as create mode 100644 Task/Draw-a-clock/AutoHotkey/draw-a-clock.ahk create mode 100644 Task/Draw-a-clock/C++/draw-a-clock.cpp create mode 100644 Task/Draw-a-clock/C/draw-a-clock.c create mode 100644 Task/Draw-a-clock/Fortran/draw-a-clock.f create mode 100644 Task/Draw-a-clock/GUISS/draw-a-clock.guiss create mode 100644 Task/Draw-a-clock/Go/draw-a-clock-1.go create mode 100644 Task/Draw-a-clock/Go/draw-a-clock-2.go create mode 100644 Task/Draw-a-clock/Haskell/draw-a-clock.hs create mode 100644 Task/Draw-a-clock/J/draw-a-clock-1.j create mode 100644 Task/Draw-a-clock/J/draw-a-clock-2.j create mode 100644 Task/Draw-a-clock/Java/draw-a-clock.java create mode 100644 Task/Draw-a-clock/JavaScript/draw-a-clock.js create mode 100644 Task/Draw-a-clock/Liberty-BASIC/draw-a-clock.liberty create mode 100644 Task/Draw-a-clock/Locomotive-Basic/draw-a-clock.locomotive create mode 100644 Task/Draw-a-clock/MATLAB/draw-a-clock.m create mode 100644 Task/Draw-a-clock/Mathematica/draw-a-clock.math create mode 100644 Task/Draw-a-clock/NetRexx/draw-a-clock.netrexx create mode 100644 Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml create mode 100644 Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml create mode 100644 Task/Draw-a-clock/Perl-6/draw-a-clock.pl6 create mode 100644 Task/Draw-a-clock/Perl/draw-a-clock.pl create mode 100644 Task/Draw-a-clock/PicoLisp/draw-a-clock.l create mode 100644 Task/Draw-a-clock/PureBasic/draw-a-clock.purebasic create mode 100644 Task/Draw-a-clock/Python/draw-a-clock.py create mode 100644 Task/Draw-a-clock/README create mode 100644 Task/Draw-a-clock/REXX/draw-a-clock.rexx create mode 100644 Task/Draw-a-clock/Racket/draw-a-clock.rkt create mode 100644 Task/Draw-a-clock/Ruby/draw-a-clock-1.rb create mode 100644 Task/Draw-a-clock/Ruby/draw-a-clock-2.rb create mode 100644 Task/Draw-a-clock/Run-BASIC/draw-a-clock.run create mode 100644 Task/Draw-a-clock/Scala/draw-a-clock-1.scala create mode 100644 Task/Draw-a-clock/Scala/draw-a-clock-2.scala create mode 100644 Task/Draw-a-clock/Seed7/draw-a-clock.seed7 create mode 100644 Task/Draw-a-clock/Tcl/draw-a-clock.tcl create mode 100644 Task/Extensible-prime-generator/00DESCRIPTION create mode 100644 Task/Extensible-prime-generator/Ada/extensible-prime-generator.ada create mode 100644 Task/Extensible-prime-generator/AutoHotkey/extensible-prime-generator.ahk create mode 100644 Task/Extensible-prime-generator/C/extensible-prime-generator.c create mode 100644 Task/Extensible-prime-generator/D/extensible-prime-generator-1.d create mode 100644 Task/Extensible-prime-generator/D/extensible-prime-generator-2.d create mode 100644 Task/Extensible-prime-generator/Go/extensible-prime-generator-1.go create mode 100644 Task/Extensible-prime-generator/Go/extensible-prime-generator-2.go create mode 100644 Task/Extensible-prime-generator/Haskell/extensible-prime-generator-1.hs create mode 100644 Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs create mode 100644 Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs create mode 100644 Task/Extensible-prime-generator/J/extensible-prime-generator.j create mode 100644 Task/Extensible-prime-generator/Mathematica/extensible-prime-generator.math create mode 100644 Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal create mode 100644 Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 create mode 100644 Task/Extensible-prime-generator/Perl/extensible-prime-generator-1.pl create mode 100644 Task/Extensible-prime-generator/Perl/extensible-prime-generator-2.pl create mode 100644 Task/Extensible-prime-generator/Perl/extensible-prime-generator-3.pl create mode 100644 Task/Extensible-prime-generator/Perl/extensible-prime-generator-4.pl create mode 100644 Task/Extensible-prime-generator/Python/extensible-prime-generator-1.py create mode 100644 Task/Extensible-prime-generator/Python/extensible-prime-generator-2.py create mode 100644 Task/Extensible-prime-generator/README create mode 100644 Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx create mode 100644 Task/Extensible-prime-generator/Racket/extensible-prime-generator.rkt create mode 100644 Task/Extensible-prime-generator/Ruby/extensible-prime-generator.rb create mode 100644 Task/Extensible-prime-generator/Seed7/extensible-prime-generator.seed7 create mode 100644 Task/Extensible-prime-generator/Tcl/extensible-prime-generator.tcl create mode 100644 Task/Fibonacci-word-fractal/00DESCRIPTION create mode 100644 Task/Fibonacci-word-fractal/AutoHotkey/fibonacci-word-fractal.ahk create mode 100644 Task/Fibonacci-word-fractal/C++/fibonacci-word-fractal.cpp create mode 100644 Task/Fibonacci-word-fractal/D/fibonacci-word-fractal.d create mode 100644 Task/Fibonacci-word-fractal/Icon/fibonacci-word-fractal.icon create mode 100644 Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-1.j create mode 100644 Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-2.j create mode 100644 Task/Fibonacci-word-fractal/Logo/fibonacci-word-fractal.logo create mode 100644 Task/Fibonacci-word-fractal/Mathematica/fibonacci-word-fractal.math create mode 100644 Task/Fibonacci-word-fractal/Perl-6/fibonacci-word-fractal.pl6 create mode 100644 Task/Fibonacci-word-fractal/Perl/fibonacci-word-fractal.pl create mode 100644 Task/Fibonacci-word-fractal/Python/fibonacci-word-fractal.py create mode 100644 Task/Fibonacci-word-fractal/README create mode 100644 Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx create mode 100644 Task/Fibonacci-word-fractal/Racket/fibonacci-word-fractal.rkt create mode 100644 Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb create mode 100644 Task/Fibonacci-word-fractal/Scala/fibonacci-word-fractal.scala create mode 100644 Task/Fibonacci-word-fractal/Tcl/fibonacci-word-fractal.tcl create mode 100644 Task/Fibonacci-word/00DESCRIPTION create mode 100644 Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg create mode 100644 Task/Fibonacci-word/Ada/fibonacci-word.ada create mode 100644 Task/Fibonacci-word/AutoHotkey/fibonacci-word.ahk create mode 100644 Task/Fibonacci-word/C++/fibonacci-word.cpp create mode 100644 Task/Fibonacci-word/C/fibonacci-word.c create mode 100644 Task/Fibonacci-word/Clojure/fibonacci-word.clj create mode 100644 Task/Fibonacci-word/D/fibonacci-word.d create mode 100644 Task/Fibonacci-word/Go/fibonacci-word.go create mode 100644 Task/Fibonacci-word/Haskell/fibonacci-word.hs create mode 100644 Task/Fibonacci-word/Icon/fibonacci-word.icon create mode 100644 Task/Fibonacci-word/J/fibonacci-word-1.j create mode 100644 Task/Fibonacci-word/J/fibonacci-word-2.j create mode 100644 Task/Fibonacci-word/J/fibonacci-word-3.j create mode 100644 Task/Fibonacci-word/Java/fibonacci-word.java create mode 100644 Task/Fibonacci-word/Mathematica/fibonacci-word.math create mode 100644 Task/Fibonacci-word/PARI-GP/fibonacci-word.pari create mode 100644 Task/Fibonacci-word/PL-I/fibonacci-word.pli create mode 100644 Task/Fibonacci-word/Pascal/fibonacci-word.pascal create mode 100644 Task/Fibonacci-word/Perl-6/fibonacci-word-1.pl6 create mode 100644 Task/Fibonacci-word/Perl-6/fibonacci-word-2.pl6 create mode 100644 Task/Fibonacci-word/Perl/fibonacci-word.pl create mode 100644 Task/Fibonacci-word/Python/fibonacci-word.py create mode 100644 Task/Fibonacci-word/R/fibonacci-word.r create mode 100644 Task/Fibonacci-word/README create mode 100644 Task/Fibonacci-word/REXX/fibonacci-word.rexx create mode 100644 Task/Fibonacci-word/Racket/fibonacci-word-1.rkt create mode 100644 Task/Fibonacci-word/Racket/fibonacci-word-2.rkt create mode 100644 Task/Fibonacci-word/Ruby/fibonacci-word.rb create mode 100644 Task/Fibonacci-word/Scala/fibonacci-word.scala create mode 100644 Task/Fibonacci-word/Seed7/fibonacci-word.seed7 create mode 100644 Task/Fibonacci-word/Tcl/fibonacci-word.tcl delete mode 100644 Task/File-IO/README delete mode 100644 Task/File-IO/REXX/file-io-1.rexx delete mode 100644 Task/File-IO/REXX/file-io-2.rexx rename Task/{File-IO => File-input-output}/00DESCRIPTION (100%) create mode 100644 Task/File-input-output/00META.yaml rename Task/{File-IO/ACL2/file-io.acl2 => File-input-output/ACL2/file-input-output.acl2} (100%) rename Task/{File-IO/ALGOL-68/file-io.alg => File-input-output/ALGOL-68/file-input-output.alg} (100%) rename Task/{File-IO/AWK/file-io.awk => File-input-output/AWK/file-input-output.awk} (100%) rename Task/{File-IO/Ada/file-io-1.ada => File-input-output/Ada/file-input-output-1.ada} (76%) rename Task/{File-IO/Ada/file-io-2.ada => File-input-output/Ada/file-input-output-2.ada} (86%) rename Task/{File-IO/Ada/file-io-3.ada => File-input-output/Ada/file-input-output-3.ada} (76%) rename Task/{File-IO/Ada/file-io-4.ada => File-input-output/Ada/file-input-output-4.ada} (75%) rename Task/{File-IO/Aime/file-io.aime => File-input-output/Aime/file-input-output.aime} (100%) rename Task/{File-IO/AppleScript/file-io.applescript => File-input-output/AppleScript/file-input-output.applescript} (100%) rename Task/{File-IO/AutoHotkey/file-io-1.ahk => File-input-output/AutoHotkey/file-input-output-1.ahk} (100%) rename Task/{File-IO/AutoHotkey/file-io-2.ahk => File-input-output/AutoHotkey/file-input-output-2.ahk} (100%) rename Task/{File-IO/AutoHotkey/file-io-3.ahk => File-input-output/AutoHotkey/file-input-output-3.ahk} (100%) rename Task/{File-IO/BASIC/file-io-1.basic => File-input-output/BASIC/file-input-output-1.basic} (100%) rename Task/{File-IO/BASIC/file-io-2.basic => File-input-output/BASIC/file-input-output-2.basic} (100%) rename Task/{File-IO/BBC-BASIC/file-io-1.bbc => File-input-output/BBC-BASIC/file-input-output-1.bbc} (100%) rename Task/{File-IO/BBC-BASIC/file-io-2.bbc => File-input-output/BBC-BASIC/file-input-output-2.bbc} (100%) rename Task/{File-IO/Babel/file-io.pb => File-input-output/Babel/file-input-output.pb} (73%) rename Task/{File-IO/Batch-File/file-io-1.bat => File-input-output/Batch-File/file-input-output-1.bat} (100%) rename Task/{File-IO/Batch-File/file-io-2.bat => File-input-output/Batch-File/file-input-output-2.bat} (100%) rename Task/{File-IO/Batch-File/file-io-3.bat => File-input-output/Batch-File/file-input-output-3.bat} (100%) rename Task/{File-IO/Befunge/file-io.bf => File-input-output/Befunge/file-input-output.bf} (100%) rename Task/{File-IO/Bracmat/file-io.bracmat => File-input-output/Bracmat/file-input-output.bracmat} (100%) rename Task/{File-IO/C++/file-io-1.cpp => File-input-output/C++/file-input-output-1.cpp} (100%) rename Task/{File-IO/C++/file-io-2.cpp => File-input-output/C++/file-input-output-2.cpp} (100%) rename Task/{File-IO/C++/file-io-3.cpp => File-input-output/C++/file-input-output-3.cpp} (100%) rename Task/{File-IO/C++/file-io-4.cpp => File-input-output/C++/file-input-output-4.cpp} (100%) rename Task/{File-IO/C/file-io-1.c => File-input-output/C/file-input-output-1.c} (100%) rename Task/{File-IO/C/file-io-2.c => File-input-output/C/file-input-output-2.c} (100%) rename Task/{File-IO/C/file-io-3.c => File-input-output/C/file-input-output-3.c} (100%) rename Task/{File-IO/COBOL/file-io-1.cobol => File-input-output/COBOL/file-input-output-1.cobol} (100%) rename Task/{File-IO/COBOL/file-io-2.cobol => File-input-output/COBOL/file-input-output-2.cobol} (100%) rename Task/{File-IO/COBOL/file-io-3.cobol => File-input-output/COBOL/file-input-output-3.cobol} (100%) rename Task/{File-IO/Clean/file-io-1.clean => File-input-output/Clean/file-input-output-1.clean} (100%) rename Task/{File-IO/Clean/file-io-2.clean => File-input-output/Clean/file-input-output-2.clean} (100%) rename Task/{File-IO/Clojure/file-io-1.clj => File-input-output/Clojure/file-input-output-1.clj} (100%) rename Task/{File-IO/Clojure/file-io-2.clj => File-input-output/Clojure/file-input-output-2.clj} (100%) rename Task/{File-IO/ColdFusion/file-io.cfm => File-input-output/ColdFusion/file-input-output.cfm} (100%) rename Task/{File-IO/Common-Lisp/file-io-1.lisp => File-input-output/Common-Lisp/file-input-output-1.lisp} (100%) rename Task/{File-IO/Common-Lisp/file-io-2.lisp => File-input-output/Common-Lisp/file-input-output-2.lisp} (100%) rename Task/{File-IO/D/file-io-1.d => File-input-output/D/file-input-output-1.d} (100%) create mode 100644 Task/File-input-output/D/file-input-output-2.d rename Task/{File-IO/D/file-io-2.d => File-input-output/D/file-input-output-3.d} (100%) rename Task/{File-IO/D/file-io-3.d => File-input-output/D/file-input-output-4.d} (100%) rename Task/{File-IO/Delphi/file-io-1.delphi => File-input-output/Delphi/file-input-output-1.delphi} (100%) rename Task/{File-IO/Delphi/file-io-2.delphi => File-input-output/Delphi/file-input-output-2.delphi} (100%) rename Task/{File-IO/Delphi/file-io-3.delphi => File-input-output/Delphi/file-input-output-3.delphi} (100%) rename Task/{File-IO/E/file-io.e => File-input-output/E/file-input-output.e} (100%) rename Task/{File-IO/Eiffel/file-io.e => File-input-output/Eiffel/file-input-output.e} (100%) rename Task/{File-IO/Erlang/file-io.erl => File-input-output/Erlang/file-input-output.erl} (100%) rename Task/{File-IO/Euphoria/file-io-1.euphoria => File-input-output/Euphoria/file-input-output-1.euphoria} (100%) rename Task/{File-IO/Euphoria/file-io-2.euphoria => File-input-output/Euphoria/file-input-output-2.euphoria} (100%) rename Task/{File-IO/Factor/file-io-1.factor => File-input-output/Factor/file-input-output-1.factor} (100%) rename Task/{File-IO/Factor/file-io-2.factor => File-input-output/Factor/file-input-output-2.factor} (100%) rename Task/{File-IO/Factor/file-io-3.factor => File-input-output/Factor/file-input-output-3.factor} (100%) rename Task/{File-IO/Forth/file-io.fth => File-input-output/Forth/file-input-output.fth} (100%) rename Task/{File-IO/Fortran/file-io.f => File-input-output/Fortran/file-input-output.f} (100%) rename Task/{File-IO/Frink/file-io.frink => File-input-output/Frink/file-input-output.frink} (100%) rename Task/{File-IO/GAP/file-io.gap => File-input-output/GAP/file-input-output.gap} (100%) rename Task/{File-IO/GML/file-io.gml => File-input-output/GML/file-input-output.gml} (60%) rename Task/{File-IO/GUISS/file-io.guiss => File-input-output/GUISS/file-input-output.guiss} (100%) rename Task/{File-IO/Go/file-io-1.go => File-input-output/Go/file-input-output-1.go} (100%) rename Task/{File-IO/Go/file-io-2.go => File-input-output/Go/file-input-output-2.go} (100%) rename Task/{File-IO/Groovy/file-io-1.groovy => File-input-output/Groovy/file-input-output-1.groovy} (100%) rename Task/{File-IO/Groovy/file-io-2.groovy => File-input-output/Groovy/file-input-output-2.groovy} (100%) rename Task/{File-IO/Groovy/file-io-3.groovy => File-input-output/Groovy/file-input-output-3.groovy} (100%) rename Task/{File-IO/Haskell/file-io.hs => File-input-output/Haskell/file-input-output.hs} (100%) rename Task/{File-IO/HicEst/file-io-1.hicest => File-input-output/HicEst/file-input-output-1.hicest} (100%) rename Task/{File-IO/HicEst/file-io-2.hicest => File-input-output/HicEst/file-input-output-2.hicest} (100%) rename Task/{File-IO/HicEst/file-io-3.hicest => File-input-output/HicEst/file-input-output-3.hicest} (100%) rename Task/{File-IO/IDL/file-io.idl => File-input-output/IDL/file-input-output.idl} (100%) rename Task/{File-IO/Icon/file-io.icon => File-input-output/Icon/file-input-output.icon} (100%) rename Task/{File-IO/Io/file-io.io => File-input-output/Io/file-input-output.io} (100%) rename Task/{File-IO/J/file-io-1.j => File-input-output/J/file-input-output-1.j} (100%) rename Task/{File-IO/J/file-io-2.j => File-input-output/J/file-input-output-2.j} (100%) rename Task/{File-IO/Java/file-io-1.java => File-input-output/Java/file-input-output-1.java} (100%) rename Task/{File-IO/Java/file-io-2.java => File-input-output/Java/file-input-output-2.java} (100%) rename Task/{File-IO/Java/file-io-3.java => File-input-output/Java/file-input-output-3.java} (100%) rename Task/{File-IO/Java/file-io-4.java => File-input-output/Java/file-input-output-4.java} (100%) rename Task/{File-IO/Java/file-io-5.java => File-input-output/Java/file-input-output-5.java} (100%) rename Task/{File-IO/JavaScript/file-io-1.js => File-input-output/JavaScript/file-input-output-1.js} (100%) rename Task/{File-IO/JavaScript/file-io-2.js => File-input-output/JavaScript/file-input-output-2.js} (100%) create mode 100644 Task/File-input-output/Julia/file-input-output-1.julia create mode 100644 Task/File-input-output/Julia/file-input-output-2.julia create mode 100644 Task/File-input-output/Julia/file-input-output-3.julia create mode 100644 Task/File-input-output/Julia/file-input-output-4.julia rename Task/{File-IO/K/file-io.k => File-input-output/K/file-input-output.k} (100%) rename Task/{File-IO/Lang5/file-io.lang5 => File-input-output/Lang5/file-input-output.lang5} (100%) rename Task/{File-IO/Liberty-BASIC/file-io.liberty => File-input-output/Liberty-BASIC/file-input-output.liberty} (100%) rename Task/{File-IO/Lisaac/file-io.lisaac => File-input-output/Lisaac/file-input-output.lisaac} (100%) rename Task/{File-IO/Logo/file-io.logo => File-input-output/Logo/file-input-output.logo} (100%) rename Task/{File-IO/Lua/file-io.lua => File-input-output/Lua/file-input-output.lua} (100%) rename Task/{File-IO/MAXScript/file-io.max => File-input-output/MAXScript/file-input-output.max} (100%) rename Task/{File-IO/Mathematica/file-io.math => File-input-output/Mathematica/file-input-output.math} (100%) rename Task/{File-IO/Mercury/file-io.mercury => File-input-output/Mercury/file-input-output.mercury} (100%) rename Task/{File-IO/Modula-3/file-io.mod3 => File-input-output/Modula-3/file-input-output.mod3} (100%) rename Task/{File-IO/NetRexx/file-io.netrexx => File-input-output/NetRexx/file-input-output.netrexx} (100%) rename Task/{File-IO/OCaml/file-io-1.ocaml => File-input-output/OCaml/file-input-output-1.ocaml} (100%) rename Task/{File-IO/OCaml/file-io-2.ocaml => File-input-output/OCaml/file-input-output-2.ocaml} (100%) rename Task/{File-IO/Objeck/file-io.objeck => File-input-output/Objeck/file-input-output.objeck} (100%) rename Task/{File-IO/Object-Pascal/file-io.object => File-input-output/Object-Pascal/file-input-output.object} (100%) create mode 100644 Task/File-input-output/Objective-C/file-input-output-1.m rename Task/{File-IO/Objective-C/file-io.m => File-input-output/Objective-C/file-input-output-2.m} (100%) create mode 100644 Task/File-input-output/Octave/file-input-output.octave rename Task/{File-IO/OpenEdge-Progress/file-io.openedge => File-input-output/OpenEdge-Progress/file-input-output.openedge} (100%) rename Task/{File-IO/Oz/file-io.oz => File-input-output/Oz/file-input-output.oz} (100%) rename Task/{File-IO/PARI-GP/file-io.pari => File-input-output/PARI-GP/file-input-output.pari} (100%) rename Task/{File-IO/PHP/file-io-1.php => File-input-output/PHP/file-input-output-1.php} (100%) rename Task/{File-IO/PHP/file-io-2.php => File-input-output/PHP/file-input-output-2.php} (100%) rename Task/{File-IO/PL-I/file-io.pli => File-input-output/PL-I/file-input-output.pli} (100%) rename Task/{File-IO/Perl-6/file-io-1.pl6 => File-input-output/Perl-6/file-input-output-1.pl6} (100%) rename Task/{File-IO/Perl-6/file-io-2.pl6 => File-input-output/Perl-6/file-input-output-2.pl6} (100%) rename Task/{File-IO/Perl/file-io.pl => File-input-output/Perl/file-input-output.pl} (100%) rename Task/{File-IO/PicoLisp/file-io-1.l => File-input-output/PicoLisp/file-input-output-1.l} (100%) rename Task/{File-IO/PicoLisp/file-io-2.l => File-input-output/PicoLisp/file-input-output-2.l} (100%) rename Task/{File-IO/Pop11/file-io-1.pop11 => File-input-output/Pop11/file-input-output-1.pop11} (100%) rename Task/{File-IO/Pop11/file-io-2.pop11 => File-input-output/Pop11/file-input-output-2.pop11} (100%) rename Task/{File-IO/PowerShell/file-io-1.psh => File-input-output/PowerShell/file-input-output-1.psh} (100%) rename Task/{File-IO/PowerShell/file-io-2.psh => File-input-output/PowerShell/file-input-output-2.psh} (100%) rename Task/{File-IO/PureBasic/file-io-1.purebasic => File-input-output/PureBasic/file-input-output-1.purebasic} (100%) rename Task/{File-IO/PureBasic/file-io-2.purebasic => File-input-output/PureBasic/file-input-output-2.purebasic} (100%) rename Task/{File-IO/PureBasic/file-io-3.purebasic => File-input-output/PureBasic/file-input-output-3.purebasic} (100%) rename Task/{File-IO/Python/file-io-1.py => File-input-output/Python/file-input-output-1.py} (100%) rename Task/{File-IO/Python/file-io-2.py => File-input-output/Python/file-input-output-2.py} (100%) rename Task/{File-IO/Python/file-io-3.py => File-input-output/Python/file-input-output-3.py} (100%) rename Task/{File-IO/Python/file-io-4.py => File-input-output/Python/file-input-output-4.py} (100%) rename Task/{File-IO/R/file-io-1.r => File-input-output/R/file-input-output-1.r} (100%) rename Task/{File-IO/R/file-io-2.r => File-input-output/R/file-input-output-2.r} (100%) rename Task/{File-IO/R/file-io-3.r => File-input-output/R/file-input-output-3.r} (100%) create mode 100644 Task/File-input-output/README rename Task/{File-IO/REALbasic/file-io.realbasic => File-input-output/REALbasic/file-input-output.realbasic} (100%) rename Task/{File-IO/REBOL/file-io.rebol => File-input-output/REBOL/file-input-output.rebol} (100%) create mode 100644 Task/File-input-output/REXX/file-input-output-1.rexx rename Task/{File-IO/REXX/file-io-3.rexx => File-input-output/REXX/file-input-output-2.rexx} (100%) rename Task/{File-IO/Racket/file-io.rkt => File-input-output/Racket/file-input-output.rkt} (100%) rename Task/{File-IO/RapidQ/file-io-1.rapidq => File-input-output/RapidQ/file-input-output-1.rapidq} (100%) rename Task/{File-IO/RapidQ/file-io-2.rapidq => File-input-output/RapidQ/file-input-output-2.rapidq} (100%) rename Task/{File-IO/Raven/file-io.raven => File-input-output/Raven/file-input-output.raven} (100%) rename Task/{File-IO/Retro/file-io.retro => File-input-output/Retro/file-input-output.retro} (100%) rename Task/{File-IO/Ruby/file-io-1.rb => File-input-output/Ruby/file-input-output-1.rb} (100%) rename Task/{File-IO/Ruby/file-io-2.rb => File-input-output/Ruby/file-input-output-2.rb} (100%) rename Task/{File-IO/Ruby/file-io-3.rb => File-input-output/Ruby/file-input-output-3.rb} (100%) rename Task/{File-IO/Run-BASIC/file-io.run => File-input-output/Run-BASIC/file-input-output.run} (100%) rename Task/{File-IO/Rust/file-io.rust => File-input-output/Rust/file-input-output.rust} (100%) rename Task/{File-IO/SNOBOL4/file-io.sno => File-input-output/SNOBOL4/file-input-output.sno} (100%) rename Task/{File-IO/Scala/file-io.scala => File-input-output/Scala/file-input-output.scala} (68%) rename Task/{File-IO/Scheme/file-io.ss => File-input-output/Scheme/file-input-output.ss} (100%) rename Task/{File-IO/Seed7/file-io.seed7 => File-input-output/Seed7/file-input-output.seed7} (100%) rename Task/{File-IO/Slate/file-io.slate => File-input-output/Slate/file-input-output.slate} (100%) rename Task/{File-IO/Smalltalk/file-io.st => File-input-output/Smalltalk/file-input-output.st} (100%) rename Task/{File-IO/Standard-ML/file-io.ml => File-input-output/Standard-ML/file-input-output.ml} (100%) rename Task/{File-IO/Tcl/file-io-1.tcl => File-input-output/Tcl/file-input-output-1.tcl} (100%) rename Task/{File-IO/Tcl/file-io-2.tcl => File-input-output/Tcl/file-input-output-2.tcl} (100%) rename Task/{File-IO/Tcl/file-io-3.tcl => File-input-output/Tcl/file-input-output-3.tcl} (100%) rename Task/{File-IO/Tcl/file-io-4.tcl => File-input-output/Tcl/file-input-output-4.tcl} (100%) rename Task/{File-IO/Tcl/file-io-5.tcl => File-input-output/Tcl/file-input-output-5.tcl} (100%) rename Task/{File-IO/Toka/file-io-1.toka => File-input-output/Toka/file-input-output-1.toka} (100%) rename Task/{File-IO/Toka/file-io-2.toka => File-input-output/Toka/file-input-output-2.toka} (100%) rename Task/{File-IO/Toka/file-io-3.toka => File-input-output/Toka/file-input-output-3.toka} (100%) rename Task/{File-IO/UNIX-Shell/file-io-1.sh => File-input-output/UNIX-Shell/file-input-output-1.sh} (100%) rename Task/{File-IO/UNIX-Shell/file-io-2.sh => File-input-output/UNIX-Shell/file-input-output-2.sh} (100%) rename Task/{File-IO/UNIX-Shell/file-io-3.sh => File-input-output/UNIX-Shell/file-input-output-3.sh} (100%) rename Task/{File-IO/Ursala/file-io.ursala => File-input-output/Ursala/file-input-output.ursala} (100%) rename Task/{File-IO/VBScript/file-io.vb => File-input-output/VBScript/file-input-output.vb} (100%) rename Task/{File-IO/Vedit-macro-language/file-io.vedit => File-input-output/Vedit-macro-language/file-input-output.vedit} (100%) rename Task/{File-IO/Visual-Basic-.NET/file-io.visual => File-input-output/Visual-Basic-.NET/file-input-output.visual} (100%) rename Task/{File-IO/XPL0/file-io.xpl0 => File-input-output/XPL0/file-input-output.xpl0} (100%) create mode 100644 Task/Find-the-last-Sunday-of-each-month/00DESCRIPTION create mode 100644 Task/Find-the-last-Sunday-of-each-month/00META.yaml create mode 100644 Task/Find-the-last-Sunday-of-each-month/AutoHotkey/find-the-last-sunday-of-each-month.ahk create mode 100644 Task/Find-the-last-Sunday-of-each-month/BBC-BASIC/find-the-last-sunday-of-each-month.bbc create mode 100644 Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-1.cpp create mode 100644 Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-2.cpp create mode 100644 Task/Find-the-last-Sunday-of-each-month/Clojure/find-the-last-sunday-of-each-month.clj create mode 100644 Task/Find-the-last-Sunday-of-each-month/D/find-the-last-sunday-of-each-month.d create mode 100644 Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl create mode 100644 Task/Find-the-last-Sunday-of-each-month/FBSL/find-the-last-sunday-of-each-month.fbsl create mode 100644 Task/Find-the-last-Sunday-of-each-month/Go/find-the-last-sunday-of-each-month.go create mode 100644 Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-1.groovy create mode 100644 Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-2.groovy create mode 100644 Task/Find-the-last-Sunday-of-each-month/Icon/find-the-last-sunday-of-each-month.icon create mode 100644 Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-1.j create mode 100644 Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-2.j create mode 100644 Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-1.java create mode 100644 Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-2.java create mode 100644 Task/Find-the-last-Sunday-of-each-month/Mathematica/find-the-last-sunday-of-each-month.math create mode 100644 Task/Find-the-last-Sunday-of-each-month/OCaml/find-the-last-sunday-of-each-month.ocaml create mode 100644 Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 create mode 100644 Task/Find-the-last-Sunday-of-each-month/Perl/find-the-last-sunday-of-each-month.pl create mode 100644 Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-1.l create mode 100644 Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-2.l create mode 100644 Task/Find-the-last-Sunday-of-each-month/Python/find-the-last-sunday-of-each-month.py create mode 100644 Task/Find-the-last-Sunday-of-each-month/README create mode 100644 Task/Find-the-last-Sunday-of-each-month/REBOL/find-the-last-sunday-of-each-month.rebol create mode 100644 Task/Find-the-last-Sunday-of-each-month/REXX/find-the-last-sunday-of-each-month.rexx create mode 100644 Task/Find-the-last-Sunday-of-each-month/Racket/find-the-last-sunday-of-each-month.rkt create mode 100644 Task/Find-the-last-Sunday-of-each-month/Ruby/find-the-last-sunday-of-each-month.rb create mode 100644 Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-1.scala create mode 100644 Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-2.scala create mode 100644 Task/Find-the-last-Sunday-of-each-month/Seed7/find-the-last-sunday-of-each-month.seed7 create mode 100644 Task/Find-the-last-Sunday-of-each-month/Tcl/find-the-last-sunday-of-each-month.tcl create mode 100644 Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vb create mode 100644 Task/Flipping-bits-game/00DESCRIPTION create mode 100644 Task/Flipping-bits-game/00META.yaml create mode 100644 Task/Flipping-bits-game/Ada/flipping-bits-game.ada create mode 100644 Task/Flipping-bits-game/AutoHotkey/flipping-bits-game.ahk create mode 100644 Task/Flipping-bits-game/C++/flipping-bits-game.cpp create mode 100644 Task/Flipping-bits-game/C/flipping-bits-game.c create mode 100644 Task/Flipping-bits-game/D/flipping-bits-game.d create mode 100644 Task/Flipping-bits-game/Fortran/flipping-bits-game.f create mode 100644 Task/Flipping-bits-game/Go/flipping-bits-game.go create mode 100644 Task/Flipping-bits-game/Haskell/flipping-bits-game.hs create mode 100644 Task/Flipping-bits-game/J/flipping-bits-game-1.j create mode 100644 Task/Flipping-bits-game/J/flipping-bits-game-2.j create mode 100644 Task/Flipping-bits-game/MATLAB/flipping-bits-game.m create mode 100644 Task/Flipping-bits-game/PL-I/flipping-bits-game.pli create mode 100644 Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 create mode 100644 Task/Flipping-bits-game/Perl/flipping-bits-game.pl create mode 100644 Task/Flipping-bits-game/Python/flipping-bits-game.py create mode 100644 Task/Flipping-bits-game/README create mode 100644 Task/Flipping-bits-game/REXX/flipping-bits-game.rexx create mode 100644 Task/Flipping-bits-game/Racket/flipping-bits-game.rkt create mode 100644 Task/Flipping-bits-game/Ruby/flipping-bits-game.rb create mode 100644 Task/Flipping-bits-game/Tcl/flipping-bits-game.tcl create mode 100644 Task/Fractran/00DESCRIPTION create mode 100644 Task/Fractran/Ada/fractran.ada create mode 100644 Task/Fractran/AutoHotkey/fractran.ahk create mode 100644 Task/Fractran/Bracmat/fractran.bracmat create mode 100644 Task/Fractran/C++/fractran.cpp create mode 100644 Task/Fractran/C/fractran.c create mode 100644 Task/Fractran/Common-Lisp/fractran.lisp create mode 100644 Task/Fractran/D/fractran-1.d create mode 100644 Task/Fractran/D/fractran-2.d create mode 100644 Task/Fractran/Go/fractran-1.go create mode 100644 Task/Fractran/Go/fractran-2.go create mode 100644 Task/Fractran/Haskell/fractran.hs create mode 100644 Task/Fractran/Icon/fractran.icon create mode 100644 Task/Fractran/J/fractran-1.j create mode 100644 Task/Fractran/J/fractran-2.j create mode 100644 Task/Fractran/Java/fractran.java create mode 100644 Task/Fractran/JavaScript/fractran.js create mode 100644 Task/Fractran/Mathematica/fractran.math create mode 100644 Task/Fractran/Perl-6/fractran-1.pl6 create mode 100644 Task/Fractran/Perl-6/fractran-2.pl6 create mode 100644 Task/Fractran/Perl/fractran.pl create mode 100644 Task/Fractran/Python/fractran-1.py create mode 100644 Task/Fractran/Python/fractran-2.py create mode 100644 Task/Fractran/README create mode 100644 Task/Fractran/REXX/fractran-1.rexx create mode 100644 Task/Fractran/REXX/fractran-2.rexx create mode 100644 Task/Fractran/Racket/fractran.rkt create mode 100644 Task/Fractran/Ruby/fractran.rb create mode 100644 Task/Fractran/Seed7/fractran-1.seed7 create mode 100644 Task/Fractran/Seed7/fractran-2.seed7 create mode 100644 Task/Fractran/Tcl/fractran-1.tcl create mode 100644 Task/Fractran/Tcl/fractran-2.tcl create mode 100644 Task/Gaussian-elimination/00DESCRIPTION create mode 100644 Task/Gaussian-elimination/00META.yaml create mode 100644 Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-1.alg create mode 100644 Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-2.alg create mode 100644 Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-3.alg create mode 100644 Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-4.alg create mode 100644 Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-5.alg create mode 100644 Task/Gaussian-elimination/C/gaussian-elimination.c create mode 100644 Task/Gaussian-elimination/D/gaussian-elimination.d create mode 100644 Task/Gaussian-elimination/Fortran/gaussian-elimination.f create mode 100644 Task/Gaussian-elimination/Go/gaussian-elimination.go create mode 100644 Task/Gaussian-elimination/J/gaussian-elimination.j create mode 100644 Task/Gaussian-elimination/Julia/gaussian-elimination.julia create mode 100644 Task/Gaussian-elimination/MATLAB/gaussian-elimination.m create mode 100644 Task/Gaussian-elimination/Mathematica/gaussian-elimination.math create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml create mode 100644 Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml create mode 100644 Task/Gaussian-elimination/PARI-GP/gaussian-elimination.pari create mode 100644 Task/Gaussian-elimination/PHP/gaussian-elimination.php create mode 100644 Task/Gaussian-elimination/PL-I/gaussian-elimination.pli create mode 100644 Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 create mode 100644 Task/Gaussian-elimination/Perl/gaussian-elimination.pl create mode 100644 Task/Gaussian-elimination/Python/gaussian-elimination.py create mode 100644 Task/Gaussian-elimination/README create mode 100644 Task/Gaussian-elimination/REXX/gaussian-elimination-1.rexx create mode 100644 Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx create mode 100644 Task/Gaussian-elimination/Racket/gaussian-elimination-1.rkt create mode 100644 Task/Gaussian-elimination/Racket/gaussian-elimination-2.rkt create mode 100644 Task/Gaussian-elimination/Ruby/gaussian-elimination.rb create mode 100644 Task/Gaussian-elimination/Tcl/gaussian-elimination.tcl create mode 100644 Task/Generate-Chess960-starting-position/00DESCRIPTION create mode 100644 Task/Generate-Chess960-starting-position/AutoHotkey/generate-chess960-starting-position.ahk create mode 100644 Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp create mode 100644 Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d create mode 100644 Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d create mode 100644 Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d create mode 100644 Task/Generate-Chess960-starting-position/Go/generate-chess960-starting-position.go create mode 100644 Task/Generate-Chess960-starting-position/Haskell/generate-chess960-starting-position.hs create mode 100644 Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-1.j create mode 100644 Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-2.j create mode 100644 Task/Generate-Chess960-starting-position/Java/generate-chess960-starting-position.java create mode 100644 Task/Generate-Chess960-starting-position/Objeck/generate-chess960-starting-position.objeck create mode 100644 Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-1.pl6 create mode 100644 Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-2.pl6 create mode 100644 Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 create mode 100644 Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 create mode 100644 Task/Generate-Chess960-starting-position/Perl/generate-chess960-starting-position.pl create mode 100644 Task/Generate-Chess960-starting-position/PicoLisp/generate-chess960-starting-position.l create mode 100644 Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-1.py create mode 100644 Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-2.py create mode 100644 Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-3.py create mode 100644 Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-4.py create mode 100644 Task/Generate-Chess960-starting-position/README create mode 100644 Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-1.rexx create mode 100644 Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-2.rexx create mode 100644 Task/Generate-Chess960-starting-position/Racket/generate-chess960-starting-position.rkt create mode 100644 Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-1.rb create mode 100644 Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-2.rb create mode 100644 Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-3.rb create mode 100644 Task/Generate-Chess960-starting-position/Seed7/generate-chess960-starting-position.seed7 create mode 100644 Task/Generate-Chess960-starting-position/Tcl/generate-chess960-starting-position.tcl create mode 100644 Task/Generate-lower-case-ASCII-alphabet/00DESCRIPTION create mode 100644 Task/Generate-lower-case-ASCII-alphabet/00META.yaml create mode 100644 Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-1.alg create mode 100644 Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-2.alg create mode 100644 Task/Generate-lower-case-ASCII-alphabet/ATS/generate-lower-case-ascii-alphabet.ats create mode 100644 Task/Generate-lower-case-ASCII-alphabet/AWK/generate-lower-case-ascii-alphabet.awk create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-1.ada create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-2.ada create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-3.ada create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-1.applesoft create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-2.applesoft create mode 100644 Task/Generate-lower-case-ASCII-alphabet/AutoHotkey/generate-lower-case-ascii-alphabet.ahk create mode 100644 Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Bracmat/generate-lower-case-ascii-alphabet.bracmat create mode 100644 Task/Generate-lower-case-ASCII-alphabet/C++/generate-lower-case-ascii-alphabet.cpp create mode 100644 Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs create mode 100644 Task/Generate-lower-case-ASCII-alphabet/C/generate-lower-case-ascii-alphabet.c create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Clojure/generate-lower-case-ascii-alphabet.clj create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp create mode 100644 Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-1.d create mode 100644 Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-2.d create mode 100644 Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-3.d create mode 100644 Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-4.d create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Delphi/generate-lower-case-ascii-alphabet.delphi create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Factor/generate-lower-case-ascii-alphabet.factor create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Fortran/generate-lower-case-ascii-alphabet.f create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Go/generate-lower-case-ascii-alphabet.go create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-1.groovy create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-2.groovy create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Icon/generate-lower-case-ascii-alphabet.icon create mode 100644 Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet.j create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Java/generate-lower-case-ascii-alphabet.java create mode 100644 Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet.js create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet.logo create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Mathematica/generate-lower-case-ascii-alphabet.math create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Mercury/generate-lower-case-ascii-alphabet.mercury create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PHP/generate-lower-case-ascii-alphabet.php create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-1.pli create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-2.pli create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Perl/generate-lower-case-ascii-alphabet.pl create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PicoLisp/generate-lower-case-ascii-alphabet.l create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Prolog/generate-lower-case-ascii-alphabet.pro create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Python/generate-lower-case-ascii-alphabet.py create mode 100644 Task/Generate-lower-case-ASCII-alphabet/README create mode 100644 Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-1.rexx create mode 100644 Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-2.rexx create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Racket/generate-lower-case-ascii-alphabet.rkt create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ruby/generate-lower-case-ascii-alphabet.rb create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Scala/generate-lower-case-ascii-alphabet.scala create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Scheme/generate-lower-case-ascii-alphabet.ss create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Standard-ML/generate-lower-case-ascii-alphabet.ml create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-1.tcl create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-2.tcl create mode 100644 Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-1.sh create mode 100644 Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-2.sh create mode 100644 Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-3.sh create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-1.vim create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-2.vim create mode 100644 Task/Hash-join/00DESCRIPTION create mode 100644 Task/Hash-join/Bracmat/hash-join.bracmat create mode 100644 Task/Hash-join/C-sharp/hash-join.cs create mode 100644 Task/Hash-join/Clojure/hash-join.clj create mode 100644 Task/Hash-join/Common-Lisp/hash-join.lisp create mode 100644 Task/Hash-join/D/hash-join.d create mode 100644 Task/Hash-join/Deja-Vu/hash-join.djv create mode 100644 Task/Hash-join/Erlang/hash-join.erl create mode 100644 Task/Hash-join/Go/hash-join.go create mode 100644 Task/Hash-join/Groovy/hash-join-1.groovy create mode 100644 Task/Hash-join/Groovy/hash-join-2.groovy create mode 100644 Task/Hash-join/Groovy/hash-join-3.groovy create mode 100644 Task/Hash-join/Haskell/hash-join-1.hs create mode 100644 Task/Hash-join/Haskell/hash-join-2.hs create mode 100644 Task/Hash-join/J/hash-join-1.j create mode 100644 Task/Hash-join/J/hash-join-2.j create mode 100644 Task/Hash-join/J/hash-join-3.j create mode 100644 Task/Hash-join/Mathematica/hash-join.math create mode 100644 Task/Hash-join/OCaml/hash-join.ocaml create mode 100644 Task/Hash-join/Oberon-2/hash-join.oberon-2 create mode 100644 Task/Hash-join/PHP/hash-join.php create mode 100644 Task/Hash-join/Perl-6/hash-join.pl6 create mode 100644 Task/Hash-join/Perl/hash-join.pl create mode 100644 Task/Hash-join/Python/hash-join.py create mode 100644 Task/Hash-join/README create mode 100644 Task/Hash-join/REXX/hash-join.rexx create mode 100644 Task/Hash-join/Racket/hash-join.rkt create mode 100644 Task/Hash-join/Ruby/hash-join.rb create mode 100644 Task/Hash-join/SQL/hash-join-1.sql create mode 100644 Task/Hash-join/SQL/hash-join-2.sql create mode 100644 Task/Hash-join/Scala/hash-join.scala create mode 100644 Task/Hash-join/Scheme/hash-join.ss create mode 100644 Task/Hash-join/TXR/hash-join.txr create mode 100644 Task/Hash-join/Tcl/hash-join.tcl create mode 100644 Task/Hello-world-Newbie/00DESCRIPTION create mode 100644 Task/Hello-world-Newbie/ALGOL-68/hello-world-newbie.alg create mode 100644 Task/Hello-world-Newbie/AWK/hello-world-newbie.awk create mode 100644 Task/Hello-world-Newbie/AutoHotkey/hello-world-newbie.ahk create mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-1.cobol create mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-2.cobol create mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-3.cobol create mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-4.cobol create mode 100644 Task/Hello-world-Newbie/Clojure/hello-world-newbie-1.clj create mode 100644 Task/Hello-world-Newbie/Clojure/hello-world-newbie-2.clj create mode 100644 Task/Hello-world-Newbie/Clojure/hello-world-newbie-3.clj create mode 100644 Task/Hello-world-Newbie/D/hello-world-newbie.d create mode 100644 Task/Hello-world-Newbie/Erlang/hello-world-newbie.erl create mode 100644 Task/Hello-world-Newbie/Haskell/hello-world-newbie-1.hs create mode 100644 Task/Hello-world-Newbie/Haskell/hello-world-newbie-2.hs create mode 100644 Task/Hello-world-Newbie/Haskell/hello-world-newbie-3.hs create mode 100644 Task/Hello-world-Newbie/Haskell/hello-world-newbie-4.hs create mode 100644 Task/Hello-world-Newbie/J/hello-world-newbie.j create mode 100644 Task/Hello-world-Newbie/Locomotive-Basic/hello-world-newbie.locomotive create mode 100644 Task/Hello-world-Newbie/OCaml/hello-world-newbie-1.ocaml create mode 100644 Task/Hello-world-Newbie/OCaml/hello-world-newbie-2.ocaml create mode 100644 Task/Hello-world-Newbie/OCaml/hello-world-newbie-3.ocaml create mode 100644 Task/Hello-world-Newbie/PARI-GP/hello-world-newbie.pari create mode 100644 Task/Hello-world-Newbie/Perl/hello-world-newbie.pl create mode 100644 Task/Hello-world-Newbie/Python/hello-world-newbie.py create mode 100644 Task/Hello-world-Newbie/README create mode 100644 Task/Hello-world-Newbie/REXX/hello-world-newbie.rexx create mode 100644 Task/Hello-world-Newbie/Rust/hello-world-newbie.rust create mode 100644 Task/Hello-world-Newbie/Scala/hello-world-newbie.scala create mode 100644 Task/Hello-world-Newbie/TI-83-BASIC/hello-world-newbie.ti-83 create mode 100644 Task/Hello-world-Newbie/Tcl/hello-world-newbie.tcl create mode 100644 Task/Hello-world-Newbie/ZX-Spectrum-Basic/hello-world-newbie.zx create mode 100644 Task/Heronian-triangles/00DESCRIPTION create mode 100644 Task/Heronian-triangles/D/heronian-triangles.d create mode 100644 Task/Heronian-triangles/Haskell/heronian-triangles.hs create mode 100644 Task/Heronian-triangles/J/heronian-triangles-1.j create mode 100644 Task/Heronian-triangles/J/heronian-triangles-2.j create mode 100644 Task/Heronian-triangles/Java/heronian-triangles-1.java create mode 100644 Task/Heronian-triangles/Java/heronian-triangles-2.java create mode 100644 Task/Heronian-triangles/JavaScript/heronian-triangles-1.js create mode 100644 Task/Heronian-triangles/JavaScript/heronian-triangles-2.js create mode 100644 Task/Heronian-triangles/Perl-6/heronian-triangles.pl6 create mode 100644 Task/Heronian-triangles/Perl/heronian-triangles.pl create mode 100644 Task/Heronian-triangles/PowerShell/heronian-triangles-1.psh create mode 100644 Task/Heronian-triangles/PowerShell/heronian-triangles-2.psh create mode 100644 Task/Heronian-triangles/Python/heronian-triangles.py create mode 100644 Task/Heronian-triangles/README create mode 100644 Task/Heronian-triangles/REXX/heronian-triangles.rexx create mode 100644 Task/Heronian-triangles/Racket/heronian-triangles.rkt create mode 100644 Task/Heronian-triangles/Ruby/heronian-triangles.rb create mode 100644 Task/Hickerson-series-of-almost-integers/00DESCRIPTION create mode 100644 Task/Hickerson-series-of-almost-integers/Bracmat/hickerson-series-of-almost-integers.bracmat create mode 100644 Task/Hickerson-series-of-almost-integers/C++/hickerson-series-of-almost-integers.cpp create mode 100644 Task/Hickerson-series-of-almost-integers/C/hickerson-series-of-almost-integers.c create mode 100644 Task/Hickerson-series-of-almost-integers/COBOL/hickerson-series-of-almost-integers.cobol create mode 100644 Task/Hickerson-series-of-almost-integers/Clojure/hickerson-series-of-almost-integers.clj create mode 100644 Task/Hickerson-series-of-almost-integers/D/hickerson-series-of-almost-integers.d create mode 100644 Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f create mode 100644 Task/Hickerson-series-of-almost-integers/Go/hickerson-series-of-almost-integers.go create mode 100644 Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-1.j create mode 100644 Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-2.j create mode 100644 Task/Hickerson-series-of-almost-integers/Mathematica/hickerson-series-of-almost-integers.math create mode 100644 Task/Hickerson-series-of-almost-integers/PARI-GP/hickerson-series-of-almost-integers.pari create mode 100644 Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-1.pli create mode 100644 Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-2.pli create mode 100644 Task/Hickerson-series-of-almost-integers/Perl-6/hickerson-series-of-almost-integers.pl6 create mode 100644 Task/Hickerson-series-of-almost-integers/Perl/hickerson-series-of-almost-integers.pl create mode 100644 Task/Hickerson-series-of-almost-integers/Python/hickerson-series-of-almost-integers.py create mode 100644 Task/Hickerson-series-of-almost-integers/README create mode 100644 Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers.rexx create mode 100644 Task/Hickerson-series-of-almost-integers/Racket/hickerson-series-of-almost-integers.rkt create mode 100644 Task/Hickerson-series-of-almost-integers/Ruby/hickerson-series-of-almost-integers.rb create mode 100644 Task/Hickerson-series-of-almost-integers/Seed7/hickerson-series-of-almost-integers.seed7 create mode 100644 Task/Hickerson-series-of-almost-integers/Tcl/hickerson-series-of-almost-integers.tcl create mode 100644 Task/IBAN/00DESCRIPTION create mode 100644 Task/IBAN/00META.yaml create mode 100644 Task/IBAN/Ada/iban-1.ada create mode 100644 Task/IBAN/Ada/iban-2.ada create mode 100644 Task/IBAN/Ada/iban-3.ada create mode 100644 Task/IBAN/AutoHotkey/iban.ahk create mode 100644 Task/IBAN/BBC-BASIC/iban.bbc create mode 100644 Task/IBAN/Bracmat/iban.bracmat create mode 100644 Task/IBAN/C++/iban.cpp create mode 100644 Task/IBAN/C-sharp/iban-1.cs create mode 100644 Task/IBAN/C-sharp/iban-2.cs create mode 100644 Task/IBAN/C/iban.c create mode 100644 Task/IBAN/COBOL/iban.cobol create mode 100644 Task/IBAN/Cache-ObjectScript/iban.cos create mode 100644 Task/IBAN/Clojure/iban.clj create mode 100644 Task/IBAN/Common-Lisp/iban.lisp create mode 100644 Task/IBAN/D/iban.d create mode 100644 Task/IBAN/Go/iban.go create mode 100644 Task/IBAN/Groovy/iban-1.groovy create mode 100644 Task/IBAN/Groovy/iban-2.groovy create mode 100644 Task/IBAN/Haskell/iban.hs create mode 100644 Task/IBAN/J/iban.j create mode 100644 Task/IBAN/Java/iban.java create mode 100644 Task/IBAN/MATLAB/iban-1.m create mode 100644 Task/IBAN/MATLAB/iban-2.m create mode 100644 Task/IBAN/Mathematica/iban-1.math create mode 100644 Task/IBAN/Mathematica/iban-2.math create mode 100644 Task/IBAN/Oberon-2/iban.oberon-2 create mode 100644 Task/IBAN/Perl-6/iban.pl6 create mode 100644 Task/IBAN/Perl/iban.pl create mode 100644 Task/IBAN/PicoLisp/iban.l create mode 100644 Task/IBAN/Python/iban.py create mode 100644 Task/IBAN/README create mode 100644 Task/IBAN/REXX/iban-1.rexx create mode 100644 Task/IBAN/REXX/iban-2.rexx create mode 100644 Task/IBAN/Racket/iban.rkt create mode 100644 Task/IBAN/Ruby/iban.rb create mode 100644 Task/IBAN/Scala/iban-1.scala create mode 100644 Task/IBAN/Scala/iban-2.scala create mode 100644 Task/IBAN/Seed7/iban.seed7 create mode 100644 Task/IBAN/Tcl/iban-1.tcl create mode 100644 Task/IBAN/Tcl/iban-2.tcl create mode 100644 Task/IBAN/UNIX-Shell/iban.sh create mode 100644 Task/Integer-overflow/00DESCRIPTION create mode 100644 Task/Integer-overflow/Ada/integer-overflow.ada create mode 100644 Task/Integer-overflow/AutoHotkey/integer-overflow.ahk create mode 100644 Task/Integer-overflow/C/integer-overflow.c create mode 100644 Task/Integer-overflow/Clojure/integer-overflow-1.clj create mode 100644 Task/Integer-overflow/Clojure/integer-overflow-2.clj create mode 100644 Task/Integer-overflow/D/integer-overflow.d create mode 100644 Task/Integer-overflow/Go/integer-overflow.go create mode 100644 Task/Integer-overflow/Haskell/integer-overflow.hs create mode 100644 Task/Integer-overflow/J/integer-overflow-1.j create mode 100644 Task/Integer-overflow/J/integer-overflow-2.j create mode 100644 Task/Integer-overflow/J/integer-overflow-3.j create mode 100644 Task/Integer-overflow/J/integer-overflow-4.j create mode 100644 Task/Integer-overflow/Java/integer-overflow.java create mode 100644 Task/Integer-overflow/Perl/integer-overflow.pl create mode 100644 Task/Integer-overflow/Python/integer-overflow-1.py create mode 100644 Task/Integer-overflow/Python/integer-overflow-2.py create mode 100644 Task/Integer-overflow/README create mode 100644 Task/Integer-overflow/REXX/integer-overflow.rexx create mode 100644 Task/Integer-overflow/Ruby/integer-overflow.rb create mode 100644 Task/Integer-overflow/Scala/integer-overflow.scala create mode 100644 Task/Integer-overflow/Seed7/integer-overflow.seed7 create mode 100644 Task/Integer-overflow/Tcl/integer-overflow.tcl create mode 100644 Task/Iterated-digits-squaring/00DESCRIPTION create mode 100644 Task/Iterated-digits-squaring/C++/iterated-digits-squaring.cpp create mode 100644 Task/Iterated-digits-squaring/C/iterated-digits-squaring.c create mode 100644 Task/Iterated-digits-squaring/D/iterated-digits-squaring-1.d create mode 100644 Task/Iterated-digits-squaring/D/iterated-digits-squaring-2.d create mode 100644 Task/Iterated-digits-squaring/D/iterated-digits-squaring-3.d create mode 100644 Task/Iterated-digits-squaring/D/iterated-digits-squaring-4.d create mode 100644 Task/Iterated-digits-squaring/Go/iterated-digits-squaring.go create mode 100644 Task/Iterated-digits-squaring/Haskell/iterated-digits-squaring.hs create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-1.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-2.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-3.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-4.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-5.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-7.j create mode 100644 Task/Iterated-digits-squaring/J/iterated-digits-squaring-8.j create mode 100644 Task/Iterated-digits-squaring/Java/iterated-digits-squaring.java create mode 100644 Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia create mode 100644 Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia create mode 100644 Task/Iterated-digits-squaring/Lua/iterated-digits-squaring.lua create mode 100644 Task/Iterated-digits-squaring/Mathematica/iterated-digits-squaring.math create mode 100644 Task/Iterated-digits-squaring/Oberon-2/iterated-digits-squaring.oberon-2 create mode 100644 Task/Iterated-digits-squaring/Pascal/iterated-digits-squaring.pascal create mode 100644 Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-1.pl6 create mode 100644 Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-2.pl6 create mode 100644 Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 create mode 100644 Task/Iterated-digits-squaring/Perl/iterated-digits-squaring.pl create mode 100644 Task/Iterated-digits-squaring/Python/iterated-digits-squaring-1.py create mode 100644 Task/Iterated-digits-squaring/Python/iterated-digits-squaring-2.py create mode 100644 Task/Iterated-digits-squaring/Python/iterated-digits-squaring-3.py create mode 100644 Task/Iterated-digits-squaring/Python/iterated-digits-squaring-4.py create mode 100644 Task/Iterated-digits-squaring/README create mode 100644 Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx create mode 100644 Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx create mode 100644 Task/Iterated-digits-squaring/Racket/iterated-digits-squaring.rkt create mode 100644 Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb create mode 100644 Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-1.tcl create mode 100644 Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-2.tcl create mode 100644 Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-3.tcl create mode 100644 Task/K-d-tree/00DESCRIPTION create mode 100644 Task/K-d-tree/C/k-d-tree.c create mode 100644 Task/K-d-tree/D/k-d-tree-1.d create mode 100644 Task/K-d-tree/D/k-d-tree-2.d create mode 100644 Task/K-d-tree/Go/k-d-tree.go create mode 100644 Task/K-d-tree/Haskell/k-d-tree.hs create mode 100644 Task/K-d-tree/J/k-d-tree-1.j create mode 100644 Task/K-d-tree/J/k-d-tree-2.j create mode 100644 Task/K-d-tree/J/k-d-tree-3.j create mode 100644 Task/K-d-tree/J/k-d-tree-4.j create mode 100644 Task/K-d-tree/J/k-d-tree-5.j create mode 100644 Task/K-d-tree/J/k-d-tree-6.j create mode 100644 Task/K-d-tree/J/k-d-tree-7.j create mode 100644 Task/K-d-tree/Perl-6/k-d-tree.pl6 create mode 100644 Task/K-d-tree/Python/k-d-tree.py create mode 100644 Task/K-d-tree/README create mode 100644 Task/K-d-tree/Racket/k-d-tree-1.rkt create mode 100644 Task/K-d-tree/Racket/k-d-tree-2.rkt create mode 100644 Task/K-d-tree/Racket/k-d-tree-3.rkt create mode 100644 Task/K-d-tree/Scala/k-d-tree-1.scala create mode 100644 Task/K-d-tree/Scala/k-d-tree-2.scala create mode 100644 Task/K-d-tree/Tcl/k-d-tree-1.tcl create mode 100644 Task/K-d-tree/Tcl/k-d-tree-2.tcl create mode 100644 Task/Left-factorials/00DESCRIPTION create mode 100644 Task/Left-factorials/00META.yaml create mode 100644 Task/Left-factorials/Bracmat/left-factorials.bracmat create mode 100644 Task/Left-factorials/C/left-factorials.c create mode 100644 Task/Left-factorials/D/left-factorials.d create mode 100644 Task/Left-factorials/Go/left-factorials.go create mode 100644 Task/Left-factorials/Haskell/left-factorials.hs create mode 100644 Task/Left-factorials/Icon/left-factorials.icon create mode 100644 Task/Left-factorials/J/left-factorials-1.j create mode 100644 Task/Left-factorials/J/left-factorials-2.j create mode 100644 Task/Left-factorials/Java/left-factorials.java create mode 100644 Task/Left-factorials/Julia/left-factorials.julia create mode 100644 Task/Left-factorials/Mathematica/left-factorials.math create mode 100644 Task/Left-factorials/PARI-GP/left-factorials.pari create mode 100644 Task/Left-factorials/PL-I/left-factorials.pli create mode 100644 Task/Left-factorials/Perl-6/left-factorials-1.pl6 create mode 100644 Task/Left-factorials/Perl-6/left-factorials-2.pl6 create mode 100644 Task/Left-factorials/Perl-6/left-factorials-3.pl6 create mode 100644 Task/Left-factorials/Perl/left-factorials.pl create mode 100644 Task/Left-factorials/Python/left-factorials.py create mode 100644 Task/Left-factorials/README create mode 100644 Task/Left-factorials/REXX/left-factorials.rexx create mode 100644 Task/Left-factorials/Racket/left-factorials.rkt create mode 100644 Task/Left-factorials/Ruby/left-factorials-1.rb create mode 100644 Task/Left-factorials/Ruby/left-factorials-2.rb create mode 100644 Task/Left-factorials/Ruby/left-factorials-3.rb create mode 100644 Task/Left-factorials/Seed7/left-factorials.seed7 create mode 100644 Task/Left-factorials/Tcl/left-factorials.tcl create mode 100644 Task/Longest-increasing-subsequence/00DESCRIPTION create mode 100644 Task/Longest-increasing-subsequence/AutoHotkey/longest-increasing-subsequence.ahk create mode 100644 Task/Longest-increasing-subsequence/C++/longest-increasing-subsequence.cpp create mode 100644 Task/Longest-increasing-subsequence/C/longest-increasing-subsequence.c create mode 100644 Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-1.clj create mode 100644 Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-2.clj create mode 100644 Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-1.lisp create mode 100644 Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-2.lisp create mode 100644 Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-3.lisp create mode 100644 Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-1.d create mode 100644 Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-2.d create mode 100644 Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-3.d create mode 100644 Task/Longest-increasing-subsequence/Deja-Vu/longest-increasing-subsequence.djv create mode 100644 Task/Longest-increasing-subsequence/Go/longest-increasing-subsequence.go create mode 100644 Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-1.hs create mode 100644 Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-2.hs create mode 100644 Task/Longest-increasing-subsequence/Icon/longest-increasing-subsequence.icon create mode 100644 Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-1.j create mode 100644 Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-2.j create mode 100644 Task/Longest-increasing-subsequence/Java/longest-increasing-subsequence.java create mode 100644 Task/Longest-increasing-subsequence/JavaScript/longest-increasing-subsequence.js create mode 100644 Task/Longest-increasing-subsequence/Lua/longest-increasing-subsequence.lua create mode 100644 Task/Longest-increasing-subsequence/Mathematica/longest-increasing-subsequence.math create mode 100644 Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-1.ocaml create mode 100644 Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-2.ocaml create mode 100644 Task/Longest-increasing-subsequence/Objective-C/longest-increasing-subsequence.m create mode 100644 Task/Longest-increasing-subsequence/PHP/longest-increasing-subsequence.php create mode 100644 Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-1.pl6 create mode 100644 Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 create mode 100644 Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-1.pl create mode 100644 Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-2.pl create mode 100644 Task/Longest-increasing-subsequence/Prolog/longest-increasing-subsequence.pro create mode 100644 Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py create mode 100644 Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py create mode 100644 Task/Longest-increasing-subsequence/README create mode 100644 Task/Longest-increasing-subsequence/Racket/longest-increasing-subsequence.rkt create mode 100644 Task/Longest-increasing-subsequence/Ruby/longest-increasing-subsequence.rb create mode 100644 Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence.scala create mode 100644 Task/Longest-increasing-subsequence/Scheme/longest-increasing-subsequence.ss create mode 100644 Task/Longest-increasing-subsequence/Standard-ML/longest-increasing-subsequence.ml create mode 100644 Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-1.tcl create mode 100644 Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-2.tcl create mode 100644 Task/Ludic-numbers/00DESCRIPTION create mode 100644 Task/Ludic-numbers/00META.yaml create mode 100644 Task/Ludic-numbers/AutoHotkey/ludic-numbers.ahk create mode 100644 Task/Ludic-numbers/C++/ludic-numbers.cpp create mode 100644 Task/Ludic-numbers/C/ludic-numbers.c create mode 100644 Task/Ludic-numbers/Clojure/ludic-numbers.clj create mode 100644 Task/Ludic-numbers/D/ludic-numbers-1.d create mode 100644 Task/Ludic-numbers/D/ludic-numbers-2.d create mode 100644 Task/Ludic-numbers/D/ludic-numbers-3.d create mode 100644 Task/Ludic-numbers/Eiffel/ludic-numbers-1.e create mode 100644 Task/Ludic-numbers/Eiffel/ludic-numbers-2.e create mode 100644 Task/Ludic-numbers/Go/ludic-numbers.go create mode 100644 Task/Ludic-numbers/Haskell/ludic-numbers-1.hs create mode 100644 Task/Ludic-numbers/Haskell/ludic-numbers-2.hs create mode 100644 Task/Ludic-numbers/Icon/ludic-numbers.icon create mode 100644 Task/Ludic-numbers/J/ludic-numbers-1.j create mode 100644 Task/Ludic-numbers/J/ludic-numbers-2.j create mode 100644 Task/Ludic-numbers/Java/ludic-numbers.java create mode 100644 Task/Ludic-numbers/Mathematica/ludic-numbers.math create mode 100644 Task/Ludic-numbers/PL-I/ludic-numbers.pli create mode 100644 Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 create mode 100644 Task/Ludic-numbers/Perl/ludic-numbers.pl create mode 100644 Task/Ludic-numbers/PicoLisp/ludic-numbers.l create mode 100644 Task/Ludic-numbers/Python/ludic-numbers-1.py create mode 100644 Task/Ludic-numbers/Python/ludic-numbers-2.py create mode 100644 Task/Ludic-numbers/README create mode 100644 Task/Ludic-numbers/REXX/ludic-numbers.rexx create mode 100644 Task/Ludic-numbers/Racket/ludic-numbers.rkt create mode 100644 Task/Ludic-numbers/Ruby/ludic-numbers.rb create mode 100644 Task/Ludic-numbers/Seed7/ludic-numbers.seed7 create mode 100644 Task/Ludic-numbers/Tcl/ludic-numbers.tcl create mode 100644 Task/Machine-code/00DESCRIPTION create mode 100644 Task/Machine-code/AutoHotkey/machine-code.ahk create mode 100644 Task/Machine-code/BBC-BASIC/machine-code.bbc create mode 100644 Task/Machine-code/C/machine-code.c create mode 100644 Task/Machine-code/Common-Lisp/machine-code.lisp create mode 100644 Task/Machine-code/D/machine-code.d create mode 100644 Task/Machine-code/PARI-GP/machine-code.pari create mode 100644 Task/Machine-code/Pascal/machine-code.pascal create mode 100644 Task/Machine-code/PureBasic/machine-code.purebasic create mode 100644 Task/Machine-code/Python/machine-code.py create mode 100644 Task/Machine-code/README create mode 100644 Task/Machine-code/Tcl/machine-code-1.tcl create mode 100644 Task/Machine-code/Tcl/machine-code-2.tcl create mode 100644 Task/Magic-squares-of-odd-order/00DESCRIPTION create mode 100644 Task/Magic-squares-of-odd-order/AWK/magic-squares-of-odd-order.awk create mode 100644 Task/Magic-squares-of-odd-order/Ada/magic-squares-of-odd-order.ada create mode 100644 Task/Magic-squares-of-odd-order/AutoHotkey/magic-squares-of-odd-order.ahk create mode 100644 Task/Magic-squares-of-odd-order/C++/magic-squares-of-odd-order.cpp create mode 100644 Task/Magic-squares-of-odd-order/C/magic-squares-of-odd-order.c create mode 100644 Task/Magic-squares-of-odd-order/Common-Lisp/magic-squares-of-odd-order.lisp create mode 100644 Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-1.d create mode 100644 Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-2.d create mode 100644 Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-3.d create mode 100644 Task/Magic-squares-of-odd-order/Go/magic-squares-of-odd-order.go create mode 100644 Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order.hs create mode 100644 Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-1.j create mode 100644 Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-2.j create mode 100644 Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-3.j create mode 100644 Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-4.j create mode 100644 Task/Magic-squares-of-odd-order/Java/magic-squares-of-odd-order.java create mode 100644 Task/Magic-squares-of-odd-order/Mathematica/magic-squares-of-odd-order.math create mode 100644 Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-1.maxima create mode 100644 Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-2.maxima create mode 100644 Task/Magic-squares-of-odd-order/PL-I/magic-squares-of-odd-order.pli create mode 100644 Task/Magic-squares-of-odd-order/Perl-6/magic-squares-of-odd-order.pl6 create mode 100644 Task/Magic-squares-of-odd-order/Python/magic-squares-of-odd-order.py create mode 100644 Task/Magic-squares-of-odd-order/README create mode 100644 Task/Magic-squares-of-odd-order/REXX/magic-squares-of-odd-order.rexx create mode 100644 Task/Magic-squares-of-odd-order/Racket/magic-squares-of-odd-order.rkt create mode 100644 Task/Magic-squares-of-odd-order/Ruby/magic-squares-of-odd-order.rb create mode 100644 Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust create mode 100644 Task/Magic-squares-of-odd-order/Seed7/magic-squares-of-odd-order.seed7 create mode 100644 Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-1.tcl create mode 100644 Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-2.tcl create mode 100644 Task/Make-directory-path/00DESCRIPTION create mode 100644 Task/Make-directory-path/00META.yaml create mode 100644 Task/Make-directory-path/Clojure/make-directory-path.clj create mode 100644 Task/Make-directory-path/Go/make-directory-path.go create mode 100644 Task/Make-directory-path/Java/make-directory-path.java create mode 100644 Task/Make-directory-path/JavaScript/make-directory-path.js create mode 100644 Task/Make-directory-path/Mathematica/make-directory-path.math create mode 100644 Task/Make-directory-path/Perl-6/make-directory-path.pl6 create mode 100644 Task/Make-directory-path/Python/make-directory-path-1.py create mode 100644 Task/Make-directory-path/Python/make-directory-path-2.py create mode 100644 Task/Make-directory-path/Python/make-directory-path-3.py create mode 100644 Task/Make-directory-path/README create mode 100644 Task/Make-directory-path/REXX/make-directory-path.rexx create mode 100644 Task/Make-directory-path/Racket/make-directory-path.rkt create mode 100644 Task/Make-directory-path/Ruby/make-directory-path.rb create mode 100644 Task/Make-directory-path/Scala/make-directory-path-1.scala create mode 100644 Task/Make-directory-path/Scala/make-directory-path-2.scala create mode 100644 Task/Make-directory-path/Tcl/make-directory-path.tcl create mode 100644 Task/Make-directory-path/UNIX-Shell/make-directory-path.sh create mode 100644 Task/Maximum-triangle-path-sum/00DESCRIPTION create mode 100644 Task/Maximum-triangle-path-sum/ALGOL-68/maximum-triangle-path-sum.alg create mode 100644 Task/Maximum-triangle-path-sum/Ada/maximum-triangle-path-sum.ada create mode 100644 Task/Maximum-triangle-path-sum/Bracmat/maximum-triangle-path-sum.bracmat create mode 100644 Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp create mode 100644 Task/Maximum-triangle-path-sum/C/maximum-triangle-path-sum.c create mode 100644 Task/Maximum-triangle-path-sum/Common-Lisp/maximum-triangle-path-sum.lisp create mode 100644 Task/Maximum-triangle-path-sum/D/maximum-triangle-path-sum.d create mode 100644 Task/Maximum-triangle-path-sum/Go/maximum-triangle-path-sum.go create mode 100644 Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs create mode 100644 Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-1.j create mode 100644 Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-2.j create mode 100644 Task/Maximum-triangle-path-sum/Java/maximum-triangle-path-sum.java create mode 100644 Task/Maximum-triangle-path-sum/Mathematica/maximum-triangle-path-sum.math create mode 100644 Task/Maximum-triangle-path-sum/PARI-GP/maximum-triangle-path-sum.pari create mode 100644 Task/Maximum-triangle-path-sum/Pascal/maximum-triangle-path-sum.pascal create mode 100644 Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-1.pl6 create mode 100644 Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-2.pl6 create mode 100644 Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-3.pl6 create mode 100644 Task/Maximum-triangle-path-sum/Perl/maximum-triangle-path-sum.pl create mode 100644 Task/Maximum-triangle-path-sum/Prolog/maximum-triangle-path-sum.pro create mode 100644 Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-1.py create mode 100644 Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-2.py create mode 100644 Task/Maximum-triangle-path-sum/README create mode 100644 Task/Maximum-triangle-path-sum/REXX/maximum-triangle-path-sum.rexx create mode 100644 Task/Maximum-triangle-path-sum/Racket/maximum-triangle-path-sum.rkt create mode 100644 Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb create mode 100644 Task/Maximum-triangle-path-sum/Scala/maximum-triangle-path-sum.scala create mode 100644 Task/Maximum-triangle-path-sum/Tcl/maximum-triangle-path-sum.tcl create mode 100644 Task/Move-to-front-algorithm/00DESCRIPTION create mode 100644 Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg create mode 100644 Task/Move-to-front-algorithm/Ada/move-to-front-algorithm.ada create mode 100644 Task/Move-to-front-algorithm/C++/move-to-front-algorithm.cpp create mode 100644 Task/Move-to-front-algorithm/C/move-to-front-algorithm.c create mode 100644 Task/Move-to-front-algorithm/Common-Lisp/move-to-front-algorithm.lisp create mode 100644 Task/Move-to-front-algorithm/D/move-to-front-algorithm.d create mode 100644 Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go create mode 100644 Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs create mode 100644 Task/Move-to-front-algorithm/Icon/move-to-front-algorithm.icon create mode 100644 Task/Move-to-front-algorithm/J/move-to-front-algorithm-1.j create mode 100644 Task/Move-to-front-algorithm/J/move-to-front-algorithm-2.j create mode 100644 Task/Move-to-front-algorithm/Java/move-to-front-algorithm.java create mode 100644 Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js create mode 100644 Task/Move-to-front-algorithm/MATLAB/move-to-front-algorithm.m create mode 100644 Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-1.math create mode 100644 Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-2.math create mode 100644 Task/Move-to-front-algorithm/PL-I/move-to-front-algorithm.pli create mode 100644 Task/Move-to-front-algorithm/Perl-6/move-to-front-algorithm.pl6 create mode 100644 Task/Move-to-front-algorithm/Perl/move-to-front-algorithm.pl create mode 100644 Task/Move-to-front-algorithm/Python/move-to-front-algorithm-1.py create mode 100644 Task/Move-to-front-algorithm/Python/move-to-front-algorithm-2.py create mode 100644 Task/Move-to-front-algorithm/README create mode 100644 Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-1.rexx create mode 100644 Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx create mode 100644 Task/Move-to-front-algorithm/Racket/move-to-front-algorithm.rkt create mode 100644 Task/Move-to-front-algorithm/Ruby/move-to-front-algorithm.rb create mode 100644 Task/Move-to-front-algorithm/Tcl/move-to-front-algorithm.tcl create mode 100644 Task/Munching-squares/00DESCRIPTION create mode 100644 Task/Munching-squares/00META.yaml create mode 100644 Task/Munching-squares/Ada/munching-squares.ada create mode 100644 Task/Munching-squares/Burlesque/munching-squares.blq create mode 100644 Task/Munching-squares/C++/munching-squares.cpp create mode 100644 Task/Munching-squares/C-sharp/munching-squares.cs create mode 100644 Task/Munching-squares/C/munching-squares.c create mode 100644 Task/Munching-squares/D/munching-squares.d create mode 100644 Task/Munching-squares/Gnuplot/munching-squares.gnuplot create mode 100644 Task/Munching-squares/Go/munching-squares.go create mode 100644 Task/Munching-squares/Haskell/munching-squares.hs create mode 100644 Task/Munching-squares/Icon/munching-squares.icon create mode 100644 Task/Munching-squares/J/munching-squares.j create mode 100644 Task/Munching-squares/Java/munching-squares.java create mode 100644 Task/Munching-squares/Liberty-BASIC/munching-squares.liberty create mode 100644 Task/Munching-squares/MATLAB/munching-squares.m create mode 100644 Task/Munching-squares/Mathematica/munching-squares-1.math create mode 100644 Task/Munching-squares/Mathematica/munching-squares-2.math create mode 100644 Task/Munching-squares/OCaml/munching-squares.ocaml create mode 100644 Task/Munching-squares/Octave/munching-squares.octave create mode 100644 Task/Munching-squares/PHP/munching-squares.php create mode 100644 Task/Munching-squares/PL-I/munching-squares.pli create mode 100644 Task/Munching-squares/Perl-6/munching-squares-1.pl6 create mode 100644 Task/Munching-squares/Perl-6/munching-squares-2.pl6 create mode 100644 Task/Munching-squares/Perl/munching-squares.pl create mode 100644 Task/Munching-squares/Prolog/munching-squares.pro create mode 100644 Task/Munching-squares/PureBasic/munching-squares.purebasic create mode 100644 Task/Munching-squares/Python/munching-squares.py create mode 100644 Task/Munching-squares/README create mode 100644 Task/Munching-squares/Racket/munching-squares.rkt create mode 100644 Task/Munching-squares/Ruby/munching-squares.rb create mode 100644 Task/Munching-squares/Run-BASIC/munching-squares.run create mode 100644 Task/Munching-squares/Scala/munching-squares.scala create mode 100644 Task/Munching-squares/TI-83-BASIC/munching-squares.ti-83 create mode 100644 Task/Munching-squares/Tcl/munching-squares.tcl create mode 100644 Task/Munching-squares/XPL0/munching-squares.xpl0 delete mode 100644 Task/Mutex/00DESCRIPTION delete mode 100644 Task/Mutex/00META.yaml delete mode 100644 Task/Mutex/Ada/mutex-1.ada delete mode 100644 Task/Mutex/Ada/mutex-2.ada delete mode 100644 Task/Mutex/Ada/mutex-3.ada delete mode 100644 Task/Mutex/BBC-BASIC/mutex.bbc delete mode 100644 Task/Mutex/C/mutex-1.c delete mode 100644 Task/Mutex/C/mutex-2.c delete mode 100644 Task/Mutex/C/mutex-3.c delete mode 100644 Task/Mutex/C/mutex-4.c delete mode 100644 Task/Mutex/C/mutex-5.c delete mode 100644 Task/Mutex/C/mutex-6.c delete mode 100644 Task/Mutex/C/mutex-7.c delete mode 100644 Task/Mutex/C/mutex-8.c delete mode 100644 Task/Mutex/C/mutex-9.c delete mode 100644 Task/Mutex/D/mutex-1.d delete mode 100644 Task/Mutex/D/mutex-2.d delete mode 100644 Task/Mutex/D/mutex-3.d delete mode 100644 Task/Mutex/E/mutex-1.e delete mode 100644 Task/Mutex/E/mutex-2.e delete mode 100644 Task/Mutex/Erlang/mutex.erl delete mode 100644 Task/Mutex/Go/mutex-1.go delete mode 100644 Task/Mutex/Go/mutex-2.go delete mode 100644 Task/Mutex/Haskell/mutex-1.hs delete mode 100644 Task/Mutex/Haskell/mutex-2.hs delete mode 100644 Task/Mutex/Java/mutex-1.java delete mode 100644 Task/Mutex/Java/mutex-2.java delete mode 100644 Task/Mutex/Java/mutex-3.java delete mode 100644 Task/Mutex/Logtalk/mutex-1.logtalk delete mode 100644 Task/Mutex/Logtalk/mutex-2.logtalk delete mode 100644 Task/Mutex/OCaml/mutex.ocaml delete mode 100644 Task/Mutex/Objeck/mutex.objeck delete mode 100644 Task/Mutex/Objective-C/mutex.m delete mode 100644 Task/Mutex/Oz/mutex-1.oz delete mode 100644 Task/Mutex/Oz/mutex-2.oz delete mode 100644 Task/Mutex/Oz/mutex-3.oz delete mode 100644 Task/Mutex/Perl-6/mutex.pl6 delete mode 100644 Task/Mutex/Perl/mutex.pl delete mode 100644 Task/Mutex/PureBasic/mutex-1.purebasic delete mode 100644 Task/Mutex/PureBasic/mutex-2.purebasic delete mode 100644 Task/Mutex/Python/mutex.py delete mode 100644 Task/Mutex/README delete mode 100644 Task/Mutex/Racket/mutex-1.rkt delete mode 100644 Task/Mutex/Racket/mutex-2.rkt delete mode 100644 Task/Mutex/Ruby/mutex-1.rb delete mode 100644 Task/Mutex/Ruby/mutex-2.rb delete mode 100644 Task/Mutex/Ruby/mutex-3.rb delete mode 100644 Task/Mutex/Tcl/mutex-1.tcl delete mode 100644 Task/Mutex/Tcl/mutex-2.tcl create mode 100644 Task/Narcissistic-decimal-number/00DESCRIPTION create mode 100644 Task/Narcissistic-decimal-number/AWK/narcissistic-decimal-number.awk create mode 100644 Task/Narcissistic-decimal-number/Ada/narcissistic-decimal-number.ada create mode 100644 Task/Narcissistic-decimal-number/AutoHotkey/narcissistic-decimal-number.ahk create mode 100644 Task/Narcissistic-decimal-number/C++/narcissistic-decimal-number.cpp create mode 100644 Task/Narcissistic-decimal-number/C/narcissistic-decimal-number.c create mode 100644 Task/Narcissistic-decimal-number/Common-Lisp/narcissistic-decimal-number.lisp create mode 100644 Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-1.d create mode 100644 Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-2.d create mode 100644 Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-3.d create mode 100644 Task/Narcissistic-decimal-number/Go/narcissistic-decimal-number.go create mode 100644 Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs create mode 100644 Task/Narcissistic-decimal-number/Icon/narcissistic-decimal-number.icon create mode 100644 Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-1.j create mode 100644 Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-2.j create mode 100644 Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java create mode 100644 Task/Narcissistic-decimal-number/MATLAB/narcissistic-decimal-number.m create mode 100644 Task/Narcissistic-decimal-number/Pascal/narcissistic-decimal-number.pascal create mode 100644 Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-1.pl6 create mode 100644 Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 create mode 100644 Task/Narcissistic-decimal-number/Perl/narcissistic-decimal-number.pl create mode 100644 Task/Narcissistic-decimal-number/PicoLisp/narcissistic-decimal-number.l create mode 100644 Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-1.py create mode 100644 Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-2.py create mode 100644 Task/Narcissistic-decimal-number/README create mode 100644 Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx create mode 100644 Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx create mode 100644 Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx create mode 100644 Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-1.rkt create mode 100644 Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-2.rkt create mode 100644 Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb create mode 100644 Task/Narcissistic-decimal-number/Scala/narcissistic-decimal-number.scala create mode 100644 Task/Narcissistic-decimal-number/Tcl/narcissistic-decimal-number.tcl create mode 100644 Task/Narcissistic-decimal-number/UNIX-Shell/narcissistic-decimal-number.sh create mode 100644 Task/Natural-sorting/00DESCRIPTION create mode 100644 Task/Natural-sorting/C/natural-sorting-1.c create mode 100644 Task/Natural-sorting/C/natural-sorting-2.c create mode 100644 Task/Natural-sorting/D/natural-sorting.d create mode 100644 Task/Natural-sorting/Go/natural-sorting.go create mode 100644 Task/Natural-sorting/J/natural-sorting-1.j create mode 100644 Task/Natural-sorting/J/natural-sorting-2.j create mode 100644 Task/Natural-sorting/J/natural-sorting-3.j create mode 100644 Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 create mode 100644 Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 create mode 100644 Task/Natural-sorting/Perl/natural-sorting-1.pl create mode 100644 Task/Natural-sorting/Perl/natural-sorting-2.pl create mode 100644 Task/Natural-sorting/PicoLisp/natural-sorting-1.l create mode 100644 Task/Natural-sorting/PicoLisp/natural-sorting-2.l create mode 100644 Task/Natural-sorting/PicoLisp/natural-sorting-3.l create mode 100644 Task/Natural-sorting/PicoLisp/natural-sorting-4.l create mode 100644 Task/Natural-sorting/Python/natural-sorting.py create mode 100644 Task/Natural-sorting/README create mode 100644 Task/Natural-sorting/Racket/natural-sorting.rkt create mode 100644 Task/Natural-sorting/Ruby/natural-sorting-1.rb create mode 100644 Task/Natural-sorting/Ruby/natural-sorting-2.rb create mode 100644 Task/Natural-sorting/Ruby/natural-sorting-3.rb create mode 100644 Task/Natural-sorting/Scala/natural-sorting.scala create mode 100644 Task/Natural-sorting/Tcl/natural-sorting.tcl create mode 100644 Task/Nth/00DESCRIPTION create mode 100644 Task/Nth/00META.yaml create mode 100644 Task/Nth/ALGOL-68/nth.alg create mode 100644 Task/Nth/AWK/nth.awk create mode 100644 Task/Nth/Ada/nth.ada create mode 100644 Task/Nth/Applesoft-BASIC/nth.applesoft create mode 100644 Task/Nth/AutoHotkey/nth.ahk create mode 100644 Task/Nth/BBC-BASIC/nth.bbc create mode 100644 Task/Nth/Babel/nth.pb create mode 100644 Task/Nth/C/nth.c create mode 100644 Task/Nth/Clojure/nth-1.clj create mode 100644 Task/Nth/Clojure/nth-2.clj create mode 100644 Task/Nth/Common-Lisp/nth.lisp create mode 100644 Task/Nth/D/nth.d create mode 100644 Task/Nth/Forth/nth.fth create mode 100644 Task/Nth/Fortran/nth.f create mode 100644 Task/Nth/Go/nth.go create mode 100644 Task/Nth/Haskell/nth.hs create mode 100644 Task/Nth/Icon/nth.icon create mode 100644 Task/Nth/J/nth-1.j create mode 100644 Task/Nth/J/nth-2.j create mode 100644 Task/Nth/Java/nth-1.java create mode 100644 Task/Nth/Java/nth-2.java create mode 100644 Task/Nth/MATLAB/nth.m create mode 100644 Task/Nth/Mathematica/nth.math create mode 100644 Task/Nth/PARI-GP/nth.pari create mode 100644 Task/Nth/PHP/nth.php create mode 100644 Task/Nth/PL-I/nth.pli create mode 100644 Task/Nth/Perl-6/nth-1.pl6 create mode 100644 Task/Nth/Perl-6/nth-2.pl6 create mode 100644 Task/Nth/Perl/nth-1.pl create mode 100644 Task/Nth/Perl/nth-2.pl create mode 100644 Task/Nth/PicoLisp/nth.l create mode 100644 Task/Nth/Prolog/nth.pro create mode 100644 Task/Nth/Python/nth.py create mode 100644 Task/Nth/R/nth.r create mode 100644 Task/Nth/README create mode 100644 Task/Nth/REXX/nth.rexx create mode 100644 Task/Nth/Racket/nth.rkt create mode 100644 Task/Nth/Ruby/nth.rb create mode 100644 Task/Nth/Rust/nth.rust create mode 100644 Task/Nth/Scala/nth.scala create mode 100644 Task/Nth/Seed7/nth.seed7 create mode 100644 Task/Nth/Tcl/nth.tcl create mode 100644 Task/Odd-word-problem/00DESCRIPTION create mode 100644 Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg create mode 100644 Task/Odd-word-problem/Ada/odd-word-problem.ada create mode 100644 Task/Odd-word-problem/Bracmat/odd-word-problem.bracmat create mode 100644 Task/Odd-word-problem/C++/odd-word-problem.cpp create mode 100644 Task/Odd-word-problem/C/odd-word-problem.c create mode 100644 Task/Odd-word-problem/Clojure/odd-word-problem-1.clj create mode 100644 Task/Odd-word-problem/Clojure/odd-word-problem-2.clj create mode 100644 Task/Odd-word-problem/CoffeeScript/odd-word-problem-1.coffee create mode 100644 Task/Odd-word-problem/CoffeeScript/odd-word-problem-2.coffee create mode 100644 Task/Odd-word-problem/CoffeeScript/odd-word-problem-3.coffee create mode 100644 Task/Odd-word-problem/Common-Lisp/odd-word-problem-1.lisp create mode 100644 Task/Odd-word-problem/Common-Lisp/odd-word-problem-2.lisp create mode 100644 Task/Odd-word-problem/D/odd-word-problem.d create mode 100644 Task/Odd-word-problem/Erlang/odd-word-problem.erl create mode 100644 Task/Odd-word-problem/FALSE/odd-word-problem.false create mode 100644 Task/Odd-word-problem/Factor/odd-word-problem.factor create mode 100644 Task/Odd-word-problem/Forth/odd-word-problem.fth create mode 100644 Task/Odd-word-problem/Go/odd-word-problem-1.go create mode 100644 Task/Odd-word-problem/Go/odd-word-problem-2.go create mode 100644 Task/Odd-word-problem/Go/odd-word-problem-3.go create mode 100644 Task/Odd-word-problem/Haskell/odd-word-problem-1.hs create mode 100644 Task/Odd-word-problem/Haskell/odd-word-problem-2.hs create mode 100644 Task/Odd-word-problem/Icon/odd-word-problem-1.icon create mode 100644 Task/Odd-word-problem/Icon/odd-word-problem-2.icon create mode 100644 Task/Odd-word-problem/J/odd-word-problem-1.j create mode 100644 Task/Odd-word-problem/J/odd-word-problem-2.j create mode 100644 Task/Odd-word-problem/Java/odd-word-problem.java create mode 100644 Task/Odd-word-problem/OCaml/odd-word-problem.ocaml create mode 100644 Task/Odd-word-problem/PHP/odd-word-problem.php create mode 100644 Task/Odd-word-problem/PL-I/odd-word-problem.pli create mode 100644 Task/Odd-word-problem/Perl-6/odd-word-problem.pl6 create mode 100644 Task/Odd-word-problem/Perl/odd-word-problem-1.pl create mode 100644 Task/Odd-word-problem/Perl/odd-word-problem-2.pl create mode 100644 Task/Odd-word-problem/Perl/odd-word-problem-3.pl create mode 100644 Task/Odd-word-problem/PicoLisp/odd-word-problem-1.l create mode 100644 Task/Odd-word-problem/PicoLisp/odd-word-problem-2.l create mode 100644 Task/Odd-word-problem/Prolog/odd-word-problem.pro create mode 100644 Task/Odd-word-problem/PureBasic/odd-word-problem.purebasic create mode 100644 Task/Odd-word-problem/Python/odd-word-problem-1.py create mode 100644 Task/Odd-word-problem/Python/odd-word-problem-2.py create mode 100644 Task/Odd-word-problem/Python/odd-word-problem-3.py create mode 100644 Task/Odd-word-problem/Python/odd-word-problem-4.py create mode 100644 Task/Odd-word-problem/README create mode 100644 Task/Odd-word-problem/REXX/odd-word-problem.rexx create mode 100644 Task/Odd-word-problem/Racket/odd-word-problem.rkt create mode 100644 Task/Odd-word-problem/Ruby/odd-word-problem-1.rb create mode 100644 Task/Odd-word-problem/Ruby/odd-word-problem-2.rb create mode 100644 Task/Odd-word-problem/Run-BASIC/odd-word-problem.run create mode 100644 Task/Odd-word-problem/Scala/odd-word-problem.scala create mode 100644 Task/Odd-word-problem/Scheme/odd-word-problem.ss create mode 100644 Task/Odd-word-problem/Seed7/odd-word-problem.seed7 create mode 100644 Task/Odd-word-problem/TUSCRIPT/odd-word-problem.tu create mode 100644 Task/Odd-word-problem/Tcl/odd-word-problem.tcl create mode 100644 Task/Old-lady-swallowed-a-fly/00DESCRIPTION create mode 100644 Task/Old-lady-swallowed-a-fly/ALGOL-68/old-lady-swallowed-a-fly-1.alg create mode 100644 Task/Old-lady-swallowed-a-fly/ALGOL-68/old-lady-swallowed-a-fly-2.alg create mode 100644 Task/Old-lady-swallowed-a-fly/AWK/old-lady-swallowed-a-fly.awk create mode 100644 Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada create mode 100644 Task/Old-lady-swallowed-a-fly/AutoHotkey/old-lady-swallowed-a-fly.ahk create mode 100644 Task/Old-lady-swallowed-a-fly/Babel/old-lady-swallowed-a-fly.pb create mode 100644 Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c create mode 100644 Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-1.d create mode 100644 Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-2.d create mode 100644 Task/Old-lady-swallowed-a-fly/Factor/old-lady-swallowed-a-fly.factor create mode 100644 Task/Old-lady-swallowed-a-fly/Forth/old-lady-swallowed-a-fly.fth create mode 100644 Task/Old-lady-swallowed-a-fly/Frege/old-lady-swallowed-a-fly.frege create mode 100644 Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs create mode 100644 Task/Old-lady-swallowed-a-fly/Icon/old-lady-swallowed-a-fly.icon create mode 100644 Task/Old-lady-swallowed-a-fly/J/old-lady-swallowed-a-fly.j create mode 100644 Task/Old-lady-swallowed-a-fly/Java/old-lady-swallowed-a-fly.java create mode 100644 Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml create mode 100644 Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml create mode 100644 Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml create mode 100644 Task/Old-lady-swallowed-a-fly/PHP/old-lady-swallowed-a-fly.php create mode 100644 Task/Old-lady-swallowed-a-fly/Perl-6/old-lady-swallowed-a-fly.pl6 create mode 100644 Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-1.pl create mode 100644 Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-2.pl create mode 100644 Task/Old-lady-swallowed-a-fly/PicoLisp/old-lady-swallowed-a-fly.l create mode 100644 Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py create mode 100644 Task/Old-lady-swallowed-a-fly/README create mode 100644 Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx create mode 100644 Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-1.rkt create mode 100644 Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-2.rkt create mode 100644 Task/Old-lady-swallowed-a-fly/Ruby/old-lady-swallowed-a-fly.rb create mode 100644 Task/Old-lady-swallowed-a-fly/Scala/old-lady-swallowed-a-fly.scala create mode 100644 Task/Old-lady-swallowed-a-fly/Seed7/old-lady-swallowed-a-fly.seed7 create mode 100644 Task/Old-lady-swallowed-a-fly/TXR/old-lady-swallowed-a-fly.txr create mode 100644 Task/Old-lady-swallowed-a-fly/Tcl/old-lady-swallowed-a-fly.tcl create mode 100644 Task/Order-disjoint-list-items/00DESCRIPTION create mode 100644 Task/Order-disjoint-list-items/AutoHotkey/order-disjoint-list-items.ahk create mode 100644 Task/Order-disjoint-list-items/Bracmat/order-disjoint-list-items.bracmat create mode 100644 Task/Order-disjoint-list-items/D/order-disjoint-list-items.d create mode 100644 Task/Order-disjoint-list-items/Go/order-disjoint-list-items.go create mode 100644 Task/Order-disjoint-list-items/Icon/order-disjoint-list-items.icon create mode 100644 Task/Order-disjoint-list-items/J/order-disjoint-list-items-1.j create mode 100644 Task/Order-disjoint-list-items/J/order-disjoint-list-items-2.j create mode 100644 Task/Order-disjoint-list-items/Java/order-disjoint-list-items.java create mode 100644 Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-1.pl6 create mode 100644 Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-2.pl6 create mode 100644 Task/Order-disjoint-list-items/Perl/order-disjoint-list-items.pl create mode 100644 Task/Order-disjoint-list-items/Python/order-disjoint-list-items.py create mode 100644 Task/Order-disjoint-list-items/README create mode 100644 Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx create mode 100644 Task/Order-disjoint-list-items/Racket/order-disjoint-list-items.rkt create mode 100644 Task/Order-disjoint-list-items/Ruby/order-disjoint-list-items.rb create mode 100644 Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-1.scala create mode 100644 Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-2.scala create mode 100644 Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-1.tcl create mode 100644 Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-2.tcl create mode 100644 Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-3.tcl create mode 100644 Task/Paraffins/00DESCRIPTION create mode 100644 Task/Paraffins/C/paraffins-1.c create mode 100644 Task/Paraffins/C/paraffins-2.c create mode 100644 Task/Paraffins/D/paraffins.d create mode 100644 Task/Paraffins/Go/paraffins.go create mode 100644 Task/Paraffins/Haskell/paraffins.hs create mode 100644 Task/Paraffins/J/paraffins-1.j create mode 100644 Task/Paraffins/J/paraffins-2.j create mode 100644 Task/Paraffins/Mathematica/paraffins.math create mode 100644 Task/Paraffins/Pascal/paraffins.pascal create mode 100644 Task/Paraffins/Perl-6/paraffins.pl6 create mode 100644 Task/Paraffins/Perl/paraffins.pl create mode 100644 Task/Paraffins/Pike/paraffins.pike create mode 100644 Task/Paraffins/Python/paraffins.py create mode 100644 Task/Paraffins/README create mode 100644 Task/Paraffins/REXX/paraffins.rexx create mode 100644 Task/Paraffins/Racket/paraffins.rkt create mode 100644 Task/Paraffins/Ruby/paraffins.rb create mode 100644 Task/Paraffins/Seed7/paraffins.seed7 create mode 100644 Task/Paraffins/Tcl/paraffins.tcl create mode 100644 Task/Parse-an-IP-Address/00DESCRIPTION create mode 100644 Task/Parse-an-IP-Address/C/parse-an-ip-address-1.c create mode 100644 Task/Parse-an-IP-Address/C/parse-an-ip-address-2.c create mode 100644 Task/Parse-an-IP-Address/Go/parse-an-ip-address.go create mode 100644 Task/Parse-an-IP-Address/Icon/parse-an-ip-address.icon create mode 100644 Task/Parse-an-IP-Address/J/parse-an-ip-address-1.j create mode 100644 Task/Parse-an-IP-Address/J/parse-an-ip-address-2.j create mode 100644 Task/Parse-an-IP-Address/Java/parse-an-ip-address-1.java create mode 100644 Task/Parse-an-IP-Address/Java/parse-an-ip-address-2.java create mode 100644 Task/Parse-an-IP-Address/Perl-6/parse-an-ip-address.pl6 create mode 100644 Task/Parse-an-IP-Address/Perl/parse-an-ip-address-1.pl create mode 100644 Task/Parse-an-IP-Address/Perl/parse-an-ip-address-2.pl create mode 100644 Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-1.l create mode 100644 Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-2.l create mode 100644 Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-3.l create mode 100644 Task/Parse-an-IP-Address/Python/parse-an-ip-address.py create mode 100644 Task/Parse-an-IP-Address/README create mode 100644 Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx create mode 100644 Task/Parse-an-IP-Address/REXX/parse-an-ip-address-2.rexx create mode 100644 Task/Parse-an-IP-Address/Racket/parse-an-ip-address.rkt create mode 100644 Task/Parse-an-IP-Address/Ruby/parse-an-ip-address.rb create mode 100644 Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-1.tcl create mode 100644 Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-2.tcl create mode 100644 Task/Penneys-game/00DESCRIPTION create mode 100644 Task/Penneys-game/C++/penneys-game.cpp create mode 100644 Task/Penneys-game/C/penneys-game.c create mode 100644 Task/Penneys-game/D/penneys-game.d create mode 100644 Task/Penneys-game/Haskell/penneys-game.hs create mode 100644 Task/Penneys-game/J/penneys-game-1.j create mode 100644 Task/Penneys-game/J/penneys-game-2.j create mode 100644 Task/Penneys-game/Java/penneys-game.java create mode 100644 Task/Penneys-game/Perl-6/penneys-game.pl6 create mode 100644 Task/Penneys-game/Python/penneys-game.py create mode 100644 Task/Penneys-game/README create mode 100644 Task/Penneys-game/REXX/penneys-game.rexx create mode 100644 Task/Penneys-game/Racket/penneys-game.rkt create mode 100644 Task/Penneys-game/Ruby/penneys-game.rb create mode 100644 Task/Penneys-game/Tcl/penneys-game.tcl create mode 100644 Task/Penneys-game/UNIX-Shell/penneys-game.sh create mode 100644 Task/Percolation-Bond-percolation/00DESCRIPTION create mode 100644 Task/Percolation-Bond-percolation/00META.yaml create mode 100644 Task/Percolation-Bond-percolation/C/percolation-bond-percolation.c create mode 100644 Task/Percolation-Bond-percolation/D/percolation-bond-percolation.d create mode 100644 Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go create mode 100644 Task/Percolation-Bond-percolation/Python/percolation-bond-percolation.py create mode 100644 Task/Percolation-Bond-percolation/README create mode 100644 Task/Percolation-Bond-percolation/Racket/percolation-bond-percolation.rkt create mode 100644 Task/Percolation-Bond-percolation/Tcl/percolation-bond-percolation.tcl create mode 100644 Task/Percolation-Mean-cluster-density/00DESCRIPTION create mode 100644 Task/Percolation-Mean-cluster-density/00META.yaml create mode 100644 Task/Percolation-Mean-cluster-density/C/percolation-mean-cluster-density.c create mode 100644 Task/Percolation-Mean-cluster-density/D/percolation-mean-cluster-density.d create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-1.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-10.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-11.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-12.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-13.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-14.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-2.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-3.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-4.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-5.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-6.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-7.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-8.j create mode 100644 Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-9.j create mode 100644 Task/Percolation-Mean-cluster-density/Python/percolation-mean-cluster-density.py create mode 100644 Task/Percolation-Mean-cluster-density/README create mode 100644 Task/Percolation-Mean-cluster-density/Racket/percolation-mean-cluster-density.rkt create mode 100644 Task/Percolation-Mean-cluster-density/Tcl/percolation-mean-cluster-density.tcl create mode 100644 Task/Percolation-Mean-run-density/00DESCRIPTION create mode 100644 Task/Percolation-Mean-run-density/00META.yaml create mode 100644 Task/Percolation-Mean-run-density/C++/percolation-mean-run-density.cpp create mode 100644 Task/Percolation-Mean-run-density/C/percolation-mean-run-density.c create mode 100644 Task/Percolation-Mean-run-density/D/percolation-mean-run-density.d create mode 100644 Task/Percolation-Mean-run-density/Fortran/percolation-mean-run-density.f create mode 100644 Task/Percolation-Mean-run-density/Haskell/percolation-mean-run-density.hs create mode 100644 Task/Percolation-Mean-run-density/Icon/percolation-mean-run-density.icon create mode 100644 Task/Percolation-Mean-run-density/J/percolation-mean-run-density.j create mode 100644 Task/Percolation-Mean-run-density/Perl-6/percolation-mean-run-density.pl6 create mode 100644 Task/Percolation-Mean-run-density/Perl/percolation-mean-run-density.pl create mode 100644 Task/Percolation-Mean-run-density/Python/percolation-mean-run-density.py create mode 100644 Task/Percolation-Mean-run-density/README create mode 100644 Task/Percolation-Mean-run-density/Racket/percolation-mean-run-density.rkt create mode 100644 Task/Percolation-Mean-run-density/Tcl/percolation-mean-run-density.tcl create mode 100644 Task/Percolation-Site-percolation/00DESCRIPTION create mode 100644 Task/Percolation-Site-percolation/00META.yaml create mode 100644 Task/Percolation-Site-percolation/C/percolation-site-percolation-1.c create mode 100644 Task/Percolation-Site-percolation/C/percolation-site-percolation-2.c create mode 100644 Task/Percolation-Site-percolation/D/percolation-site-percolation.d create mode 100644 Task/Percolation-Site-percolation/Fortran/percolation-site-percolation.f create mode 100644 Task/Percolation-Site-percolation/Go/percolation-site-percolation.go create mode 100644 Task/Percolation-Site-percolation/J/percolation-site-percolation.j create mode 100644 Task/Percolation-Site-percolation/Python/percolation-site-percolation.py create mode 100644 Task/Percolation-Site-percolation/README create mode 100644 Task/Percolation-Site-percolation/Racket/percolation-site-percolation.rkt create mode 100644 Task/Percolation-Site-percolation/Tcl/percolation-site-percolation.tcl create mode 100644 Task/Permutations-Rank-of-a-permutation/00DESCRIPTION create mode 100644 Task/Permutations-Rank-of-a-permutation/C/permutations-rank-of-a-permutation.c create mode 100644 Task/Permutations-Rank-of-a-permutation/D/permutations-rank-of-a-permutation.d create mode 100644 Task/Permutations-Rank-of-a-permutation/Go/permutations-rank-of-a-permutation.go create mode 100644 Task/Permutations-Rank-of-a-permutation/Haskell/permutations-rank-of-a-permutation.hs create mode 100644 Task/Permutations-Rank-of-a-permutation/J/permutations-rank-of-a-permutation.j create mode 100644 Task/Permutations-Rank-of-a-permutation/Java/permutations-rank-of-a-permutation.java create mode 100644 Task/Permutations-Rank-of-a-permutation/Mathematica/permutations-rank-of-a-permutation.math create mode 100644 Task/Permutations-Rank-of-a-permutation/PARI-GP/permutations-rank-of-a-permutation.pari create mode 100644 Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-1.py create mode 100644 Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-2.py create mode 100644 Task/Permutations-Rank-of-a-permutation/README create mode 100644 Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx create mode 100644 Task/Permutations-Rank-of-a-permutation/Racket/permutations-rank-of-a-permutation.rkt create mode 100644 Task/Permutations-Rank-of-a-permutation/Ruby/permutations-rank-of-a-permutation-1.rb create mode 100644 Task/Permutations-Rank-of-a-permutation/Ruby/permutations-rank-of-a-permutation-2.rb create mode 100644 Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-1.tcl create mode 100644 Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-2.tcl create mode 100644 Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-3.tcl create mode 100644 Task/Pernicious-numbers/00DESCRIPTION create mode 100644 Task/Pernicious-numbers/00META.yaml create mode 100644 Task/Pernicious-numbers/Ada/pernicious-numbers-1.ada create mode 100644 Task/Pernicious-numbers/Ada/pernicious-numbers-2.ada create mode 100644 Task/Pernicious-numbers/AutoHotkey/pernicious-numbers.ahk create mode 100644 Task/Pernicious-numbers/C++/pernicious-numbers.cpp create mode 100644 Task/Pernicious-numbers/C/pernicious-numbers.c create mode 100644 Task/Pernicious-numbers/Common-Lisp/pernicious-numbers.lisp create mode 100644 Task/Pernicious-numbers/D/pernicious-numbers-1.d create mode 100644 Task/Pernicious-numbers/D/pernicious-numbers-2.d create mode 100644 Task/Pernicious-numbers/Go/pernicious-numbers.go create mode 100644 Task/Pernicious-numbers/Haskell/pernicious-numbers.hs create mode 100644 Task/Pernicious-numbers/Icon/pernicious-numbers.icon create mode 100644 Task/Pernicious-numbers/J/pernicious-numbers-1.j create mode 100644 Task/Pernicious-numbers/J/pernicious-numbers-2.j create mode 100644 Task/Pernicious-numbers/Java/pernicious-numbers.java create mode 100644 Task/Pernicious-numbers/Mathematica/pernicious-numbers-1.math create mode 100644 Task/Pernicious-numbers/Mathematica/pernicious-numbers-2.math create mode 100644 Task/Pernicious-numbers/Mathematica/pernicious-numbers-3.math create mode 100644 Task/Pernicious-numbers/Mathematica/pernicious-numbers-4.math create mode 100644 Task/Pernicious-numbers/PARI-GP/pernicious-numbers.pari create mode 100644 Task/Pernicious-numbers/Pascal/pernicious-numbers.pascal create mode 100644 Task/Pernicious-numbers/Perl-6/pernicious-numbers.pl6 create mode 100644 Task/Pernicious-numbers/Perl/pernicious-numbers-1.pl create mode 100644 Task/Pernicious-numbers/Perl/pernicious-numbers-2.pl create mode 100644 Task/Pernicious-numbers/Python/pernicious-numbers.py create mode 100644 Task/Pernicious-numbers/README create mode 100644 Task/Pernicious-numbers/REXX/pernicious-numbers.rexx create mode 100644 Task/Pernicious-numbers/Racket/pernicious-numbers.rkt create mode 100644 Task/Pernicious-numbers/Ruby/pernicious-numbers.rb create mode 100644 Task/Pernicious-numbers/Scala/pernicious-numbers.scala create mode 100644 Task/Pernicious-numbers/Tcl/pernicious-numbers.tcl create mode 100644 Task/Phrase-reversals/00DESCRIPTION create mode 100644 Task/Phrase-reversals/AWK/phrase-reversals.awk create mode 100644 Task/Phrase-reversals/Ada/phrase-reversals.ada create mode 100644 Task/Phrase-reversals/AutoHotkey/phrase-reversals.ahk create mode 100644 Task/Phrase-reversals/Bracmat/phrase-reversals.bracmat create mode 100644 Task/Phrase-reversals/C++/phrase-reversals.cpp create mode 100644 Task/Phrase-reversals/C/phrase-reversals.c create mode 100644 Task/Phrase-reversals/D/phrase-reversals.d create mode 100644 Task/Phrase-reversals/Go/phrase-reversals-1.go create mode 100644 Task/Phrase-reversals/Go/phrase-reversals-2.go create mode 100644 Task/Phrase-reversals/Groovy/phrase-reversals.groovy create mode 100644 Task/Phrase-reversals/Haskell/phrase-reversals.hs create mode 100644 Task/Phrase-reversals/J/phrase-reversals-1.j create mode 100644 Task/Phrase-reversals/J/phrase-reversals-2.j create mode 100644 Task/Phrase-reversals/Java/phrase-reversals.java create mode 100644 Task/Phrase-reversals/Mathematica/phrase-reversals.math create mode 100644 Task/Phrase-reversals/PHP/phrase-reversals.php create mode 100644 Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 create mode 100644 Task/Phrase-reversals/Perl/phrase-reversals.pl create mode 100644 Task/Phrase-reversals/Python/phrase-reversals.py create mode 100644 Task/Phrase-reversals/README create mode 100644 Task/Phrase-reversals/REXX/phrase-reversals-1.rexx create mode 100644 Task/Phrase-reversals/REXX/phrase-reversals-2.rexx create mode 100644 Task/Phrase-reversals/Racket/phrase-reversals.rkt create mode 100644 Task/Phrase-reversals/Ruby/phrase-reversals.rb create mode 100644 Task/Phrase-reversals/Tcl/phrase-reversals.tcl create mode 100644 Task/Phrase-reversals/UNIX-Shell/phrase-reversals-1.sh create mode 100644 Task/Phrase-reversals/UNIX-Shell/phrase-reversals-2.sh create mode 100644 Task/Quickselect-algorithm/00DESCRIPTION create mode 100644 Task/Quickselect-algorithm/AutoHotkey/quickselect-algorithm.ahk create mode 100644 Task/Quickselect-algorithm/C++/quickselect-algorithm-1.cpp create mode 100644 Task/Quickselect-algorithm/C++/quickselect-algorithm-2.cpp create mode 100644 Task/Quickselect-algorithm/C/quickselect-algorithm.c create mode 100644 Task/Quickselect-algorithm/COBOL/quickselect-algorithm.cobol create mode 100644 Task/Quickselect-algorithm/D/quickselect-algorithm-1.d create mode 100644 Task/Quickselect-algorithm/D/quickselect-algorithm-2.d create mode 100644 Task/Quickselect-algorithm/Go/quickselect-algorithm-1.go create mode 100644 Task/Quickselect-algorithm/Go/quickselect-algorithm-2.go create mode 100644 Task/Quickselect-algorithm/Haskell/quickselect-algorithm.hs create mode 100644 Task/Quickselect-algorithm/Icon/quickselect-algorithm.icon create mode 100644 Task/Quickselect-algorithm/J/quickselect-algorithm-1.j create mode 100644 Task/Quickselect-algorithm/J/quickselect-algorithm-2.j create mode 100644 Task/Quickselect-algorithm/J/quickselect-algorithm-3.j create mode 100644 Task/Quickselect-algorithm/Java/quickselect-algorithm.java create mode 100644 Task/Quickselect-algorithm/NetRexx/quickselect-algorithm.netrexx create mode 100644 Task/Quickselect-algorithm/OCaml/quickselect-algorithm.ocaml create mode 100644 Task/Quickselect-algorithm/PARI-GP/quickselect-algorithm.pari create mode 100644 Task/Quickselect-algorithm/PL-I/quickselect-algorithm.pli create mode 100644 Task/Quickselect-algorithm/Perl-6/quickselect-algorithm.pl6 create mode 100644 Task/Quickselect-algorithm/Perl/quickselect-algorithm.pl create mode 100644 Task/Quickselect-algorithm/Python/quickselect-algorithm.py create mode 100644 Task/Quickselect-algorithm/README create mode 100644 Task/Quickselect-algorithm/REXX/quickselect-algorithm.rexx create mode 100644 Task/Quickselect-algorithm/Racket/quickselect-algorithm.rkt create mode 100644 Task/Quickselect-algorithm/Ruby/quickselect-algorithm.rb create mode 100644 Task/Quickselect-algorithm/Scala/quickselect-algorithm.scala create mode 100644 Task/Quickselect-algorithm/Standard-ML/quickselect-algorithm.ml create mode 100644 Task/Quickselect-algorithm/Tcl/quickselect-algorithm-1.tcl create mode 100644 Task/Quickselect-algorithm/Tcl/quickselect-algorithm-2.tcl create mode 100644 Task/RSA-code/00DESCRIPTION create mode 100644 Task/RSA-code/00META.yaml create mode 100644 Task/RSA-code/Common-Lisp/rsa-code.lisp create mode 100644 Task/RSA-code/D/rsa-code.d create mode 100644 Task/RSA-code/Go/rsa-code.go create mode 100644 Task/RSA-code/Icon/rsa-code.icon create mode 100644 Task/RSA-code/J/rsa-code.j create mode 100644 Task/RSA-code/Perl-6/rsa-code.pl6 create mode 100644 Task/RSA-code/PicoLisp/rsa-code.l create mode 100644 Task/RSA-code/Python/rsa-code-1.py create mode 100644 Task/RSA-code/Python/rsa-code-2.py create mode 100644 Task/RSA-code/Python/rsa-code-3.py create mode 100644 Task/RSA-code/README create mode 100644 Task/RSA-code/Racket/rsa-code.rkt create mode 100644 Task/RSA-code/Seed7/rsa-code.seed7 create mode 100644 Task/RSA-code/Tcl/rsa-code.tcl create mode 100644 Task/Ranking-methods/00DESCRIPTION create mode 100644 Task/Ranking-methods/AWK/ranking-methods.awk create mode 100644 Task/Ranking-methods/Go/ranking-methods.go create mode 100644 Task/Ranking-methods/Haskell/ranking-methods.hs create mode 100644 Task/Ranking-methods/J/ranking-methods-1.j create mode 100644 Task/Ranking-methods/J/ranking-methods-2.j create mode 100644 Task/Ranking-methods/Java/ranking-methods.java create mode 100644 Task/Ranking-methods/Perl-6/ranking-methods.pl6 create mode 100644 Task/Ranking-methods/Python/ranking-methods.py create mode 100644 Task/Ranking-methods/README create mode 100644 Task/Ranking-methods/Racket/ranking-methods.rkt create mode 100644 Task/Ranking-methods/Ruby/ranking-methods.rb create mode 100644 Task/Ranking-methods/Scala/ranking-methods.scala create mode 100644 Task/Ranking-methods/Tcl/ranking-methods.tcl create mode 100644 Task/Rep-string/00DESCRIPTION create mode 100644 Task/Rep-string/ALGOL-68/rep-string.alg create mode 100644 Task/Rep-string/Ada/rep-string.ada create mode 100644 Task/Rep-string/AutoHotkey/rep-string.ahk create mode 100644 Task/Rep-string/Bracmat/rep-string.bracmat create mode 100644 Task/Rep-string/C++/rep-string.cpp create mode 100644 Task/Rep-string/C/rep-string.c create mode 100644 Task/Rep-string/D/rep-string.d create mode 100644 Task/Rep-string/Go/rep-string.go create mode 100644 Task/Rep-string/Haskell/rep-string.hs create mode 100644 Task/Rep-string/Icon/rep-string.icon create mode 100644 Task/Rep-string/J/rep-string-1.j create mode 100644 Task/Rep-string/J/rep-string-2.j create mode 100644 Task/Rep-string/J/rep-string-3.j create mode 100644 Task/Rep-string/J/rep-string-4.j create mode 100644 Task/Rep-string/Java/rep-string.java create mode 100644 Task/Rep-string/Maple/rep-string-1.maple create mode 100644 Task/Rep-string/Maple/rep-string-2.maple create mode 100644 Task/Rep-string/Mathematica/rep-string-1.math create mode 100644 Task/Rep-string/Mathematica/rep-string-2.math create mode 100644 Task/Rep-string/NetRexx/rep-string.netrexx create mode 100644 Task/Rep-string/PARI-GP/rep-string.pari create mode 100644 Task/Rep-string/PL-I/rep-string.pli create mode 100644 Task/Rep-string/Perl-6/rep-string-1.pl6 create mode 100644 Task/Rep-string/Perl-6/rep-string-2.pl6 create mode 100644 Task/Rep-string/Perl/rep-string.pl create mode 100644 Task/Rep-string/Prolog/rep-string.pro create mode 100644 Task/Rep-string/Python/rep-string-1.py create mode 100644 Task/Rep-string/Python/rep-string-2.py create mode 100644 Task/Rep-string/Python/rep-string-3.py create mode 100644 Task/Rep-string/README create mode 100644 Task/Rep-string/REXX/rep-string-1.rexx create mode 100644 Task/Rep-string/REXX/rep-string-2.rexx create mode 100644 Task/Rep-string/Racket/rep-string.rkt create mode 100644 Task/Rep-string/Ruby/rep-string.rb create mode 100644 Task/Rep-string/Scala/rep-string.scala create mode 100644 Task/Rep-string/Seed7/rep-string.seed7 create mode 100644 Task/Rep-string/Tcl/rep-string-1.tcl create mode 100644 Task/Rep-string/Tcl/rep-string-2.tcl create mode 100644 Task/Rep-string/UNIX-Shell/rep-string.sh create mode 100644 Task/Reverse-words-in-a-string/00DESCRIPTION create mode 100644 Task/Reverse-words-in-a-string/AWK/reverse-words-in-a-string.awk create mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-1.ada create mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-2.ada create mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-3.ada create mode 100644 Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime create mode 100644 Task/Reverse-words-in-a-string/Applesoft-BASIC/reverse-words-in-a-string.applesoft create mode 100644 Task/Reverse-words-in-a-string/AutoHotkey/reverse-words-in-a-string.ahk create mode 100644 Task/Reverse-words-in-a-string/BBC-BASIC/reverse-words-in-a-string.bbc create mode 100644 Task/Reverse-words-in-a-string/Bracmat/reverse-words-in-a-string.bracmat create mode 100644 Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-1.cpp create mode 100644 Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-2.cpp create mode 100644 Task/Reverse-words-in-a-string/C/reverse-words-in-a-string.c create mode 100644 Task/Reverse-words-in-a-string/Clojure/reverse-words-in-a-string.clj create mode 100644 Task/Reverse-words-in-a-string/Common-Lisp/reverse-words-in-a-string.lisp create mode 100644 Task/Reverse-words-in-a-string/D/reverse-words-in-a-string.d create mode 100644 Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-1.elixir create mode 100644 Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-2.elixir create mode 100644 Task/Reverse-words-in-a-string/Go/reverse-words-in-a-string.go create mode 100644 Task/Reverse-words-in-a-string/Groovy/reverse-words-in-a-string.groovy create mode 100644 Task/Reverse-words-in-a-string/Haskell/reverse-words-in-a-string.hs create mode 100644 Task/Reverse-words-in-a-string/Icon/reverse-words-in-a-string.icon create mode 100644 Task/Reverse-words-in-a-string/J/reverse-words-in-a-string.j create mode 100644 Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-1.java create mode 100644 Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-2.java create mode 100644 Task/Reverse-words-in-a-string/Julia/reverse-words-in-a-string.julia create mode 100644 Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua create mode 100644 Task/Reverse-words-in-a-string/MATLAB/reverse-words-in-a-string.m create mode 100644 Task/Reverse-words-in-a-string/Mathematica/reverse-words-in-a-string.math create mode 100644 Task/Reverse-words-in-a-string/OCaml/reverse-words-in-a-string.ocaml create mode 100644 Task/Reverse-words-in-a-string/Objeck/reverse-words-in-a-string.objeck create mode 100644 Task/Reverse-words-in-a-string/PL-I/reverse-words-in-a-string.pli create mode 100644 Task/Reverse-words-in-a-string/Perl-6/reverse-words-in-a-string.pl6 create mode 100644 Task/Reverse-words-in-a-string/Perl/reverse-words-in-a-string.pl create mode 100644 Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-1.py create mode 100644 Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-2.py create mode 100644 Task/Reverse-words-in-a-string/README create mode 100644 Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string.rexx create mode 100644 Task/Reverse-words-in-a-string/Racket/reverse-words-in-a-string.rkt create mode 100644 Task/Reverse-words-in-a-string/Ruby/reverse-words-in-a-string.rb create mode 100644 Task/Reverse-words-in-a-string/Scala/reverse-words-in-a-string.scala create mode 100644 Task/Reverse-words-in-a-string/Scheme/reverse-words-in-a-string.ss create mode 100644 Task/Reverse-words-in-a-string/Seed7/reverse-words-in-a-string.seed7 create mode 100644 Task/Reverse-words-in-a-string/Smalltalk/reverse-words-in-a-string.st create mode 100644 Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-1.tcl create mode 100644 Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-2.tcl create mode 100644 Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-1.sh create mode 100644 Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-2.sh create mode 100644 Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-3.sh create mode 100644 Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk create mode 100644 Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c create mode 100644 Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl create mode 100644 Task/Runge-Kutta-method/00DESCRIPTION create mode 100644 Task/Runge-Kutta-method/00META.yaml create mode 100644 Task/Runge-Kutta-method/AWK/runge-kutta-method.awk create mode 100644 Task/Runge-Kutta-method/Ada/runge-kutta-method.ada create mode 100644 Task/Runge-Kutta-method/BASIC/runge-kutta-method.basic create mode 100644 Task/Runge-Kutta-method/C/runge-kutta-method.c create mode 100644 Task/Runge-Kutta-method/D/runge-kutta-method.d create mode 100644 Task/Runge-Kutta-method/Dart/runge-kutta-method.dart create mode 100644 Task/Runge-Kutta-method/F-Sharp/runge-kutta-method.fs create mode 100644 Task/Runge-Kutta-method/Fortran/runge-kutta-method.f create mode 100644 Task/Runge-Kutta-method/Go/runge-kutta-method.go create mode 100644 Task/Runge-Kutta-method/Haskell/runge-kutta-method-1.hs create mode 100644 Task/Runge-Kutta-method/Haskell/runge-kutta-method-2.hs create mode 100644 Task/Runge-Kutta-method/J/runge-kutta-method-1.j create mode 100644 Task/Runge-Kutta-method/J/runge-kutta-method-2.j create mode 100644 Task/Runge-Kutta-method/J/runge-kutta-method-3.j create mode 100644 Task/Runge-Kutta-method/JavaScript/runge-kutta-method.js create mode 100644 Task/Runge-Kutta-method/Julia/runge-kutta-method.julia create mode 100644 Task/Runge-Kutta-method/MATLAB/runge-kutta-method.m create mode 100644 Task/Runge-Kutta-method/Mathematica/runge-kutta-method.math create mode 100644 Task/Runge-Kutta-method/Maxima/runge-kutta-method.maxima create mode 100644 Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml create mode 100644 Task/Runge-Kutta-method/Octave/runge-kutta-method.octave create mode 100644 Task/Runge-Kutta-method/PARI-GP/runge-kutta-method.pari create mode 100644 Task/Runge-Kutta-method/PL-I/runge-kutta-method.pli create mode 100644 Task/Runge-Kutta-method/Pascal/runge-kutta-method.pascal create mode 100644 Task/Runge-Kutta-method/Perl-6/runge-kutta-method.pl6 create mode 100644 Task/Runge-Kutta-method/Perl/runge-kutta-method.pl create mode 100644 Task/Runge-Kutta-method/Python/runge-kutta-method.py create mode 100644 Task/Runge-Kutta-method/README create mode 100644 Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx create mode 100644 Task/Runge-Kutta-method/Racket/runge-kutta-method-1.rkt create mode 100644 Task/Runge-Kutta-method/Racket/runge-kutta-method-2.rkt create mode 100644 Task/Runge-Kutta-method/Racket/runge-kutta-method-3.rkt create mode 100644 Task/Runge-Kutta-method/Racket/runge-kutta-method-4.rkt create mode 100644 Task/Runge-Kutta-method/Ruby/runge-kutta-method.rb create mode 100644 Task/Runge-Kutta-method/Run-BASIC/runge-kutta-method.run create mode 100644 Task/Runge-Kutta-method/Standard-ML/runge-kutta-method.ml create mode 100644 Task/Runge-Kutta-method/Tcl/runge-kutta-method.tcl create mode 100644 Task/Semiprime/00DESCRIPTION create mode 100644 Task/Semiprime/00META.yaml create mode 100644 Task/Semiprime/Ada/semiprime.ada create mode 100644 Task/Semiprime/AutoHotkey/semiprime.ahk create mode 100644 Task/Semiprime/C++/semiprime.cpp create mode 100644 Task/Semiprime/C/semiprime.c create mode 100644 Task/Semiprime/Common-Lisp/semiprime.lisp create mode 100644 Task/Semiprime/D/semiprime.d create mode 100644 Task/Semiprime/Forth/semiprime.fth create mode 100644 Task/Semiprime/Go/semiprime.go create mode 100644 Task/Semiprime/Haskell/semiprime-1.hs create mode 100644 Task/Semiprime/Haskell/semiprime-2.hs create mode 100644 Task/Semiprime/Icon/semiprime.icon create mode 100644 Task/Semiprime/J/semiprime-1.j create mode 100644 Task/Semiprime/J/semiprime-2.j create mode 100644 Task/Semiprime/Java/semiprime.java create mode 100644 Task/Semiprime/Julia/semiprime.julia create mode 100644 Task/Semiprime/Mathematica/semiprime-1.math create mode 100644 Task/Semiprime/Mathematica/semiprime-2.math create mode 100644 Task/Semiprime/Objeck/semiprime.objeck create mode 100644 Task/Semiprime/PARI-GP/semiprime-1.pari create mode 100644 Task/Semiprime/PARI-GP/semiprime-2.pari create mode 100644 Task/Semiprime/PARI-GP/semiprime-3.pari create mode 100644 Task/Semiprime/PL-I/semiprime.pli create mode 100644 Task/Semiprime/Pascal/semiprime.pascal create mode 100644 Task/Semiprime/Perl-6/semiprime.pl6 create mode 100644 Task/Semiprime/Perl/semiprime-1.pl create mode 100644 Task/Semiprime/Perl/semiprime-2.pl create mode 100644 Task/Semiprime/PicoLisp/semiprime.l create mode 100644 Task/Semiprime/Python/semiprime-1.py create mode 100644 Task/Semiprime/Python/semiprime-2.py create mode 100644 Task/Semiprime/README create mode 100644 Task/Semiprime/REXX/semiprime-1.rexx create mode 100644 Task/Semiprime/REXX/semiprime-2.rexx create mode 100644 Task/Semiprime/Racket/semiprime-1.rkt create mode 100644 Task/Semiprime/Racket/semiprime-2.rkt create mode 100644 Task/Semiprime/Ruby/semiprime.rb create mode 100644 Task/Semiprime/Scala/semiprime.scala create mode 100644 Task/Semiprime/Seed7/semiprime.seed7 create mode 100644 Task/Semiprime/Tcl/semiprime.tcl create mode 100644 Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION create mode 100644 Task/Sequence-of-primes-by-Trial-Division/00META.yaml create mode 100644 Task/Sequence-of-primes-by-Trial-Division/ATS/sequence-of-primes-by-trial-division.ats create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Ada/sequence-of-primes-by-trial-division.ada create mode 100644 Task/Sequence-of-primes-by-Trial-Division/D/sequence-of-primes-by-trial-division.d create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-1.go create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-2.go create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-1.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-2.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-3.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-4.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-5.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-6.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-7.hs create mode 100644 Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-1.j create mode 100644 Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-2.j create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Perl-6/sequence-of-primes-by-trial-division.pl6 create mode 100644 Task/Sequence-of-primes-by-Trial-Division/README create mode 100644 Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-1.rexx create mode 100644 Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-1.rkt create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-2.rkt create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-3.rkt create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-4.rkt create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Ruby/sequence-of-primes-by-trial-division.rb create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Scala/sequence-of-primes-by-trial-division.scala create mode 100644 Task/Sequence-of-primes-by-Trial-Division/Tcl/sequence-of-primes-by-trial-division.tcl create mode 100644 Task/Solve-a-Holy-Knights-tour/00DESCRIPTION create mode 100644 Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada create mode 100644 Task/Solve-a-Holy-Knights-tour/Bracmat/solve-a-holy-knights-tour.bracmat create mode 100644 Task/Solve-a-Holy-Knights-tour/C++/solve-a-holy-knights-tour.cpp create mode 100644 Task/Solve-a-Holy-Knights-tour/D/solve-a-holy-knights-tour.d create mode 100644 Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs create mode 100644 Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs create mode 100644 Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-3.hs create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-1.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-2.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-3.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-4.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-5.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-6.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-7.j create mode 100644 Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-8.j create mode 100644 Task/Solve-a-Holy-Knights-tour/Perl-6/solve-a-holy-knights-tour.pl6 create mode 100644 Task/Solve-a-Holy-Knights-tour/README create mode 100644 Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx create mode 100644 Task/Solve-a-Holy-Knights-tour/Racket/solve-a-holy-knights-tour.rkt create mode 100644 Task/Solve-a-Holy-Knights-tour/Ruby/solve-a-holy-knights-tour.rb create mode 100644 Task/Solve-a-Holy-Knights-tour/Tcl/solve-a-holy-knights-tour.tcl create mode 100644 Task/Solve-a-Hopido-puzzle/00DESCRIPTION create mode 100644 Task/Solve-a-Hopido-puzzle/C++/solve-a-hopido-puzzle.cpp create mode 100644 Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d create mode 100644 Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d create mode 100644 Task/Solve-a-Hopido-puzzle/Perl-6/solve-a-hopido-puzzle.pl6 create mode 100644 Task/Solve-a-Hopido-puzzle/README create mode 100644 Task/Solve-a-Hopido-puzzle/REXX/solve-a-hopido-puzzle.rexx create mode 100644 Task/Solve-a-Hopido-puzzle/Racket/solve-a-hopido-puzzle.rkt create mode 100644 Task/Solve-a-Hopido-puzzle/Ruby/solve-a-hopido-puzzle.rb create mode 100644 Task/Solve-a-Hopido-puzzle/Tcl/solve-a-hopido-puzzle.tcl create mode 100644 Task/Solve-a-Numbrix-puzzle/00DESCRIPTION create mode 100644 Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp create mode 100644 Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d create mode 100644 Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d create mode 100644 Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-1.pl6 create mode 100644 Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-2.pl6 create mode 100644 Task/Solve-a-Numbrix-puzzle/README create mode 100644 Task/Solve-a-Numbrix-puzzle/REXX/solve-a-numbrix-puzzle.rexx create mode 100644 Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-1.rkt create mode 100644 Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-2.rkt create mode 100644 Task/Solve-a-Numbrix-puzzle/Ruby/solve-a-numbrix-puzzle.rb create mode 100644 Task/Solve-the-no-connection-puzzle/00DESCRIPTION create mode 100644 Task/Solve-the-no-connection-puzzle/00META.yaml create mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.ada create mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.ada create mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada create mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada create mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada create mode 100644 Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-1.d create mode 100644 Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-2.d create mode 100644 Task/Solve-the-no-connection-puzzle/Go/solve-the-no-connection-puzzle.go create mode 100644 Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-1.j create mode 100644 Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-2.j create mode 100644 Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-3.j create mode 100644 Task/Solve-the-no-connection-puzzle/Perl-6/solve-the-no-connection-puzzle.pl6 create mode 100644 Task/Solve-the-no-connection-puzzle/Prolog/solve-the-no-connection-puzzle.pro create mode 100644 Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-1.py create mode 100644 Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-2.py create mode 100644 Task/Solve-the-no-connection-puzzle/README create mode 100644 Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx create mode 100644 Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx create mode 100644 Task/Solve-the-no-connection-puzzle/Racket/solve-the-no-connection-puzzle.rkt create mode 100644 Task/Solve-the-no-connection-puzzle/Ruby/solve-the-no-connection-puzzle.rb create mode 100644 Task/Solve-the-no-connection-puzzle/Tcl/solve-the-no-connection-puzzle.tcl create mode 100644 Task/Solve-the-no-connection-puzzle/XPL0/solve-the-no-connection-puzzle.xpl0 create mode 100644 Task/Sparkline-in-unicode/00DESCRIPTION create mode 100644 Task/Sparkline-in-unicode/AutoHotkey/sparkline-in-unicode.ahk create mode 100644 Task/Sparkline-in-unicode/C++/sparkline-in-unicode.cpp create mode 100644 Task/Sparkline-in-unicode/D/sparkline-in-unicode.d create mode 100644 Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-1.elixir create mode 100644 Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-2.elixir create mode 100644 Task/Sparkline-in-unicode/FALSE/sparkline-in-unicode.false create mode 100644 Task/Sparkline-in-unicode/Go/sparkline-in-unicode.go create mode 100644 Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-1.groovy create mode 100644 Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-2.groovy create mode 100644 Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs create mode 100644 Task/Sparkline-in-unicode/J/sparkline-in-unicode-1.j create mode 100644 Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j create mode 100644 Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j create mode 100644 Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j create mode 100644 Task/Sparkline-in-unicode/Java/sparkline-in-unicode.java create mode 100644 Task/Sparkline-in-unicode/Mathematica/sparkline-in-unicode.math create mode 100644 Task/Sparkline-in-unicode/NetRexx/sparkline-in-unicode.netrexx create mode 100644 Task/Sparkline-in-unicode/Perl-6/sparkline-in-unicode.pl6 create mode 100644 Task/Sparkline-in-unicode/Perl/sparkline-in-unicode.pl create mode 100644 Task/Sparkline-in-unicode/Python/sparkline-in-unicode.py create mode 100644 Task/Sparkline-in-unicode/README create mode 100644 Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-1.rexx create mode 100644 Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-2.rexx create mode 100644 Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-1.rkt create mode 100644 Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-2.rkt create mode 100644 Task/Sparkline-in-unicode/Ruby/sparkline-in-unicode.rb create mode 100644 Task/Sparkline-in-unicode/Scala/sparkline-in-unicode.scala create mode 100644 Task/Sparkline-in-unicode/Seed7/sparkline-in-unicode.seed7 create mode 100644 Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-1.tcl create mode 100644 Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-2.tcl create mode 100644 Task/State-name-puzzle/00DESCRIPTION create mode 100644 Task/State-name-puzzle/00META.yaml create mode 100644 Task/State-name-puzzle/Bracmat/state-name-puzzle.bracmat create mode 100644 Task/State-name-puzzle/C/state-name-puzzle.c create mode 100644 Task/State-name-puzzle/D/state-name-puzzle.d create mode 100644 Task/State-name-puzzle/Go/state-name-puzzle.go create mode 100644 Task/State-name-puzzle/Icon/state-name-puzzle-1.icon create mode 100644 Task/State-name-puzzle/Icon/state-name-puzzle-2.icon create mode 100644 Task/State-name-puzzle/Icon/state-name-puzzle-3.icon create mode 100644 Task/State-name-puzzle/J/state-name-puzzle-1.j create mode 100644 Task/State-name-puzzle/J/state-name-puzzle-2.j create mode 100644 Task/State-name-puzzle/J/state-name-puzzle-3.j create mode 100644 Task/State-name-puzzle/J/state-name-puzzle-4.j create mode 100644 Task/State-name-puzzle/Java/state-name-puzzle.java create mode 100644 Task/State-name-puzzle/Mathematica/state-name-puzzle.math create mode 100644 Task/State-name-puzzle/Perl-6/state-name-puzzle.pl6 create mode 100644 Task/State-name-puzzle/Perl/state-name-puzzle.pl create mode 100644 Task/State-name-puzzle/PicoLisp/state-name-puzzle.l create mode 100644 Task/State-name-puzzle/Prolog/state-name-puzzle.pro create mode 100644 Task/State-name-puzzle/Python/state-name-puzzle.py create mode 100644 Task/State-name-puzzle/README create mode 100644 Task/State-name-puzzle/REXX/state-name-puzzle.rexx create mode 100644 Task/State-name-puzzle/Racket/state-name-puzzle-1.rkt create mode 100644 Task/State-name-puzzle/Racket/state-name-puzzle-2.rkt create mode 100644 Task/State-name-puzzle/Ruby/state-name-puzzle.rb create mode 100644 Task/State-name-puzzle/Scala/state-name-puzzle.scala create mode 100644 Task/State-name-puzzle/Tcl/state-name-puzzle.tcl create mode 100644 Task/Statistics-Basic/00DESCRIPTION create mode 100644 Task/Statistics-Basic/00META.yaml create mode 100644 Task/Statistics-Basic/Ada/statistics-basic-1.ada create mode 100644 Task/Statistics-Basic/Ada/statistics-basic-2.ada create mode 100644 Task/Statistics-Basic/C/statistics-basic.c create mode 100644 Task/Statistics-Basic/CoffeeScript/statistics-basic.coffee create mode 100644 Task/Statistics-Basic/D/statistics-basic.d create mode 100644 Task/Statistics-Basic/Dart/statistics-basic.dart create mode 100644 Task/Statistics-Basic/Fortran/statistics-basic.f create mode 100644 Task/Statistics-Basic/Go/statistics-basic-1.go create mode 100644 Task/Statistics-Basic/Go/statistics-basic-2.go create mode 100644 Task/Statistics-Basic/Icon/statistics-basic.icon create mode 100644 Task/Statistics-Basic/J/statistics-basic-1.j create mode 100644 Task/Statistics-Basic/J/statistics-basic-2.j create mode 100644 Task/Statistics-Basic/J/statistics-basic-3.j create mode 100644 Task/Statistics-Basic/J/statistics-basic-4.j create mode 100644 Task/Statistics-Basic/Liberty-BASIC/statistics-basic.liberty create mode 100644 Task/Statistics-Basic/MATLAB/statistics-basic.m create mode 100644 Task/Statistics-Basic/Mathematica/statistics-basic.math create mode 100644 Task/Statistics-Basic/PARI-GP/statistics-basic-1.pari create mode 100644 Task/Statistics-Basic/PARI-GP/statistics-basic-2.pari create mode 100644 Task/Statistics-Basic/PL-I/statistics-basic.pli create mode 100644 Task/Statistics-Basic/Perl-6/statistics-basic.pl6 create mode 100644 Task/Statistics-Basic/Perl/statistics-basic.pl create mode 100644 Task/Statistics-Basic/PicoLisp/statistics-basic-1.l create mode 100644 Task/Statistics-Basic/PicoLisp/statistics-basic-2.l create mode 100644 Task/Statistics-Basic/PureBasic/statistics-basic.purebasic create mode 100644 Task/Statistics-Basic/Python/statistics-basic.py create mode 100644 Task/Statistics-Basic/README create mode 100644 Task/Statistics-Basic/REXX/statistics-basic.rexx create mode 100644 Task/Statistics-Basic/Racket/statistics-basic.rkt create mode 100644 Task/Statistics-Basic/Ruby/statistics-basic.rb create mode 100644 Task/Statistics-Basic/Scala/statistics-basic.scala create mode 100644 Task/Statistics-Basic/Tcl/statistics-basic.tcl create mode 100644 Task/Stern-Brocot-sequence/00DESCRIPTION create mode 100644 Task/Stern-Brocot-sequence/C/stern-brocot-sequence-1.c create mode 100644 Task/Stern-Brocot-sequence/C/stern-brocot-sequence-2.c create mode 100644 Task/Stern-Brocot-sequence/Clojure/stern-brocot-sequence.clj create mode 100644 Task/Stern-Brocot-sequence/D/stern-brocot-sequence-1.d create mode 100644 Task/Stern-Brocot-sequence/D/stern-brocot-sequence-2.d create mode 100644 Task/Stern-Brocot-sequence/D/stern-brocot-sequence-3.d create mode 100644 Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-1.go create mode 100644 Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-2.go create mode 100644 Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs create mode 100644 Task/Stern-Brocot-sequence/J/stern-brocot-sequence-1.j create mode 100644 Task/Stern-Brocot-sequence/J/stern-brocot-sequence-2.j create mode 100644 Task/Stern-Brocot-sequence/J/stern-brocot-sequence-3.j create mode 100644 Task/Stern-Brocot-sequence/J/stern-brocot-sequence-4.j create mode 100644 Task/Stern-Brocot-sequence/J/stern-brocot-sequence-5.j create mode 100644 Task/Stern-Brocot-sequence/Java/stern-brocot-sequence.java create mode 100644 Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 create mode 100644 Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl create mode 100644 Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-1.py create mode 100644 Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-2.py create mode 100644 Task/Stern-Brocot-sequence/README create mode 100644 Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx create mode 100644 Task/Stern-Brocot-sequence/Racket/stern-brocot-sequence.rkt create mode 100644 Task/Stern-Brocot-sequence/Ruby/stern-brocot-sequence.rb create mode 100644 Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb create mode 100644 Task/String-append/00DESCRIPTION create mode 100644 Task/String-append/00META.yaml create mode 100644 Task/String-append/ALGOL-68/string-append.alg create mode 100644 Task/String-append/AWK/string-append.awk create mode 100644 Task/String-append/AutoHotkey/string-append.ahk create mode 100644 Task/String-append/BASIC/string-append-1.basic create mode 100644 Task/String-append/BASIC/string-append-2.basic create mode 100644 Task/String-append/C++/string-append.cpp create mode 100644 Task/String-append/C/string-append.c create mode 100644 Task/String-append/Clojure/string-append-1.clj create mode 100644 Task/String-append/Clojure/string-append-2.clj create mode 100644 Task/String-append/Common-Lisp/string-append.lisp create mode 100644 Task/String-append/D/string-append.d create mode 100644 Task/String-append/Euphoria/string-append.euphoria create mode 100644 Task/String-append/Go/string-append.go create mode 100644 Task/String-append/Haskell/string-append.hs create mode 100644 Task/String-append/Icon/string-append.icon create mode 100644 Task/String-append/J/string-append.j create mode 100644 Task/String-append/Java/string-append.java create mode 100644 Task/String-append/JavaScript/string-append.js create mode 100644 Task/String-append/Julia/string-append.julia create mode 100644 Task/String-append/Mathematica/string-append.math create mode 100644 Task/String-append/NetRexx/string-append.netrexx create mode 100644 Task/String-append/NewLISP/string-append.newlisp create mode 100644 Task/String-append/OCaml/string-append.ocaml create mode 100644 Task/String-append/Objeck/string-append.objeck create mode 100644 Task/String-append/PARI-GP/string-append.pari create mode 100644 Task/String-append/PL-I/string-append.pli create mode 100644 Task/String-append/Pascal/string-append.pascal create mode 100644 Task/String-append/Perl-6/string-append.pl6 create mode 100644 Task/String-append/Perl/string-append.pl create mode 100644 Task/String-append/PicoLisp/string-append.l create mode 100644 Task/String-append/PureBasic/string-append.purebasic create mode 100644 Task/String-append/Python/string-append.py create mode 100644 Task/String-append/README create mode 100644 Task/String-append/REXX/string-append-1.rexx create mode 100644 Task/String-append/REXX/string-append-2.rexx create mode 100644 Task/String-append/Racket/string-append.rkt create mode 100644 Task/String-append/Ruby/string-append.rb create mode 100644 Task/String-append/Scala/string-append.scala create mode 100644 Task/String-append/Seed7/string-append.seed7 create mode 100644 Task/String-append/Tcl/string-append.tcl create mode 100644 Task/String-append/VBA/string-append.vba rename Task/{Character-matching => String-matching}/00DESCRIPTION (100%) rename Task/{Character-matching => String-matching}/00META.yaml (100%) rename Task/{Character-matching/ALGOL-68/character-matching.alg => String-matching/ALGOL-68/string-matching.alg} (100%) create mode 100644 Task/String-matching/AWK/string-matching.awk rename Task/{Character-matching/Ada/character-matching.ada => String-matching/Ada/string-matching.ada} (100%) create mode 100644 Task/String-matching/Aime/string-matching.aime rename Task/{Character-matching/AutoHotkey/character-matching.ahk => String-matching/AutoHotkey/string-matching.ahk} (100%) rename Task/{Character-matching/AutoIt/character-matching.autoit => String-matching/AutoIt/string-matching.autoit} (100%) rename Task/{Character-matching/BASIC/character-matching.basic => String-matching/BASIC/string-matching-1.basic} (100%) create mode 100644 Task/String-matching/BASIC/string-matching-2.basic rename Task/{Character-matching/BBC-BASIC/character-matching.bbc => String-matching/BBC-BASIC/string-matching.bbc} (100%) rename Task/{Character-matching/Bracmat/character-matching.bracmat => String-matching/Bracmat/string-matching.bracmat} (100%) rename Task/{Character-matching/C++/character-matching.cpp => String-matching/C++/string-matching.cpp} (100%) rename Task/{Character-matching/C/character-matching-1.c => String-matching/C/string-matching-1.c} (100%) rename Task/{Character-matching/C/character-matching-2.c => String-matching/C/string-matching-2.c} (100%) rename Task/{Character-matching/Clojure/character-matching.clj => String-matching/Clojure/string-matching.clj} (100%) rename Task/{Character-matching/CoffeeScript/character-matching.coffee => String-matching/CoffeeScript/string-matching.coffee} (100%) create mode 100644 Task/String-matching/Common-Lisp/string-matching.lisp create mode 100644 Task/String-matching/Component-Pascal/string-matching.component create mode 100644 Task/String-matching/D/string-matching.d rename Task/{Character-matching/Delphi/character-matching.delphi => String-matching/Delphi/string-matching.delphi} (100%) rename Task/{Character-matching/E/character-matching.e => String-matching/E/string-matching.e} (100%) create mode 100644 Task/String-matching/Elena/string-matching.elena create mode 100644 Task/String-matching/Elixir/string-matching.elixir rename Task/{Character-matching/Erlang/character-matching.erl => String-matching/Erlang/string-matching.erl} (100%) rename Task/{Character-matching/Euphoria/character-matching.euphoria => String-matching/Euphoria/string-matching.euphoria} (100%) rename Task/{Character-matching/FBSL/character-matching.fbsl => String-matching/FBSL/string-matching.fbsl} (100%) rename Task/{Character-matching/Fantom/character-matching.fantom => String-matching/Fantom/string-matching.fantom} (100%) rename Task/{Character-matching/Forth/character-matching.fth => String-matching/Forth/string-matching.fth} (100%) rename Task/{Character-matching/GML/character-matching.gml => String-matching/GML/string-matching.gml} (100%) rename Task/{Character-matching/Go/character-matching.go => String-matching/Go/string-matching.go} (100%) create mode 100644 Task/String-matching/Groovy/string-matching.groovy rename Task/{Character-matching/Haskell/character-matching-1.hs => String-matching/Haskell/string-matching-1.hs} (100%) rename Task/{Character-matching/Haskell/character-matching-2.hs => String-matching/Haskell/string-matching-2.hs} (100%) rename Task/{Character-matching/J/character-matching-1.j => String-matching/J/string-matching-1.j} (100%) rename Task/{Character-matching/J/character-matching-2.j => String-matching/J/string-matching-2.j} (100%) rename Task/{Character-matching/J/character-matching-3.j => String-matching/J/string-matching-3.j} (100%) rename Task/{Character-matching/Java/character-matching.java => String-matching/Java/string-matching.java} (100%) rename Task/{Character-matching/JavaScript/character-matching.js => String-matching/JavaScript/string-matching.js} (100%) rename Task/{Character-matching/Julia/character-matching.julia => String-matching/Julia/string-matching.julia} (100%) rename Task/{Character-matching/K/character-matching-1.k => String-matching/K/string-matching-1.k} (100%) rename Task/{Character-matching/K/character-matching-2.k => String-matching/K/string-matching-2.k} (100%) rename Task/{Character-matching/Lang5/character-matching.lang5 => String-matching/Lang5/string-matching.lang5} (100%) rename Task/{Character-matching/Liberty-BASIC/character-matching.liberty => String-matching/Liberty-BASIC/string-matching.liberty} (100%) rename Task/{Character-matching/Logo/character-matching.logo => String-matching/Logo/string-matching.logo} (100%) rename Task/{Character-matching/Lua/character-matching.lua => String-matching/Lua/string-matching.lua} (100%) rename Task/{Character-matching/MATLAB/character-matching.m => String-matching/MATLAB/string-matching.m} (100%) rename Task/{Character-matching/Maple/character-matching.maple => String-matching/Maple/string-matching.maple} (100%) rename Task/{Character-matching/Mathematica/character-matching.math => String-matching/Mathematica/string-matching.math} (100%) rename Task/{Character-matching/NetRexx/character-matching.netrexx => String-matching/NetRexx/string-matching.netrexx} (100%) create mode 100644 Task/String-matching/NewLISP/string-matching.newlisp rename Task/{Character-matching/OCaml/character-matching-1.ocaml => String-matching/OCaml/string-matching-1.ocaml} (100%) rename Task/{Character-matching/OCaml/character-matching-2.ocaml => String-matching/OCaml/string-matching-2.ocaml} (100%) rename Task/{Character-matching/OCaml/character-matching-3.ocaml => String-matching/OCaml/string-matching-3.ocaml} (100%) rename Task/{Character-matching/OCaml/character-matching-4.ocaml => String-matching/OCaml/string-matching-4.ocaml} (100%) rename Task/{Character-matching/OCaml/character-matching-5.ocaml => String-matching/OCaml/string-matching-5.ocaml} (100%) rename Task/{Character-matching/Objeck/character-matching.objeck => String-matching/Objeck/string-matching.objeck} (100%) rename Task/{Character-matching/Objective-C/character-matching.m => String-matching/Objective-C/string-matching.m} (100%) rename Task/{Character-matching/OxygenBasic/character-matching.oxy => String-matching/OxygenBasic/string-matching.oxy} (100%) rename Task/{Character-matching/PARI-GP/character-matching.pari => String-matching/PARI-GP/string-matching.pari} (100%) rename Task/{Character-matching/PHP/character-matching-1.php => String-matching/PHP/string-matching-1.php} (100%) rename Task/{Character-matching/PHP/character-matching-2.php => String-matching/PHP/string-matching-2.php} (100%) rename Task/{Character-matching/PL-I/character-matching-1.pli => String-matching/PL-I/string-matching-1.pli} (100%) rename Task/{Character-matching/PL-I/character-matching-2.pli => String-matching/PL-I/string-matching-2.pli} (100%) rename Task/{Character-matching/Perl-6/character-matching.pl6 => String-matching/Perl-6/string-matching.pl6} (100%) create mode 100644 Task/String-matching/Perl/string-matching-1.pl create mode 100644 Task/String-matching/Perl/string-matching-2.pl create mode 100644 Task/String-matching/Perl/string-matching-3.pl create mode 100644 Task/String-matching/Perl/string-matching-4.pl create mode 100644 Task/String-matching/Perl/string-matching-5.pl rename Task/{Character-matching/PicoLisp/character-matching.l => String-matching/PicoLisp/string-matching.l} (100%) rename Task/{Character-matching/PowerShell/character-matching.psh => String-matching/PowerShell/string-matching.psh} (100%) rename Task/{Character-matching/PureBasic/character-matching-1.purebasic => String-matching/PureBasic/string-matching-1.purebasic} (100%) rename Task/{Character-matching/PureBasic/character-matching-2.purebasic => String-matching/PureBasic/string-matching-2.purebasic} (100%) rename Task/{Character-matching/PureBasic/character-matching-3.purebasic => String-matching/PureBasic/string-matching-3.purebasic} (100%) rename Task/{Character-matching/Python/character-matching.py => String-matching/Python/string-matching.py} (100%) create mode 100644 Task/String-matching/README create mode 100644 Task/String-matching/REXX/string-matching.rexx rename Task/{Character-matching/Racket/character-matching.rkt => String-matching/Racket/string-matching.rkt} (100%) rename Task/{Character-matching/Retro/character-matching.retro => String-matching/Retro/string-matching.retro} (100%) rename Task/{Character-matching/Ruby/character-matching.rb => String-matching/Ruby/string-matching.rb} (100%) rename Task/{Character-matching/Run-BASIC/character-matching.run => String-matching/Run-BASIC/string-matching.run} (100%) rename Task/{Character-matching/Scala/character-matching.scala => String-matching/Scala/string-matching.scala} (100%) rename Task/{Character-matching/Seed7/character-matching.seed7 => String-matching/Seed7/string-matching.seed7} (100%) rename Task/{Character-matching/Smalltalk/character-matching.st => String-matching/Smalltalk/string-matching.st} (100%) rename Task/{Character-matching/Standard-ML/character-matching.ml => String-matching/Standard-ML/string-matching.ml} (100%) rename Task/{Character-matching/TUSCRIPT/character-matching.tu => String-matching/TUSCRIPT/string-matching.tu} (100%) create mode 100644 Task/String-matching/TXR/string-matching-1.txr rename Task/{Character-matching/TXR/character-matching.txr => String-matching/TXR/string-matching-2.txr} (100%) rename Task/{Character-matching/Tcl/character-matching-1.tcl => String-matching/Tcl/string-matching-1.tcl} (100%) rename Task/{Character-matching/Tcl/character-matching-2.tcl => String-matching/Tcl/string-matching-2.tcl} (100%) rename Task/{Character-matching/Tcl/character-matching-3.tcl => String-matching/Tcl/string-matching-3.tcl} (100%) rename Task/{Character-matching/Tcl/character-matching-4.tcl => String-matching/Tcl/string-matching-4.tcl} (100%) rename Task/{Character-matching/XPL0/character-matching.xpl0 => String-matching/XPL0/string-matching.xpl0} (100%) create mode 100644 Task/String-prepend/00DESCRIPTION create mode 100644 Task/String-prepend/00META.yaml create mode 100644 Task/String-prepend/ALGOL-68/string-prepend.alg create mode 100644 Task/String-prepend/AWK/string-prepend.awk create mode 100644 Task/String-prepend/AutoHotkey/string-prepend.ahk create mode 100644 Task/String-prepend/BASIC/string-prepend.basic create mode 100644 Task/String-prepend/Bracmat/string-prepend.bracmat create mode 100644 Task/String-prepend/C++/string-prepend.cpp create mode 100644 Task/String-prepend/C-sharp/string-prepend.cs create mode 100644 Task/String-prepend/C/string-prepend.c create mode 100644 Task/String-prepend/COBOL/string-prepend.cobol create mode 100644 Task/String-prepend/Clojure/string-prepend.clj create mode 100644 Task/String-prepend/Common-Lisp/string-prepend.lisp create mode 100644 Task/String-prepend/D/string-prepend.d create mode 100644 Task/String-prepend/Deja-Vu/string-prepend.djv create mode 100644 Task/String-prepend/Factor/string-prepend.factor create mode 100644 Task/String-prepend/Go/string-prepend.go create mode 100644 Task/String-prepend/Haskell/string-prepend.hs create mode 100644 Task/String-prepend/Icon/string-prepend.icon create mode 100644 Task/String-prepend/J/string-prepend.j create mode 100644 Task/String-prepend/Java/string-prepend.java create mode 100644 Task/String-prepend/Julia/string-prepend.julia create mode 100644 Task/String-prepend/Lua/string-prepend-1.lua create mode 100644 Task/String-prepend/Lua/string-prepend-2.lua create mode 100644 Task/String-prepend/Lua/string-prepend-3.lua create mode 100644 Task/String-prepend/Mathematica/string-prepend.math create mode 100644 Task/String-prepend/Mercury/string-prepend.mercury create mode 100644 Task/String-prepend/NetRexx/string-prepend.netrexx create mode 100644 Task/String-prepend/NewLISP/string-prepend.newlisp create mode 100644 Task/String-prepend/PARI-GP/string-prepend.pari create mode 100644 Task/String-prepend/PL-I/string-prepend.pli create mode 100644 Task/String-prepend/Pascal/string-prepend.pascal create mode 100644 Task/String-prepend/Perl-6/string-prepend.pl6 create mode 100644 Task/String-prepend/Perl/string-prepend.pl create mode 100644 Task/String-prepend/PicoLisp/string-prepend.l create mode 100644 Task/String-prepend/Prolog/string-prepend-1.pro create mode 100644 Task/String-prepend/Prolog/string-prepend-2.pro create mode 100644 Task/String-prepend/PureBasic/string-prepend.purebasic create mode 100644 Task/String-prepend/Python/string-prepend.py create mode 100644 Task/String-prepend/README create mode 100644 Task/String-prepend/REXX/string-prepend.rexx create mode 100644 Task/String-prepend/Racket/string-prepend.rkt create mode 100644 Task/String-prepend/Ruby/string-prepend.rb create mode 100644 Task/String-prepend/Scala/string-prepend.scala create mode 100644 Task/String-prepend/Seed7/string-prepend.seed7 create mode 100644 Task/String-prepend/Tcl/string-prepend.tcl create mode 100644 Task/String-prepend/VBA/string-prepend.vba create mode 100644 Task/Sum-multiples-of-3-and-5/00DESCRIPTION create mode 100644 Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-1.awk create mode 100644 Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-2.awk create mode 100644 Task/Sum-multiples-of-3-and-5/AutoHotkey/sum-multiples-of-3-and-5.ahk create mode 100644 Task/Sum-multiples-of-3-and-5/C++/sum-multiples-of-3-and-5.cpp create mode 100644 Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-1.c create mode 100644 Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-2.c create mode 100644 Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-1.cobol create mode 100644 Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-2.cobol create mode 100644 Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-1.clj create mode 100644 Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-2.clj create mode 100644 Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-1.lisp create mode 100644 Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-2.lisp create mode 100644 Task/Sum-multiples-of-3-and-5/Component-Pascal/sum-multiples-of-3-and-5.component create mode 100644 Task/Sum-multiples-of-3-and-5/D/sum-multiples-of-3-and-5.d create mode 100644 Task/Sum-multiples-of-3-and-5/Deja-Vu/sum-multiples-of-3-and-5.djv create mode 100644 Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi create mode 100644 Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e create mode 100644 Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e create mode 100644 Task/Sum-multiples-of-3-and-5/Erlang/sum-multiples-of-3-and-5.erl create mode 100644 Task/Sum-multiples-of-3-and-5/FBSL/sum-multiples-of-3-and-5.fbsl create mode 100644 Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-1.fth create mode 100644 Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-2.fth create mode 100644 Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-1.go create mode 100644 Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-2.go create mode 100644 Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-1.groovy create mode 100644 Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-2.groovy create mode 100644 Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs create mode 100644 Task/Sum-multiples-of-3-and-5/Icon/sum-multiples-of-3-and-5.icon create mode 100644 Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-1.j create mode 100644 Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-2.j create mode 100644 Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-3.j create mode 100644 Task/Sum-multiples-of-3-and-5/Java/sum-multiples-of-3-and-5.java create mode 100644 Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia create mode 100644 Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia create mode 100644 Task/Sum-multiples-of-3-and-5/Limbo/sum-multiples-of-3-and-5.limbo create mode 100644 Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-1.m create mode 100644 Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-2.m create mode 100644 Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-3.m create mode 100644 Task/Sum-multiples-of-3-and-5/Maple/sum-multiples-of-3-and-5.maple create mode 100644 Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-1.math create mode 100644 Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-2.math create mode 100644 Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-3.math create mode 100644 Task/Sum-multiples-of-3-and-5/Maxima/sum-multiples-of-3-and-5.maxima create mode 100644 Task/Sum-multiples-of-3-and-5/NetRexx/sum-multiples-of-3-and-5.netrexx create mode 100644 Task/Sum-multiples-of-3-and-5/PARI-GP/sum-multiples-of-3-and-5.pari create mode 100644 Task/Sum-multiples-of-3-and-5/PL-I/sum-multiples-of-3-and-5.pli create mode 100644 Task/Sum-multiples-of-3-and-5/Pascal/sum-multiples-of-3-and-5.pascal create mode 100644 Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-1.pl6 create mode 100644 Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-2.pl6 create mode 100644 Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-1.pl create mode 100644 Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-2.pl create mode 100644 Task/Sum-multiples-of-3-and-5/PicoLisp/sum-multiples-of-3-and-5.l create mode 100644 Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5.psh create mode 100644 Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-1.pro create mode 100644 Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-2.pro create mode 100644 Task/Sum-multiples-of-3-and-5/Python/sum-multiples-of-3-and-5.py create mode 100644 Task/Sum-multiples-of-3-and-5/R/sum-multiples-of-3-and-5.r create mode 100644 Task/Sum-multiples-of-3-and-5/README create mode 100644 Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-1.rexx create mode 100644 Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-2.rexx create mode 100644 Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-3.rexx create mode 100644 Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-1.rkt create mode 100644 Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-2.rkt create mode 100644 Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-1.rb create mode 100644 Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-2.rb create mode 100644 Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-3.rb create mode 100644 Task/Sum-multiples-of-3-and-5/Run-BASIC/sum-multiples-of-3-and-5.run create mode 100644 Task/Sum-multiples-of-3-and-5/Scala/sum-multiples-of-3-and-5.scala create mode 100644 Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss create mode 100644 Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss create mode 100644 Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss create mode 100644 Task/Sum-multiples-of-3-and-5/Seed7/sum-multiples-of-3-and-5.seed7 create mode 100644 Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-1.tcl create mode 100644 Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-2.tcl create mode 100644 Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-3.tcl create mode 100644 Task/Sum-multiples-of-3-and-5/XPL0/sum-multiples-of-3-and-5.xpl0 create mode 100644 Task/Textonyms/00DESCRIPTION create mode 100644 Task/Textonyms/Go/textonyms.go create mode 100644 Task/Textonyms/J/textonyms-1.j create mode 100644 Task/Textonyms/J/textonyms-2.j create mode 100644 Task/Textonyms/J/textonyms-3.j create mode 100644 Task/Textonyms/J/textonyms-4.j create mode 100644 Task/Textonyms/Perl-6/textonyms.pl6 create mode 100644 Task/Textonyms/Perl/textonyms.pl create mode 100644 Task/Textonyms/Python/textonyms.py create mode 100644 Task/Textonyms/README create mode 100644 Task/Textonyms/REXX/textonyms.rexx create mode 100644 Task/Textonyms/Ruby/textonyms.rb create mode 100644 Task/Textonyms/VBScript/textonyms.vb create mode 100644 Task/The-ISAAC-Cipher/00DESCRIPTION create mode 100644 Task/The-ISAAC-Cipher/00META.yaml create mode 100644 Task/The-ISAAC-Cipher/C-sharp/the-isaac-cipher.cs create mode 100644 Task/The-ISAAC-Cipher/C/the-isaac-cipher.c create mode 100644 Task/The-ISAAC-Cipher/D/the-isaac-cipher.d create mode 100644 Task/The-ISAAC-Cipher/Delphi/the-isaac-cipher.delphi create mode 100644 Task/The-ISAAC-Cipher/Go/the-isaac-cipher.go create mode 100644 Task/The-ISAAC-Cipher/Haskell/the-isaac-cipher.hs create mode 100644 Task/The-ISAAC-Cipher/Haxe/the-isaac-cipher.haxe create mode 100644 Task/The-ISAAC-Cipher/Java/the-isaac-cipher.java create mode 100644 Task/The-ISAAC-Cipher/Pascal/the-isaac-cipher.pascal create mode 100644 Task/The-ISAAC-Cipher/Perl/the-isaac-cipher.pl create mode 100644 Task/The-ISAAC-Cipher/PicoLisp/the-isaac-cipher.l create mode 100644 Task/The-ISAAC-Cipher/Python/the-isaac-cipher.py create mode 100644 Task/The-ISAAC-Cipher/README create mode 100644 Task/The-ISAAC-Cipher/REXX/the-isaac-cipher-1.rexx create mode 100644 Task/The-ISAAC-Cipher/REXX/the-isaac-cipher-2.rexx create mode 100644 Task/The-ISAAC-Cipher/Racket/the-isaac-cipher.rkt create mode 100644 Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-1.tcl create mode 100644 Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-2.tcl create mode 100644 Task/The-Twelve-Days-of-Christmas/00DESCRIPTION create mode 100644 Task/The-Twelve-Days-of-Christmas/AWK/the-twelve-days-of-christmas.awk create mode 100644 Task/The-Twelve-Days-of-Christmas/ActionScript/the-twelve-days-of-christmas.as create mode 100644 Task/The-Twelve-Days-of-Christmas/Ada/the-twelve-days-of-christmas.ada create mode 100644 Task/The-Twelve-Days-of-Christmas/AutoHotkey/the-twelve-days-of-christmas.ahk create mode 100644 Task/The-Twelve-Days-of-Christmas/Bracmat/the-twelve-days-of-christmas.bracmat create mode 100644 Task/The-Twelve-Days-of-Christmas/C++/the-twelve-days-of-christmas.cpp create mode 100644 Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c create mode 100644 Task/The-Twelve-Days-of-Christmas/COBOL/the-twelve-days-of-christmas.cobol create mode 100644 Task/The-Twelve-Days-of-Christmas/Clojure/the-twelve-days-of-christmas.clj create mode 100644 Task/The-Twelve-Days-of-Christmas/D/the-twelve-days-of-christmas.d create mode 100644 Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go create mode 100644 Task/The-Twelve-Days-of-Christmas/Groovy/the-twelve-days-of-christmas.groovy create mode 100644 Task/The-Twelve-Days-of-Christmas/Icon/the-twelve-days-of-christmas.icon create mode 100644 Task/The-Twelve-Days-of-Christmas/J/the-twelve-days-of-christmas.j create mode 100644 Task/The-Twelve-Days-of-Christmas/Java/the-twelve-days-of-christmas.java create mode 100644 Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas.js create mode 100644 Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol create mode 100644 Task/The-Twelve-Days-of-Christmas/Logo/the-twelve-days-of-christmas.logo create mode 100644 Task/The-Twelve-Days-of-Christmas/Lua/the-twelve-days-of-christmas.lua create mode 100644 Task/The-Twelve-Days-of-Christmas/Mathematica/the-twelve-days-of-christmas.math create mode 100644 Task/The-Twelve-Days-of-Christmas/Objeck/the-twelve-days-of-christmas.objeck create mode 100644 Task/The-Twelve-Days-of-Christmas/PHP/the-twelve-days-of-christmas.php create mode 100644 Task/The-Twelve-Days-of-Christmas/Perl-6/the-twelve-days-of-christmas.pl6 create mode 100644 Task/The-Twelve-Days-of-Christmas/Perl/the-twelve-days-of-christmas.pl create mode 100644 Task/The-Twelve-Days-of-Christmas/PicoLisp/the-twelve-days-of-christmas.l create mode 100644 Task/The-Twelve-Days-of-Christmas/PowerShell/the-twelve-days-of-christmas.psh create mode 100644 Task/The-Twelve-Days-of-Christmas/Python/the-twelve-days-of-christmas.py create mode 100644 Task/The-Twelve-Days-of-Christmas/README create mode 100644 Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx create mode 100644 Task/The-Twelve-Days-of-Christmas/Racket/the-twelve-days-of-christmas.rkt create mode 100644 Task/The-Twelve-Days-of-Christmas/Ruby/the-twelve-days-of-christmas.rb create mode 100644 Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust create mode 100644 Task/The-Twelve-Days-of-Christmas/Seed7/the-twelve-days-of-christmas.seed7 create mode 100644 Task/The-Twelve-Days-of-Christmas/Tcl/the-twelve-days-of-christmas.tcl create mode 100644 Task/Total-circles-area/00DESCRIPTION create mode 100644 Task/Total-circles-area/C/total-circles-area-1.c create mode 100644 Task/Total-circles-area/C/total-circles-area-2.c create mode 100644 Task/Total-circles-area/D/total-circles-area-1.d create mode 100644 Task/Total-circles-area/D/total-circles-area-2.d create mode 100644 Task/Total-circles-area/Go/total-circles-area.go create mode 100644 Task/Total-circles-area/Haskell/total-circles-area-1.hs create mode 100644 Task/Total-circles-area/Haskell/total-circles-area-2.hs create mode 100644 Task/Total-circles-area/J/total-circles-area.j create mode 100644 Task/Total-circles-area/Julia/total-circles-area.julia create mode 100644 Task/Total-circles-area/MATLAB/total-circles-area.m create mode 100644 Task/Total-circles-area/Mathematica/total-circles-area-1.math create mode 100644 Task/Total-circles-area/Mathematica/total-circles-area-2.math create mode 100644 Task/Total-circles-area/Perl-6/total-circles-area.pl6 create mode 100644 Task/Total-circles-area/Python/total-circles-area-1.py create mode 100644 Task/Total-circles-area/Python/total-circles-area-2.py create mode 100644 Task/Total-circles-area/Python/total-circles-area-3.py create mode 100644 Task/Total-circles-area/Python/total-circles-area-4.py create mode 100644 Task/Total-circles-area/README create mode 100644 Task/Total-circles-area/REXX/total-circles-area-1.rexx create mode 100644 Task/Total-circles-area/REXX/total-circles-area-2.rexx create mode 100644 Task/Total-circles-area/Ruby/total-circles-area-1.rb create mode 100644 Task/Total-circles-area/Ruby/total-circles-area-2.rb create mode 100644 Task/Total-circles-area/Ruby/total-circles-area-3.rb create mode 100644 Task/Total-circles-area/Tcl/total-circles-area.tcl create mode 100644 Task/Ulam-spiral--for-primes-/00DESCRIPTION create mode 100644 Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--1.ada create mode 100644 Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--2.ada create mode 100644 Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada create mode 100644 Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c create mode 100644 Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--2.c create mode 100644 Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--1.d create mode 100644 Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--2.d create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--1.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--2.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--3.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--4.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--5.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--6.j create mode 100644 Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--7.j create mode 100644 Task/Ulam-spiral--for-primes-/Java/ulam-spiral--for-primes-.java create mode 100644 Task/Ulam-spiral--for-primes-/Perl-6/ulam-spiral--for-primes-.pl6 create mode 100644 Task/Ulam-spiral--for-primes-/Perl/ulam-spiral--for-primes-.pl create mode 100644 Task/Ulam-spiral--for-primes-/Python/ulam-spiral--for-primes-.py create mode 100644 Task/Ulam-spiral--for-primes-/README create mode 100644 Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--1.rexx create mode 100644 Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--2.rexx create mode 100644 Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt create mode 100644 Task/Unix-ls/00DESCRIPTION create mode 100644 Task/Unix-ls/AWK/unix-ls.awk create mode 100644 Task/Unix-ls/Ada/unix-ls.ada create mode 100644 Task/Unix-ls/C/unix-ls.c create mode 100644 Task/Unix-ls/Clojure/unix-ls.clj create mode 100644 Task/Unix-ls/D/unix-ls.d create mode 100644 Task/Unix-ls/Forth/unix-ls-1.fth create mode 100644 Task/Unix-ls/Forth/unix-ls-2.fth create mode 100644 Task/Unix-ls/Go/unix-ls.go create mode 100644 Task/Unix-ls/Haskell/unix-ls.hs create mode 100644 Task/Unix-ls/J/unix-ls.j create mode 100644 Task/Unix-ls/Mathematica/unix-ls.math create mode 100644 Task/Unix-ls/OCaml/unix-ls.ocaml create mode 100644 Task/Unix-ls/PARI-GP/unix-ls-1.pari create mode 100644 Task/Unix-ls/PARI-GP/unix-ls-2.pari create mode 100644 Task/Unix-ls/Perl-6/unix-ls.pl6 create mode 100644 Task/Unix-ls/Python/unix-ls.py create mode 100644 Task/Unix-ls/README create mode 100644 Task/Unix-ls/REXX/unix-ls.rexx create mode 100644 Task/Unix-ls/Racket/unix-ls.rkt create mode 100644 Task/Unix-ls/Ruby/unix-ls.rb create mode 100644 Task/Unix-ls/Rust/unix-ls.rust create mode 100644 Task/Unix-ls/Tcl/unix-ls.tcl create mode 100644 Task/Vogels-approximation-method/00DESCRIPTION create mode 100644 Task/Vogels-approximation-method/D/vogels-approximation-method.d create mode 100644 Task/Vogels-approximation-method/Java/vogels-approximation-method.java create mode 100644 Task/Vogels-approximation-method/Python/vogels-approximation-method.py create mode 100644 Task/Vogels-approximation-method/README create mode 100644 Task/Vogels-approximation-method/Racket/vogels-approximation-method.rkt create mode 100644 Task/Vogels-approximation-method/Ruby/vogels-approximation-method-1.rb create mode 100644 Task/Vogels-approximation-method/Ruby/vogels-approximation-method-2.rb create mode 100644 Task/Vogels-approximation-method/Tcl/vogels-approximation-method-1.tcl create mode 100644 Task/Vogels-approximation-method/Tcl/vogels-approximation-method-2.tcl create mode 100644 Task/World-Cup-group-stage/00DESCRIPTION create mode 100644 Task/World-Cup-group-stage/D/world-cup-group-stage-1.d create mode 100644 Task/World-Cup-group-stage/D/world-cup-group-stage-2.d create mode 100644 Task/World-Cup-group-stage/Erlang/world-cup-group-stage.erl create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-1.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-2.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-3.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-4.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-5.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-6.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-7.j create mode 100644 Task/World-Cup-group-stage/J/world-cup-group-stage-8.j create mode 100644 Task/World-Cup-group-stage/Java/world-cup-group-stage.java create mode 100644 Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 create mode 100644 Task/World-Cup-group-stage/Python/world-cup-group-stage.py create mode 100644 Task/World-Cup-group-stage/README create mode 100644 Task/World-Cup-group-stage/Racket/world-cup-group-stage.rkt create mode 100644 Task/World-Cup-group-stage/Ruby/world-cup-group-stage.rb create mode 100644 Task/World-Cup-group-stage/Tcl/world-cup-group-stage.tcl create mode 100644 Task/Zero-to-the-zero-power/00DESCRIPTION create mode 100644 Task/Zero-to-the-zero-power/ALGOL-68/zero-to-the-zero-power.alg create mode 100644 Task/Zero-to-the-zero-power/AWK/zero-to-the-zero-power.awk create mode 100644 Task/Zero-to-the-zero-power/Ada/zero-to-the-zero-power.ada create mode 100644 Task/Zero-to-the-zero-power/AutoHotkey/zero-to-the-zero-power.ahk create mode 100644 Task/Zero-to-the-zero-power/Bracmat/zero-to-the-zero-power.bracmat create mode 100644 Task/Zero-to-the-zero-power/C++/zero-to-the-zero-power.cpp create mode 100644 Task/Zero-to-the-zero-power/C/zero-to-the-zero-power.c create mode 100644 Task/Zero-to-the-zero-power/D/zero-to-the-zero-power.d create mode 100644 Task/Zero-to-the-zero-power/Factor/zero-to-the-zero-power.factor create mode 100644 Task/Zero-to-the-zero-power/Forth/zero-to-the-zero-power.fth create mode 100644 Task/Zero-to-the-zero-power/Fortran/zero-to-the-zero-power.f create mode 100644 Task/Zero-to-the-zero-power/Go/zero-to-the-zero-power.go create mode 100644 Task/Zero-to-the-zero-power/Groovy/zero-to-the-zero-power.groovy create mode 100644 Task/Zero-to-the-zero-power/Haskell/zero-to-the-zero-power.hs create mode 100644 Task/Zero-to-the-zero-power/Icon/zero-to-the-zero-power.icon create mode 100644 Task/Zero-to-the-zero-power/J/zero-to-the-zero-power.j create mode 100644 Task/Zero-to-the-zero-power/Java/zero-to-the-zero-power.java create mode 100644 Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js create mode 100644 Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-1.maple create mode 100644 Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-2.maple create mode 100644 Task/Zero-to-the-zero-power/Mathematica/zero-to-the-zero-power.math create mode 100644 Task/Zero-to-the-zero-power/NetRexx/zero-to-the-zero-power.netrexx create mode 100644 Task/Zero-to-the-zero-power/PARI-GP/zero-to-the-zero-power.pari create mode 100644 Task/Zero-to-the-zero-power/PHP/zero-to-the-zero-power.php create mode 100644 Task/Zero-to-the-zero-power/PL-I/zero-to-the-zero-power.pli create mode 100644 Task/Zero-to-the-zero-power/Perl-6/zero-to-the-zero-power.pl6 create mode 100644 Task/Zero-to-the-zero-power/Perl/zero-to-the-zero-power.pl create mode 100644 Task/Zero-to-the-zero-power/PowerShell/zero-to-the-zero-power.psh create mode 100644 Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power.py create mode 100644 Task/Zero-to-the-zero-power/README create mode 100644 Task/Zero-to-the-zero-power/REXX/zero-to-the-zero-power.rexx create mode 100644 Task/Zero-to-the-zero-power/Racket/zero-to-the-zero-power.rkt create mode 100644 Task/Zero-to-the-zero-power/Ruby/zero-to-the-zero-power.rb create mode 100644 Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust create mode 100644 Task/Zero-to-the-zero-power/Scala/zero-to-the-zero-power.scala create mode 100644 Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss create mode 100644 Task/Zero-to-the-zero-power/Seed7/zero-to-the-zero-power.seed7 create mode 100644 Task/Zero-to-the-zero-power/Smalltalk/zero-to-the-zero-power.st create mode 100644 Task/Zero-to-the-zero-power/Tcl/zero-to-the-zero-power.tcl create mode 100644 Task/Zhang-Suen-thinning-algorithm/00DESCRIPTION create mode 100644 Task/Zhang-Suen-thinning-algorithm/AutoHotkey/zhang-suen-thinning-algorithm.ahk create mode 100644 Task/Zhang-Suen-thinning-algorithm/D/zhang-suen-thinning-algorithm.d create mode 100644 Task/Zhang-Suen-thinning-algorithm/Go/zhang-suen-thinning-algorithm.go create mode 100644 Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-1.groovy create mode 100644 Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-2.groovy create mode 100644 Task/Zhang-Suen-thinning-algorithm/Haskell/zhang-suen-thinning-algorithm.hs create mode 100644 Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-1.j create mode 100644 Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-2.j create mode 100644 Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-3.j create mode 100644 Task/Zhang-Suen-thinning-algorithm/Java/zhang-suen-thinning-algorithm.java create mode 100644 Task/Zhang-Suen-thinning-algorithm/Mathematica/zhang-suen-thinning-algorithm.math create mode 100644 Task/Zhang-Suen-thinning-algorithm/PL-I/zhang-suen-thinning-algorithm.pli create mode 100644 Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 create mode 100644 Task/Zhang-Suen-thinning-algorithm/Python/zhang-suen-thinning-algorithm.py create mode 100644 Task/Zhang-Suen-thinning-algorithm/README create mode 100644 Task/Zhang-Suen-thinning-algorithm/REXX/zhang-suen-thinning-algorithm.rexx create mode 100644 Task/Zhang-Suen-thinning-algorithm/Racket/zhang-suen-thinning-algorithm.rkt create mode 100644 Task/Zhang-Suen-thinning-algorithm/Ruby/zhang-suen-thinning-algorithm.rb create mode 100644 Task/Zhang-Suen-thinning-algorithm/Tcl/zhang-suen-thinning-algorithm.tcl diff --git a/Conf/task.yaml b/Conf/task.yaml index 9c9e8a247b..bc4274e403 100644 --- a/Conf/task.yaml +++ b/Conf/task.yaml @@ -1,10 +1,13 @@ 100 doors: 24 game: 24 game/Solve: +9 billion names of God the integer: 99 Bottles of Beer: A+B: +ABC Problem: Abstract type: +Abundant, deficient and perfect number classifications: Accumulator factory: Ackermann function: Active Directory/Connect: @@ -12,17 +15,24 @@ Active Directory/Search for a user: Active object: Add a variable to a class instance at runtime: Address of a variable: +AKS test for primes: Align columns: +Aliquot sequence classifications: +Almost prime: +Amb: +Amicable pairs: Anagrams: Anagrams/Deranged anagrams: Animate a pendulum: Animation: Anonymous recursion: +Append a record to the end of a text file: Apply a callback to an array: Arbitrary-precision integers (included): Arena storage pool: Arithmetic evaluation: Arithmetic-geometric mean: +Arithmetic-geometric mean/Calculate Pi: Arithmetic/Complex: Arithmetic/Integer: Arithmetic/Rational: @@ -44,13 +54,16 @@ Averages/Simple moving average: Balanced brackets: Balanced ternary: +Benford's law: #' +Bernoulli numbers: Best shuffle: Binary digits: Binary search: Binary strings: Bitcoin/address validation: +Bitcoin/public point to address: Bitmap: -Bitmap/Bresenham's line algorithm: #' +Bitmap/Bresenham's line algorithm: #' Bitmap/Bézier curves/Cubic: Bitmap/Bézier curves/Quadratic: Bitmap/Flood fill: @@ -71,7 +84,7 @@ Bulls and cows/Player: Caesar cipher: Calendar: -Calendar - for "real" programmers: +Calendar - for "REAL" programmers: Call a foreign-language function: Call a function: Call a function in a shared library: @@ -79,17 +92,22 @@ Call an object method: Canny edge detector: Carmichael 3 strong pseudoprimes: Case-sensitivity of identifiers: +Casting out nines: Catalan numbers: +Catalan numbers/Pascal's triangle: #' +Catamorphism: Catmull–Clark subdivision surface: Character codes: -Character matching: Chat server: Check Machin-like formulas: Check that file exists: Checkpoint synchronization: +Chinese remainder theorem: Cholesky decomposition: +Circles of given radius through two points: Classes: Closest-pair problem: +Closures/Value capture: Collections: Color of a screen pixel: Color quantization: @@ -97,21 +115,25 @@ Colour bars/Display: Colour pinstripe/Display: Colour pinstripe/Printer: Combinations: +Combinations and permutations: Combinations with repetitions: +Comma quibbling: Command-line arguments: Comments: -Compare sorting algorithms' performance: #' +Compare sorting algorithms' performance: #' Compile-time calculation: Compound data type: Concurrent computing: Conditional structures: +Conjugate transpose: Constrained genericity: Constrained random points on a circle: Continued fraction: Continued fraction/Arithmetic/Construct from rational number: Continued fraction/Arithmetic/G(matrix NG, Contined Fraction N): Continued fraction/Arithmetic/G(matrix NG, Contined Fraction N1, Contined Fraction N2): -Conway's Game of Life: #' +Convert decimal number to rational: +Conway's Game of Life: #' Copy a string: Count in factors: Count in octal: @@ -123,7 +145,9 @@ Create a file on magnetic tape: Create a two-dimensional array at runtime: Create an HTML table: Create an object at a given address: +CSV data manipulation: CSV to HTML translation: +Currying: Cut a rectangle: Date format: @@ -141,7 +165,8 @@ Detect division by zero: Determine if a string is numeric: Determine if only one instance is running: Digital root: -Dinesman's multiple-dwelling problem: #' +Digital root/Multiplicative digital root: +Dinesman's multiple-dwelling problem: #' Dining philosophers: Discordian date: Distributed programming: @@ -153,6 +178,7 @@ Doubly-linked list/Element definition: Doubly-linked list/Element insertion: Doubly-linked list/Traversal: Dragon curve: +Draw a clock: Draw a cuboid: Draw a sphere: Dutch national flag problem: @@ -184,6 +210,7 @@ Execute HQ9+: Execute SNUSP: Exponentiation operator: Extend your language: +Extensible prime generator: Extreme floating point values: Factorial: @@ -192,13 +219,16 @@ Factors of an integer: Fast Fourier transform: Fibonacci n-step number sequences: Fibonacci sequence: -File IO: +Fibonacci word: +Fibonacci word/fractal: +File input/output: File modification time: File size: Filter: Find common directory path: Find largest left truncatable prime in a given base: Find limit of recursion: +Find the last Sunday of each month: Find the missing permutation: First class environments: First-class functions: @@ -206,8 +236,9 @@ First-class functions/Use numbers analogously: Five weekends: FizzBuzz: Flatten a list: +Flipping bits game: Flow-control structures: -Floyd's triangle: #' +Floyd's triangle: #' Forest fire: Fork: Formal power series: @@ -215,6 +246,7 @@ Formatted numeric output: Forward difference: Four bit adder: Fractal tree: +Fractran: Function composition: Function definition: Function frequency: @@ -222,6 +254,9 @@ Function prototype: Galton box animation: Gamma function: +Gaussian elimination: +Generate Chess960 starting position: +Generate lower case ASCII alphabet: Generator/Exponential: Generic swap: Globally replace text in several files: @@ -245,14 +280,18 @@ Handle a signal: Happy numbers: Harshad or Niven series: Hash from two arrays: +Hash join: Haversine formula: Hello world/Graphical: Hello world/Line printer: +Hello world/Newbie: Hello world/Newline omission: Hello world/Standard error: Hello world/Text: Hello world/Web server: Here document: +Heronian triangles: +Hickerson series of almost integers: Higher-order functions: History variables: Hofstadter Figure-Figure sequences: @@ -261,7 +300,7 @@ Hofstadter-Conway $10,000 sequence: Holidays related to Easter: Honeycombs: Horizontal sundial calculations: -Horner's rule for polynomial evaluation: #' +Horner's rule for polynomial evaluation: #' Host introspection: Hostname: Hough transform: @@ -272,6 +311,7 @@ HTTPS/Client-authenticated: Huffman coding: I before E except after C: +IBAN: Identity matrix: Image convolution: Image noise: @@ -282,18 +322,21 @@ Inheritance/Multiple: Inheritance/Single: Input loop: Integer comparison: +Integer overflow: Integer sequence: Interactive programming: Introspection: Inverted index: Inverted syntax: +Iterated digits squaring: -Jensen's Device: #' +Jensen's Device: #' Josephus problem: Joystick position: JSON: Jump anywhere: +K-d tree: K-means++ clustering: Kaprekar numbers: Keyboard input/Flush the keyboard buffer: @@ -304,16 +347,17 @@ Knapsack problem/0-1: Knapsack problem/Bounded: Knapsack problem/Continuous: Knapsack problem/Unbounded: -Knight's tour: #' +Knight's tour: #' Knuth shuffle: -Knuth's algorithm S: #' +Knuth's algorithm S: #' -Langton's ant: #' +Langton's ant: #' Largest int from concatenated ints: Last Friday of each month: Last letter-first letter: Leap year: Least common multiple: +Left factorials: Letter frequency: Levenshtein distance: Linear congruential generator: @@ -324,6 +368,7 @@ Literals/String: Logical operations: Long multiplication: Longest common subsequence: +Longest increasing subsequence: Longest string challenge: Look-and-say sequence: Loop over multiple arrays simultaneously: @@ -340,11 +385,15 @@ Loops/Nested: Loops/While: LU decomposition: Lucas-Lehmer test: +Ludic numbers: Luhn test of credit card numbers: LZW compression: +Machine code: Mad Libs: +Magic squares of odd order: Main step of GOST 28147-89: +Make directory path: Man or boy test: Mandelbrot set: Map range: @@ -352,6 +401,7 @@ Matrix arithmetic: Matrix multiplication: Matrix transposition: Matrix-exponentiation operator: +Maximum triangle path sum: Maze generation: Maze solving: MD4: @@ -373,18 +423,22 @@ Monte Carlo methods: Monty Hall problem: Morse code: Mouse position: +Move-to-front algorithm: Multifactorial: Multiple distinct objects: Multiple regression: Multiplication tables: Multiplicative order: Multisplit: -# Mutex: +Munching squares: Mutual recursion: +N'th: #' N-queens problem: Named parameters: Narcissist: +Narcissistic decimal number: +Natural sorting: Nautical bell: Non-continuous subsequences: Non-decimal radices/Convert: @@ -399,34 +453,47 @@ Numerical integration: Numerical integration/Gauss-Legendre Quadrature: Object serialization: +Odd word problem: +Old lady swallowed a fly: OLE Automation: One of n lines in a file: One-dimensional cellular automata: OpenGL: Operator precedence: Optional parameters: +Order disjoint list items: Order two numerical lists: Ordered Partitions: Ordered words: Palindrome detection: Pangram checker: +Paraffins: Parallel calculations: Parametric polymorphism: Parametrized SQL statement: +Parse an IP Address: Parsing/RPN calculator algorithm: Parsing/RPN to infix conversion: Parsing/Shunting-yard algorithm: Partial function application: -Pascal's triangle: #' -Pascal's triangle/Puzzle: #' +Pascal's triangle: #' +Pascal's triangle/Puzzle: #' Pattern matching: +Penney's game: #' Percentage difference between images: +Percolation/Bond percolation: +Percolation/Mean cluster density: +Percolation/Mean run density: +Percolation/Site percolation: Perfect numbers: Permutation test: Permutations: Permutations by swapping: Permutations/Derangements: +Permutations/Rank of a permutation: +Pernicious numbers: +Phrase reversals: Pi: Pick random element: Pig the dice game: @@ -457,6 +524,7 @@ QR decomposition: Quaternion type: Queue/Definition: Queue/Usage: +Quickselect algorithm: Quine: Random number generator (device): @@ -464,6 +532,7 @@ Random number generator (included): Random numbers: Range expansion: Range extraction: +Ranking methods: Rate counter: Ray-casting algorithm: RCRPG: @@ -479,11 +548,13 @@ Remove duplicate elements: Remove lines from a file: Rename a file: Rendezvous: +Rep-string: Repeat a string: Resistor mesh: Respond to an unknown method call: Return multiple values: Reverse a string: +Reverse words in a string: RIPEMD-160: Rock-paper-scissors: Roman numerals/Decode: @@ -491,12 +562,18 @@ Roman numerals/Encode: Roots of a function: Roots of a quadratic function: Roots of unity: -Rosetta Code/Count examples: -Rosetta Code/Find unimplemented tasks: -Rosetta Code/Fix code tags: -Rosetta Code/Rank languages by popularity: + +# XXX - These break the parser currently: +# Rosetta Code/Count examples: +# Rosetta Code/Find bare lang tags: +# Rosetta Code/Find unimplemented tasks: +# Rosetta Code/Fix code tags: +# Rosetta Code/Rank languages by popularity: + Rot-13: +RSA code: Run-length encoding: +Runge-Kutta method: Runtime evaluation: Runtime evaluation/In an environment: @@ -510,10 +587,12 @@ Secure temporary file: SEDOLs: Self-describing numbers: Self-referential sequence: +Semiprime: Semordnilap: Send an unknown method call: Send email: Sequence of non-squares: +Sequence of primes by Trial Division: Set: Set consolidation: Set of real numbers: @@ -541,6 +620,10 @@ SOAP: Sockets: Sokoban: Solve a Hidato puzzle: +Solve a Holy Knight's tour: #' +Solve a Hopido puzzle: +Solve a Numbrix puzzle: +Solve the no connection puzzle: Sort an array of composite structures: Sort an integer array: Sort disjoint sublist: @@ -566,6 +649,7 @@ Sorting algorithms/Sleep sort: Sorting algorithms/Stooge sort: Sorting algorithms/Strand sort: Soundex: +Sparkline in unicode: Special characters: Special variables: Speech synthesis: @@ -577,12 +661,18 @@ Stack traces: Stair-climbing puzzle: Standard deviation: Start from a main routine: +State name puzzle: +Statistics/Basic: Stem-and-leaf plot: +Stern-Brocot sequence: +String append: String case: String comparison: String concatenation: String interpolation (included): String length: +String matching: +String prepend: Strip a set of characters from a string: Strip block comments: Strip comments from a string: @@ -594,6 +684,7 @@ Subtractive generator: Sudoku: Sum and product of an array: Sum digits of an integer: +Sum multiples of 3 and 5: Sum of a series: Sum of squares: Sutherland-Hodgman polygon clipping: @@ -621,7 +712,10 @@ Test a function: Text processing/1: Text processing/2: Text processing/Max licenses in use: -Thiele's interpolation formula: #' +Textonyms: +The ISAAC Cipher: +The Twelve Days of Christmas: +Thiele's interpolation formula: #' Tic-tac-toe: Time a function: Tokenize a string: @@ -629,6 +723,7 @@ Top rank per group: Topic variable: Topological sort: Topswops: +Total circles area: Towers of Hanoi: Trabb Pardo–Knuth algorithm: Tree traversal: @@ -637,11 +732,13 @@ Truncatable primes: Truncate a file: Twelve statements: +Ulam spiral (for primes): Unbias a random generator: Undefined values: Unicode strings: Unicode variable names: Universal Turing machine: +Unix/ls: Update a configuration file: URL decoding: URL encoding: @@ -663,6 +760,7 @@ Video display modes: Vigenère cipher: Vigenère cipher/Cryptanalysis: Visualize a tree: +Vogel's approximation method: #' Voronoi diagram: Walk a directory/Non-recursively: @@ -673,11 +771,12 @@ Window creation/X11: Window management: Wireworld: Word wrap: +World Cup group stage: Write float arrays to a text file: Write language name in 3D ASCII: Write to Windows event log: -Xiaolin Wu's line algorithm: #' +Xiaolin Wu's line algorithm: #' XML/DOM serialization: XML/Input: XML/Output: @@ -690,4 +789,6 @@ Yin and yang: Zebra puzzle: Zeckendorf arithmetic: Zeckendorf number representation: +Zero to the zero power: +Zhang-Suen thinning algorithm: Zig-zag matrix: diff --git a/Lang/360-Assembly/Catalan-numbers-Pascals-triangle b/Lang/360-Assembly/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..2cd0d7b486 --- /dev/null +++ b/Lang/360-Assembly/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/360-Assembly \ No newline at end of file diff --git a/Lang/ACL2/File-input-output b/Lang/ACL2/File-input-output new file mode 120000 index 0000000000..6a1b076658 --- /dev/null +++ b/Lang/ACL2/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/ACL2 \ No newline at end of file diff --git a/Lang/ALGOL-68/Amb b/Lang/ALGOL-68/Amb new file mode 120000 index 0000000000..f42068465c --- /dev/null +++ b/Lang/ALGOL-68/Amb @@ -0,0 +1 @@ +../../Task/Amb/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Calendar---for-REAL-programmers b/Lang/ALGOL-68/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..9daf77d4e8 --- /dev/null +++ b/Lang/ALGOL-68/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Closures-Value-capture b/Lang/ALGOL-68/Closures-Value-capture new file mode 120000 index 0000000000..456d216da2 --- /dev/null +++ b/Lang/ALGOL-68/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Combinations-and-permutations b/Lang/ALGOL-68/Combinations-and-permutations new file mode 120000 index 0000000000..1c03f9655f --- /dev/null +++ b/Lang/ALGOL-68/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Currying b/Lang/ALGOL-68/Currying new file mode 120000 index 0000000000..87493ab3d7 --- /dev/null +++ b/Lang/ALGOL-68/Currying @@ -0,0 +1 @@ +../../Task/Currying/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Digital-root-Multiplicative-digital-root b/Lang/ALGOL-68/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..cff31a9114 --- /dev/null +++ b/Lang/ALGOL-68/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Fibonacci-word b/Lang/ALGOL-68/Fibonacci-word new file mode 120000 index 0000000000..820586c2d7 --- /dev/null +++ b/Lang/ALGOL-68/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/File-input-output b/Lang/ALGOL-68/File-input-output new file mode 120000 index 0000000000..db7aeb57c2 --- /dev/null +++ b/Lang/ALGOL-68/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Gaussian-elimination b/Lang/ALGOL-68/Gaussian-elimination new file mode 120000 index 0000000000..9c8cce235b --- /dev/null +++ b/Lang/ALGOL-68/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Generate-lower-case-ASCII-alphabet b/Lang/ALGOL-68/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..3323f0d03d --- /dev/null +++ b/Lang/ALGOL-68/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Hello-world-Newbie b/Lang/ALGOL-68/Hello-world-Newbie new file mode 120000 index 0000000000..d8de503baa --- /dev/null +++ b/Lang/ALGOL-68/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Maximum-triangle-path-sum b/Lang/ALGOL-68/Maximum-triangle-path-sum new file mode 120000 index 0000000000..6953b4dd4a --- /dev/null +++ b/Lang/ALGOL-68/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Move-to-front-algorithm b/Lang/ALGOL-68/Move-to-front-algorithm new file mode 120000 index 0000000000..4f4103fefd --- /dev/null +++ b/Lang/ALGOL-68/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Nth b/Lang/ALGOL-68/Nth new file mode 120000 index 0000000000..516ddb941a --- /dev/null +++ b/Lang/ALGOL-68/Nth @@ -0,0 +1 @@ +../../Task/Nth/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Odd-word-problem b/Lang/ALGOL-68/Odd-word-problem new file mode 120000 index 0000000000..c051c2d824 --- /dev/null +++ b/Lang/ALGOL-68/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Old-lady-swallowed-a-fly b/Lang/ALGOL-68/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..550ca495a4 --- /dev/null +++ b/Lang/ALGOL-68/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Rep-string b/Lang/ALGOL-68/Rep-string new file mode 120000 index 0000000000..a05d0303e5 --- /dev/null +++ b/Lang/ALGOL-68/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-append b/Lang/ALGOL-68/String-append new file mode 120000 index 0000000000..6e1bba96af --- /dev/null +++ b/Lang/ALGOL-68/String-append @@ -0,0 +1 @@ +../../Task/String-append/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-matching b/Lang/ALGOL-68/String-matching new file mode 120000 index 0000000000..d604d888a6 --- /dev/null +++ b/Lang/ALGOL-68/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-prepend b/Lang/ALGOL-68/String-prepend new file mode 120000 index 0000000000..be5d160e4b --- /dev/null +++ b/Lang/ALGOL-68/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Zero-to-the-zero-power b/Lang/ALGOL-68/Zero-to-the-zero-power new file mode 120000 index 0000000000..fddff9906b --- /dev/null +++ b/Lang/ALGOL-68/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/ALGOL-68 \ No newline at end of file diff --git a/Lang/ATS/Generate-lower-case-ASCII-alphabet b/Lang/ATS/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..79af58ba63 --- /dev/null +++ b/Lang/ATS/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ATS \ No newline at end of file diff --git a/Lang/ATS/Sequence-of-primes-by-Trial-Division b/Lang/ATS/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..62530f1780 --- /dev/null +++ b/Lang/ATS/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/ATS \ No newline at end of file diff --git a/Lang/AWK/Benfords-law b/Lang/AWK/Benfords-law new file mode 120000 index 0000000000..dd63450d19 --- /dev/null +++ b/Lang/AWK/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/AWK \ No newline at end of file diff --git a/Lang/AWK/CSV-data-manipulation b/Lang/AWK/CSV-data-manipulation new file mode 120000 index 0000000000..e59dd79eb0 --- /dev/null +++ b/Lang/AWK/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/AWK \ No newline at end of file diff --git a/Lang/AWK/Comma-quibbling b/Lang/AWK/Comma-quibbling new file mode 120000 index 0000000000..f8915ee4e6 --- /dev/null +++ b/Lang/AWK/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/AWK \ No newline at end of file diff --git a/Lang/AWK/Digital-root-Multiplicative-digital-root b/Lang/AWK/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..ff824c025c --- /dev/null +++ b/Lang/AWK/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/AWK \ No newline at end of file diff --git a/Lang/AWK/Draw-a-clock b/Lang/AWK/Draw-a-clock new file mode 120000 index 0000000000..e08ce88a21 --- /dev/null +++ b/Lang/AWK/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/AWK \ No newline at end of file diff --git a/Lang/AWK/File-input-output b/Lang/AWK/File-input-output new file mode 120000 index 0000000000..1a65bc3d82 --- /dev/null +++ b/Lang/AWK/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/AWK \ No newline at end of file diff --git a/Lang/AWK/Generate-lower-case-ASCII-alphabet b/Lang/AWK/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d6ecba6946 --- /dev/null +++ b/Lang/AWK/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/AWK \ No newline at end of file diff --git a/Lang/AWK/Hello-world-Newbie b/Lang/AWK/Hello-world-Newbie new file mode 120000 index 0000000000..cb3f87b3e8 --- /dev/null +++ b/Lang/AWK/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/AWK \ No newline at end of file diff --git a/Lang/AWK/Magic-squares-of-odd-order b/Lang/AWK/Magic-squares-of-odd-order new file mode 120000 index 0000000000..93da3782f4 --- /dev/null +++ b/Lang/AWK/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/AWK \ No newline at end of file diff --git a/Lang/AWK/Narcissistic-decimal-number b/Lang/AWK/Narcissistic-decimal-number new file mode 120000 index 0000000000..2b1560e1a0 --- /dev/null +++ b/Lang/AWK/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/AWK \ No newline at end of file diff --git a/Lang/AWK/Nth b/Lang/AWK/Nth new file mode 120000 index 0000000000..39d025ff0b --- /dev/null +++ b/Lang/AWK/Nth @@ -0,0 +1 @@ +../../Task/Nth/AWK \ No newline at end of file diff --git a/Lang/AWK/Old-lady-swallowed-a-fly b/Lang/AWK/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..24bde13baa --- /dev/null +++ b/Lang/AWK/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/AWK \ No newline at end of file diff --git a/Lang/AWK/Phrase-reversals b/Lang/AWK/Phrase-reversals new file mode 120000 index 0000000000..bdc503555e --- /dev/null +++ b/Lang/AWK/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/AWK \ No newline at end of file diff --git a/Lang/AWK/Ranking-methods b/Lang/AWK/Ranking-methods new file mode 120000 index 0000000000..432245b72b --- /dev/null +++ b/Lang/AWK/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/AWK \ No newline at end of file diff --git a/Lang/AWK/Reverse-words-in-a-string b/Lang/AWK/Reverse-words-in-a-string new file mode 120000 index 0000000000..c7d7c94183 --- /dev/null +++ b/Lang/AWK/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Runge-Kutta-method b/Lang/AWK/Runge-Kutta-method new file mode 120000 index 0000000000..3a2e752d35 --- /dev/null +++ b/Lang/AWK/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/AWK \ No newline at end of file diff --git a/Lang/AWK/String-append b/Lang/AWK/String-append new file mode 120000 index 0000000000..28f85045fe --- /dev/null +++ b/Lang/AWK/String-append @@ -0,0 +1 @@ +../../Task/String-append/AWK \ No newline at end of file diff --git a/Lang/AWK/String-matching b/Lang/AWK/String-matching new file mode 120000 index 0000000000..bea8484d18 --- /dev/null +++ b/Lang/AWK/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/AWK \ No newline at end of file diff --git a/Lang/AWK/String-prepend b/Lang/AWK/String-prepend new file mode 120000 index 0000000000..ec5fcd55a5 --- /dev/null +++ b/Lang/AWK/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/AWK \ No newline at end of file diff --git a/Lang/AWK/Sum-multiples-of-3-and-5 b/Lang/AWK/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..652f6b3592 --- /dev/null +++ b/Lang/AWK/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/AWK \ No newline at end of file diff --git a/Lang/AWK/The-Twelve-Days-of-Christmas b/Lang/AWK/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..29a8a8da38 --- /dev/null +++ b/Lang/AWK/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/AWK \ No newline at end of file diff --git a/Lang/AWK/Unix-ls b/Lang/AWK/Unix-ls new file mode 120000 index 0000000000..eaafa8c063 --- /dev/null +++ b/Lang/AWK/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/AWK \ No newline at end of file diff --git a/Lang/AWK/Zero-to-the-zero-power b/Lang/AWK/Zero-to-the-zero-power new file mode 120000 index 0000000000..4e5f1211f8 --- /dev/null +++ b/Lang/AWK/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/AWK \ No newline at end of file diff --git a/Lang/ActionScript/Draw-a-clock b/Lang/ActionScript/Draw-a-clock new file mode 120000 index 0000000000..4c52da613a --- /dev/null +++ b/Lang/ActionScript/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/The-Twelve-Days-of-Christmas b/Lang/ActionScript/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..20eb01a6ca --- /dev/null +++ b/Lang/ActionScript/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/ActionScript \ No newline at end of file diff --git a/Lang/Ada/ABC-Problem b/Lang/Ada/ABC-Problem new file mode 120000 index 0000000000..618a565150 --- /dev/null +++ b/Lang/Ada/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Ada \ No newline at end of file diff --git a/Lang/Ada/Almost-prime b/Lang/Ada/Almost-prime new file mode 120000 index 0000000000..221a475d3d --- /dev/null +++ b/Lang/Ada/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Ada \ No newline at end of file diff --git a/Lang/Ada/Amb b/Lang/Ada/Amb new file mode 120000 index 0000000000..69344b3e23 --- /dev/null +++ b/Lang/Ada/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ada \ No newline at end of file diff --git a/Lang/Ada/Benfords-law b/Lang/Ada/Benfords-law new file mode 120000 index 0000000000..b00c1dc883 --- /dev/null +++ b/Lang/Ada/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Ada \ No newline at end of file diff --git a/Lang/Ada/Calendar---for-REAL-programmers b/Lang/Ada/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..7ff6ba0bea --- /dev/null +++ b/Lang/Ada/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Ada \ No newline at end of file diff --git a/Lang/Ada/Catalan-numbers-Pascals-triangle b/Lang/Ada/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..fc5525ddff --- /dev/null +++ b/Lang/Ada/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Ada \ No newline at end of file diff --git a/Lang/Ada/Catamorphism b/Lang/Ada/Catamorphism new file mode 120000 index 0000000000..1d150f5487 --- /dev/null +++ b/Lang/Ada/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Ada \ No newline at end of file diff --git a/Lang/Ada/Chinese-remainder-theorem b/Lang/Ada/Chinese-remainder-theorem new file mode 120000 index 0000000000..8b27d8d3d7 --- /dev/null +++ b/Lang/Ada/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Ada \ No newline at end of file diff --git a/Lang/Ada/Closures-Value-capture b/Lang/Ada/Closures-Value-capture new file mode 120000 index 0000000000..f15d201b0d --- /dev/null +++ b/Lang/Ada/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Ada \ No newline at end of file diff --git a/Lang/Ada/Comma-quibbling b/Lang/Ada/Comma-quibbling new file mode 120000 index 0000000000..ce7e90d883 --- /dev/null +++ b/Lang/Ada/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Ada \ No newline at end of file diff --git a/Lang/Ada/Conjugate-transpose b/Lang/Ada/Conjugate-transpose new file mode 120000 index 0000000000..ec88d5dfa5 --- /dev/null +++ b/Lang/Ada/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Ada \ No newline at end of file diff --git a/Lang/Ada/Convert-decimal-number-to-rational b/Lang/Ada/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..706fb935d3 --- /dev/null +++ b/Lang/Ada/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Ada \ No newline at end of file diff --git a/Lang/Ada/Digital-root-Multiplicative-digital-root b/Lang/Ada/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..fed81e6601 --- /dev/null +++ b/Lang/Ada/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Ada \ No newline at end of file diff --git a/Lang/Ada/Extensible-prime-generator b/Lang/Ada/Extensible-prime-generator new file mode 120000 index 0000000000..d041b1107e --- /dev/null +++ b/Lang/Ada/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Ada \ No newline at end of file diff --git a/Lang/Ada/Fibonacci-word b/Lang/Ada/Fibonacci-word new file mode 120000 index 0000000000..dcd89c3e11 --- /dev/null +++ b/Lang/Ada/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Ada \ No newline at end of file diff --git a/Lang/Ada/File-input-output b/Lang/Ada/File-input-output new file mode 120000 index 0000000000..bf0c52f09c --- /dev/null +++ b/Lang/Ada/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Ada \ No newline at end of file diff --git a/Lang/Ada/Flipping-bits-game b/Lang/Ada/Flipping-bits-game new file mode 120000 index 0000000000..c094926424 --- /dev/null +++ b/Lang/Ada/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Fractran b/Lang/Ada/Fractran new file mode 120000 index 0000000000..d37b2edd60 --- /dev/null +++ b/Lang/Ada/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Ada \ No newline at end of file diff --git a/Lang/Ada/Generate-lower-case-ASCII-alphabet b/Lang/Ada/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..04ae7aa39b --- /dev/null +++ b/Lang/Ada/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Ada \ No newline at end of file diff --git a/Lang/Ada/IBAN b/Lang/Ada/IBAN new file mode 120000 index 0000000000..ab95454b62 --- /dev/null +++ b/Lang/Ada/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Ada \ No newline at end of file diff --git a/Lang/Ada/Integer-overflow b/Lang/Ada/Integer-overflow new file mode 120000 index 0000000000..ac7d5ff059 --- /dev/null +++ b/Lang/Ada/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Ada \ No newline at end of file diff --git a/Lang/Ada/Magic-squares-of-odd-order b/Lang/Ada/Magic-squares-of-odd-order new file mode 120000 index 0000000000..302125176c --- /dev/null +++ b/Lang/Ada/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Ada \ No newline at end of file diff --git a/Lang/Ada/Maximum-triangle-path-sum b/Lang/Ada/Maximum-triangle-path-sum new file mode 120000 index 0000000000..83101e82b9 --- /dev/null +++ b/Lang/Ada/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Ada \ No newline at end of file diff --git a/Lang/Ada/Move-to-front-algorithm b/Lang/Ada/Move-to-front-algorithm new file mode 120000 index 0000000000..3c572b1c14 --- /dev/null +++ b/Lang/Ada/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Ada \ No newline at end of file diff --git a/Lang/Ada/Munching-squares b/Lang/Ada/Munching-squares new file mode 120000 index 0000000000..02be934d36 --- /dev/null +++ b/Lang/Ada/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Ada \ No newline at end of file diff --git a/Lang/Ada/Narcissistic-decimal-number b/Lang/Ada/Narcissistic-decimal-number new file mode 120000 index 0000000000..2b27e24b74 --- /dev/null +++ b/Lang/Ada/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Ada \ No newline at end of file diff --git a/Lang/Ada/Nth b/Lang/Ada/Nth new file mode 120000 index 0000000000..c2a9c95301 --- /dev/null +++ b/Lang/Ada/Nth @@ -0,0 +1 @@ +../../Task/Nth/Ada \ No newline at end of file diff --git a/Lang/Ada/Odd-word-problem b/Lang/Ada/Odd-word-problem new file mode 120000 index 0000000000..62eefb4656 --- /dev/null +++ b/Lang/Ada/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Ada \ No newline at end of file diff --git a/Lang/Ada/Old-lady-swallowed-a-fly b/Lang/Ada/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..a39e20779f --- /dev/null +++ b/Lang/Ada/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Ada \ No newline at end of file diff --git a/Lang/Ada/Pernicious-numbers b/Lang/Ada/Pernicious-numbers new file mode 120000 index 0000000000..815360969f --- /dev/null +++ b/Lang/Ada/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Phrase-reversals b/Lang/Ada/Phrase-reversals new file mode 120000 index 0000000000..289b7e6380 --- /dev/null +++ b/Lang/Ada/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Ada \ No newline at end of file diff --git a/Lang/Ada/Rep-string b/Lang/Ada/Rep-string new file mode 120000 index 0000000000..370a940d54 --- /dev/null +++ b/Lang/Ada/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Reverse-words-in-a-string b/Lang/Ada/Reverse-words-in-a-string new file mode 120000 index 0000000000..deaf334ced --- /dev/null +++ b/Lang/Ada/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Runge-Kutta-method b/Lang/Ada/Runge-Kutta-method new file mode 120000 index 0000000000..6ee8130973 --- /dev/null +++ b/Lang/Ada/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Ada \ No newline at end of file diff --git a/Lang/Ada/Semiprime b/Lang/Ada/Semiprime new file mode 120000 index 0000000000..8e42c8763f --- /dev/null +++ b/Lang/Ada/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Ada \ No newline at end of file diff --git a/Lang/Ada/Sequence-of-primes-by-Trial-Division b/Lang/Ada/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..5a2a2ba5c4 --- /dev/null +++ b/Lang/Ada/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Ada \ No newline at end of file diff --git a/Lang/Ada/Solve-a-Holy-Knights-tour b/Lang/Ada/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..983ebf3d1d --- /dev/null +++ b/Lang/Ada/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Ada \ No newline at end of file diff --git a/Lang/Ada/Solve-the-no-connection-puzzle b/Lang/Ada/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..ebfa9fe26d --- /dev/null +++ b/Lang/Ada/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Ada \ No newline at end of file diff --git a/Lang/Ada/Statistics-Basic b/Lang/Ada/Statistics-Basic new file mode 120000 index 0000000000..ae0b0d2c60 --- /dev/null +++ b/Lang/Ada/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Ada \ No newline at end of file diff --git a/Lang/Ada/String-matching b/Lang/Ada/String-matching new file mode 120000 index 0000000000..390aad9fb6 --- /dev/null +++ b/Lang/Ada/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Ada \ No newline at end of file diff --git a/Lang/Ada/The-Twelve-Days-of-Christmas b/Lang/Ada/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..5ad9283788 --- /dev/null +++ b/Lang/Ada/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Ada \ No newline at end of file diff --git a/Lang/Ada/Ulam-spiral--for-primes- b/Lang/Ada/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..e925579c05 --- /dev/null +++ b/Lang/Ada/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Ada \ No newline at end of file diff --git a/Lang/Ada/Unix-ls b/Lang/Ada/Unix-ls new file mode 120000 index 0000000000..07b19b446a --- /dev/null +++ b/Lang/Ada/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Ada \ No newline at end of file diff --git a/Lang/Ada/Zero-to-the-zero-power b/Lang/Ada/Zero-to-the-zero-power new file mode 120000 index 0000000000..dfeb3816cf --- /dev/null +++ b/Lang/Ada/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Ada \ No newline at end of file diff --git a/Lang/Aime/Benfords-law b/Lang/Aime/Benfords-law new file mode 120000 index 0000000000..d8ae3ba4c8 --- /dev/null +++ b/Lang/Aime/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Aime \ No newline at end of file diff --git a/Lang/Aime/File-input-output b/Lang/Aime/File-input-output new file mode 120000 index 0000000000..f7292c4c91 --- /dev/null +++ b/Lang/Aime/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Aime \ No newline at end of file diff --git a/Lang/Aime/Reverse-words-in-a-string b/Lang/Aime/Reverse-words-in-a-string new file mode 120000 index 0000000000..14dd7aebd7 --- /dev/null +++ b/Lang/Aime/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Aime \ No newline at end of file diff --git a/Lang/Aime/String-matching b/Lang/Aime/String-matching new file mode 120000 index 0000000000..687ca57010 --- /dev/null +++ b/Lang/Aime/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Aime \ No newline at end of file diff --git a/Lang/AppleScript/File-input-output b/Lang/AppleScript/File-input-output new file mode 120000 index 0000000000..57d9ecd16e --- /dev/null +++ b/Lang/AppleScript/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/Applesoft-BASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..07fb99bcc3 --- /dev/null +++ b/Lang/Applesoft-BASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Nth b/Lang/Applesoft-BASIC/Nth new file mode 120000 index 0000000000..241adc7d21 --- /dev/null +++ b/Lang/Applesoft-BASIC/Nth @@ -0,0 +1 @@ +../../Task/Nth/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Reverse-words-in-a-string b/Lang/Applesoft-BASIC/Reverse-words-in-a-string new file mode 120000 index 0000000000..2641c17abb --- /dev/null +++ b/Lang/Applesoft-BASIC/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/AutoHotkey/9-billion-names-of-God-the-integer b/Lang/AutoHotkey/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..fb9c06b127 --- /dev/null +++ b/Lang/AutoHotkey/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/ABC-Problem b/Lang/AutoHotkey/ABC-Problem new file mode 120000 index 0000000000..2214268f2b --- /dev/null +++ b/Lang/AutoHotkey/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/AKS-test-for-primes b/Lang/AutoHotkey/AKS-test-for-primes new file mode 120000 index 0000000000..b56ca21e15 --- /dev/null +++ b/Lang/AutoHotkey/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Abundant,-deficient-and-perfect-number-classifications b/Lang/AutoHotkey/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..d5fa490c12 --- /dev/null +++ b/Lang/AutoHotkey/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Almost-prime b/Lang/AutoHotkey/Almost-prime new file mode 120000 index 0000000000..780c4632db --- /dev/null +++ b/Lang/AutoHotkey/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Amb b/Lang/AutoHotkey/Amb new file mode 120000 index 0000000000..c4c84e6da3 --- /dev/null +++ b/Lang/AutoHotkey/Amb @@ -0,0 +1 @@ +../../Task/Amb/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Amicable-pairs b/Lang/AutoHotkey/Amicable-pairs new file mode 120000 index 0000000000..18e5eebfa5 --- /dev/null +++ b/Lang/AutoHotkey/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Benfords-law b/Lang/AutoHotkey/Benfords-law new file mode 120000 index 0000000000..329ef3b698 --- /dev/null +++ b/Lang/AutoHotkey/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/CSV-data-manipulation b/Lang/AutoHotkey/CSV-data-manipulation new file mode 120000 index 0000000000..a218f28bc3 --- /dev/null +++ b/Lang/AutoHotkey/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Calendar---for-REAL-programmers b/Lang/AutoHotkey/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..1158cc2653 --- /dev/null +++ b/Lang/AutoHotkey/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Catalan-numbers-Pascals-triangle b/Lang/AutoHotkey/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..f3ecfae064 --- /dev/null +++ b/Lang/AutoHotkey/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Circles-of-given-radius-through-two-points b/Lang/AutoHotkey/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..e81012edb1 --- /dev/null +++ b/Lang/AutoHotkey/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Comma-quibbling b/Lang/AutoHotkey/Comma-quibbling new file mode 120000 index 0000000000..df24c28740 --- /dev/null +++ b/Lang/AutoHotkey/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Convert-decimal-number-to-rational b/Lang/AutoHotkey/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..69c1b99e84 --- /dev/null +++ b/Lang/AutoHotkey/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Draw-a-clock b/Lang/AutoHotkey/Draw-a-clock new file mode 120000 index 0000000000..2fcd180125 --- /dev/null +++ b/Lang/AutoHotkey/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Extensible-prime-generator b/Lang/AutoHotkey/Extensible-prime-generator new file mode 120000 index 0000000000..d43a1dc8c6 --- /dev/null +++ b/Lang/AutoHotkey/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Fibonacci-word b/Lang/AutoHotkey/Fibonacci-word new file mode 120000 index 0000000000..4efc4dea27 --- /dev/null +++ b/Lang/AutoHotkey/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Fibonacci-word-fractal b/Lang/AutoHotkey/Fibonacci-word-fractal new file mode 120000 index 0000000000..5d6234f5b4 --- /dev/null +++ b/Lang/AutoHotkey/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/File-input-output b/Lang/AutoHotkey/File-input-output new file mode 120000 index 0000000000..02089c6301 --- /dev/null +++ b/Lang/AutoHotkey/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Find-the-last-Sunday-of-each-month b/Lang/AutoHotkey/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..dd20ddb868 --- /dev/null +++ b/Lang/AutoHotkey/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Flipping-bits-game b/Lang/AutoHotkey/Flipping-bits-game new file mode 120000 index 0000000000..d12aa3b5b0 --- /dev/null +++ b/Lang/AutoHotkey/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Fractran b/Lang/AutoHotkey/Fractran new file mode 120000 index 0000000000..f561542b7a --- /dev/null +++ b/Lang/AutoHotkey/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Generate-Chess960-starting-position b/Lang/AutoHotkey/Generate-Chess960-starting-position new file mode 120000 index 0000000000..bfff0c26dc --- /dev/null +++ b/Lang/AutoHotkey/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Generate-lower-case-ASCII-alphabet b/Lang/AutoHotkey/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..656a28acb3 --- /dev/null +++ b/Lang/AutoHotkey/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Hello-world-Newbie b/Lang/AutoHotkey/Hello-world-Newbie new file mode 120000 index 0000000000..142896b0f3 --- /dev/null +++ b/Lang/AutoHotkey/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/IBAN b/Lang/AutoHotkey/IBAN new file mode 120000 index 0000000000..78674522e4 --- /dev/null +++ b/Lang/AutoHotkey/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Integer-overflow b/Lang/AutoHotkey/Integer-overflow new file mode 120000 index 0000000000..f8bf3cf288 --- /dev/null +++ b/Lang/AutoHotkey/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Longest-increasing-subsequence b/Lang/AutoHotkey/Longest-increasing-subsequence new file mode 120000 index 0000000000..e4f77089ad --- /dev/null +++ b/Lang/AutoHotkey/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Ludic-numbers b/Lang/AutoHotkey/Ludic-numbers new file mode 120000 index 0000000000..399c5fbb4a --- /dev/null +++ b/Lang/AutoHotkey/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Machine-code b/Lang/AutoHotkey/Machine-code new file mode 120000 index 0000000000..df463efb1c --- /dev/null +++ b/Lang/AutoHotkey/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Magic-squares-of-odd-order b/Lang/AutoHotkey/Magic-squares-of-odd-order new file mode 120000 index 0000000000..b014f0a401 --- /dev/null +++ b/Lang/AutoHotkey/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Narcissistic-decimal-number b/Lang/AutoHotkey/Narcissistic-decimal-number new file mode 120000 index 0000000000..29b2ae7cbf --- /dev/null +++ b/Lang/AutoHotkey/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Nth b/Lang/AutoHotkey/Nth new file mode 120000 index 0000000000..14414e0ffc --- /dev/null +++ b/Lang/AutoHotkey/Nth @@ -0,0 +1 @@ +../../Task/Nth/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Old-lady-swallowed-a-fly b/Lang/AutoHotkey/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..17a9143732 --- /dev/null +++ b/Lang/AutoHotkey/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Order-disjoint-list-items b/Lang/AutoHotkey/Order-disjoint-list-items new file mode 120000 index 0000000000..37abd6cfff --- /dev/null +++ b/Lang/AutoHotkey/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Pernicious-numbers b/Lang/AutoHotkey/Pernicious-numbers new file mode 120000 index 0000000000..4e0ae12882 --- /dev/null +++ b/Lang/AutoHotkey/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Phrase-reversals b/Lang/AutoHotkey/Phrase-reversals new file mode 120000 index 0000000000..75f13b0bd8 --- /dev/null +++ b/Lang/AutoHotkey/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Quickselect-algorithm b/Lang/AutoHotkey/Quickselect-algorithm new file mode 120000 index 0000000000..d553dfd7c3 --- /dev/null +++ b/Lang/AutoHotkey/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rep-string b/Lang/AutoHotkey/Rep-string new file mode 120000 index 0000000000..e13f9cbecc --- /dev/null +++ b/Lang/AutoHotkey/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Reverse-words-in-a-string b/Lang/AutoHotkey/Reverse-words-in-a-string new file mode 120000 index 0000000000..684283a9a1 --- /dev/null +++ b/Lang/AutoHotkey/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags b/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags new file mode 120000 index 0000000000..7617e8307d --- /dev/null +++ b/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Semiprime b/Lang/AutoHotkey/Semiprime new file mode 120000 index 0000000000..3d6bc09d1b --- /dev/null +++ b/Lang/AutoHotkey/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sparkline-in-unicode b/Lang/AutoHotkey/Sparkline-in-unicode new file mode 120000 index 0000000000..cfa4c3392e --- /dev/null +++ b/Lang/AutoHotkey/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-append b/Lang/AutoHotkey/String-append new file mode 120000 index 0000000000..f8c7cacc83 --- /dev/null +++ b/Lang/AutoHotkey/String-append @@ -0,0 +1 @@ +../../Task/String-append/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-matching b/Lang/AutoHotkey/String-matching new file mode 120000 index 0000000000..9ac0489f48 --- /dev/null +++ b/Lang/AutoHotkey/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-prepend b/Lang/AutoHotkey/String-prepend new file mode 120000 index 0000000000..b230c92e13 --- /dev/null +++ b/Lang/AutoHotkey/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sum-multiples-of-3-and-5 b/Lang/AutoHotkey/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..a0ab49c8b3 --- /dev/null +++ b/Lang/AutoHotkey/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/The-Twelve-Days-of-Christmas b/Lang/AutoHotkey/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..24b21edd51 --- /dev/null +++ b/Lang/AutoHotkey/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Zero-to-the-zero-power b/Lang/AutoHotkey/Zero-to-the-zero-power new file mode 120000 index 0000000000..05b636b347 --- /dev/null +++ b/Lang/AutoHotkey/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Zhang-Suen-thinning-algorithm b/Lang/AutoHotkey/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..bf9ab60f1d --- /dev/null +++ b/Lang/AutoHotkey/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/String-matching b/Lang/AutoIt/String-matching new file mode 120000 index 0000000000..31f39c11d3 --- /dev/null +++ b/Lang/AutoIt/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/AutoIt \ No newline at end of file diff --git a/Lang/Axiom/Closures-Value-capture b/Lang/Axiom/Closures-Value-capture new file mode 120000 index 0000000000..d625f11eb5 --- /dev/null +++ b/Lang/Axiom/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Axiom \ No newline at end of file diff --git a/Lang/BASIC/Circles-of-given-radius-through-two-points b/Lang/BASIC/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..74b568825e --- /dev/null +++ b/Lang/BASIC/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/BASIC \ No newline at end of file diff --git a/Lang/BASIC/File-input-output b/Lang/BASIC/File-input-output new file mode 120000 index 0000000000..88cc5c1a8d --- /dev/null +++ b/Lang/BASIC/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Runge-Kutta-method b/Lang/BASIC/Runge-Kutta-method new file mode 120000 index 0000000000..7b27a16010 --- /dev/null +++ b/Lang/BASIC/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-append b/Lang/BASIC/String-append new file mode 120000 index 0000000000..f1e07a21b9 --- /dev/null +++ b/Lang/BASIC/String-append @@ -0,0 +1 @@ +../../Task/String-append/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-matching b/Lang/BASIC/String-matching new file mode 120000 index 0000000000..364ed61428 --- /dev/null +++ b/Lang/BASIC/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-prepend b/Lang/BASIC/String-prepend new file mode 120000 index 0000000000..7601eb5216 --- /dev/null +++ b/Lang/BASIC/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/ABC-Problem b/Lang/BBC-BASIC/ABC-Problem new file mode 120000 index 0000000000..233eed606b --- /dev/null +++ b/Lang/BBC-BASIC/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Calendar---for-REAL-programmers b/Lang/BBC-BASIC/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..8862e004c1 --- /dev/null +++ b/Lang/BBC-BASIC/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/File-input-output b/Lang/BBC-BASIC/File-input-output new file mode 120000 index 0000000000..23e89931ad --- /dev/null +++ b/Lang/BBC-BASIC/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Find-the-last-Sunday-of-each-month b/Lang/BBC-BASIC/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..f445c096f0 --- /dev/null +++ b/Lang/BBC-BASIC/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..19bbed8353 --- /dev/null +++ b/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/IBAN b/Lang/BBC-BASIC/IBAN new file mode 120000 index 0000000000..52a4a62cd7 --- /dev/null +++ b/Lang/BBC-BASIC/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Machine-code b/Lang/BBC-BASIC/Machine-code new file mode 120000 index 0000000000..bf3436f0a4 --- /dev/null +++ b/Lang/BBC-BASIC/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Nth b/Lang/BBC-BASIC/Nth new file mode 120000 index 0000000000..0b0ab858c8 --- /dev/null +++ b/Lang/BBC-BASIC/Nth @@ -0,0 +1 @@ +../../Task/Nth/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Reverse-words-in-a-string b/Lang/BBC-BASIC/Reverse-words-in-a-string new file mode 120000 index 0000000000..2d91cb46b6 --- /dev/null +++ b/Lang/BBC-BASIC/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-matching b/Lang/BBC-BASIC/String-matching new file mode 120000 index 0000000000..6a5b2550f2 --- /dev/null +++ b/Lang/BBC-BASIC/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/BBC-BASIC \ No newline at end of file diff --git a/Lang/Babel/Closures-Value-capture b/Lang/Babel/Closures-Value-capture new file mode 120000 index 0000000000..ed6bc23bfe --- /dev/null +++ b/Lang/Babel/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Babel \ No newline at end of file diff --git a/Lang/Babel/File-input-output b/Lang/Babel/File-input-output new file mode 120000 index 0000000000..d0cd5bf227 --- /dev/null +++ b/Lang/Babel/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Babel \ No newline at end of file diff --git a/Lang/Babel/Nth b/Lang/Babel/Nth new file mode 120000 index 0000000000..580b9e31d8 --- /dev/null +++ b/Lang/Babel/Nth @@ -0,0 +1 @@ +../../Task/Nth/Babel \ No newline at end of file diff --git a/Lang/Babel/Old-lady-swallowed-a-fly b/Lang/Babel/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..7630f31062 --- /dev/null +++ b/Lang/Babel/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Babel \ No newline at end of file diff --git a/Lang/Batch-File/ABC-Problem b/Lang/Batch-File/ABC-Problem new file mode 120000 index 0000000000..51e7233298 --- /dev/null +++ b/Lang/Batch-File/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Catalan-numbers-Pascals-triangle b/Lang/Batch-File/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..bea743141b --- /dev/null +++ b/Lang/Batch-File/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/File-input-output b/Lang/Batch-File/File-input-output new file mode 120000 index 0000000000..c95b17b313 --- /dev/null +++ b/Lang/Batch-File/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/File-input-output b/Lang/Befunge/File-input-output new file mode 120000 index 0000000000..5fb27c8b14 --- /dev/null +++ b/Lang/Befunge/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/ABC-Problem b/Lang/Bracmat/ABC-Problem new file mode 120000 index 0000000000..51a5310324 --- /dev/null +++ b/Lang/Bracmat/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/AKS-test-for-primes b/Lang/Bracmat/AKS-test-for-primes new file mode 120000 index 0000000000..7cfad10773 --- /dev/null +++ b/Lang/Bracmat/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Amb b/Lang/Bracmat/Amb new file mode 120000 index 0000000000..ae8706e8ff --- /dev/null +++ b/Lang/Bracmat/Amb @@ -0,0 +1 @@ +../../Task/Amb/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Catamorphism b/Lang/Bracmat/Catamorphism new file mode 120000 index 0000000000..d65e448502 --- /dev/null +++ b/Lang/Bracmat/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Chinese-remainder-theorem b/Lang/Bracmat/Chinese-remainder-theorem new file mode 120000 index 0000000000..bf7b677f05 --- /dev/null +++ b/Lang/Bracmat/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Closures-Value-capture b/Lang/Bracmat/Closures-Value-capture new file mode 120000 index 0000000000..47f5797153 --- /dev/null +++ b/Lang/Bracmat/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Combinations-and-permutations b/Lang/Bracmat/Combinations-and-permutations new file mode 120000 index 0000000000..280c89cd0a --- /dev/null +++ b/Lang/Bracmat/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Convert-decimal-number-to-rational b/Lang/Bracmat/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..a4c5c67914 --- /dev/null +++ b/Lang/Bracmat/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Digital-root-Multiplicative-digital-root b/Lang/Bracmat/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..e060e22fb6 --- /dev/null +++ b/Lang/Bracmat/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/File-input-output b/Lang/Bracmat/File-input-output new file mode 120000 index 0000000000..45715d1712 --- /dev/null +++ b/Lang/Bracmat/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Fractran b/Lang/Bracmat/Fractran new file mode 120000 index 0000000000..fea02a9ec0 --- /dev/null +++ b/Lang/Bracmat/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Generate-lower-case-ASCII-alphabet b/Lang/Bracmat/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..0f9bcfb380 --- /dev/null +++ b/Lang/Bracmat/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Hash-join b/Lang/Bracmat/Hash-join new file mode 120000 index 0000000000..6f813fc5e3 --- /dev/null +++ b/Lang/Bracmat/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Hickerson-series-of-almost-integers b/Lang/Bracmat/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..eff7811324 --- /dev/null +++ b/Lang/Bracmat/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/IBAN b/Lang/Bracmat/IBAN new file mode 120000 index 0000000000..53a8115df6 --- /dev/null +++ b/Lang/Bracmat/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Left-factorials b/Lang/Bracmat/Left-factorials new file mode 120000 index 0000000000..c20420ccbd --- /dev/null +++ b/Lang/Bracmat/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Maximum-triangle-path-sum b/Lang/Bracmat/Maximum-triangle-path-sum new file mode 120000 index 0000000000..2d6859f94e --- /dev/null +++ b/Lang/Bracmat/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Odd-word-problem b/Lang/Bracmat/Odd-word-problem new file mode 120000 index 0000000000..d9518b3fb5 --- /dev/null +++ b/Lang/Bracmat/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Order-disjoint-list-items b/Lang/Bracmat/Order-disjoint-list-items new file mode 120000 index 0000000000..3de9822771 --- /dev/null +++ b/Lang/Bracmat/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Phrase-reversals b/Lang/Bracmat/Phrase-reversals new file mode 120000 index 0000000000..d87520817b --- /dev/null +++ b/Lang/Bracmat/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Rep-string b/Lang/Bracmat/Rep-string new file mode 120000 index 0000000000..ce0401cbf7 --- /dev/null +++ b/Lang/Bracmat/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Reverse-words-in-a-string b/Lang/Bracmat/Reverse-words-in-a-string new file mode 120000 index 0000000000..b24b7d5399 --- /dev/null +++ b/Lang/Bracmat/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Solve-a-Holy-Knights-tour b/Lang/Bracmat/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..92d501866b --- /dev/null +++ b/Lang/Bracmat/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/State-name-puzzle b/Lang/Bracmat/State-name-puzzle new file mode 120000 index 0000000000..7bdcb94afe --- /dev/null +++ b/Lang/Bracmat/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-matching b/Lang/Bracmat/String-matching new file mode 120000 index 0000000000..e824bcf93e --- /dev/null +++ b/Lang/Bracmat/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-prepend b/Lang/Bracmat/String-prepend new file mode 120000 index 0000000000..27318b9437 --- /dev/null +++ b/Lang/Bracmat/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/The-Twelve-Days-of-Christmas b/Lang/Bracmat/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..56c7e5e1cb --- /dev/null +++ b/Lang/Bracmat/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Zero-to-the-zero-power b/Lang/Bracmat/Zero-to-the-zero-power new file mode 120000 index 0000000000..b3670c2c19 --- /dev/null +++ b/Lang/Bracmat/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Bracmat \ No newline at end of file diff --git a/Lang/Burlesque/Munching-squares b/Lang/Burlesque/Munching-squares new file mode 120000 index 0000000000..2b22b74e5c --- /dev/null +++ b/Lang/Burlesque/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Burlesque \ No newline at end of file diff --git a/Lang/C++/9-billion-names-of-God-the-integer b/Lang/C++/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..2467ffbdc8 --- /dev/null +++ b/Lang/C++/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/C++ \ No newline at end of file diff --git a/Lang/C++/ABC-Problem b/Lang/C++/ABC-Problem new file mode 120000 index 0000000000..017d40427d --- /dev/null +++ b/Lang/C++/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/C++ \ No newline at end of file diff --git a/Lang/C++/Arithmetic-geometric-mean-Calculate-Pi b/Lang/C++/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..caacb05a88 --- /dev/null +++ b/Lang/C++/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/C++ \ No newline at end of file diff --git a/Lang/C++/Benfords-law b/Lang/C++/Benfords-law new file mode 120000 index 0000000000..299cd7ec40 --- /dev/null +++ b/Lang/C++/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/C++ \ No newline at end of file diff --git a/Lang/C++/CSV-data-manipulation b/Lang/C++/CSV-data-manipulation new file mode 120000 index 0000000000..5ee00c56ab --- /dev/null +++ b/Lang/C++/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/C++ \ No newline at end of file diff --git a/Lang/C++/Casting-out-nines b/Lang/C++/Casting-out-nines new file mode 120000 index 0000000000..b2e023a1b5 --- /dev/null +++ b/Lang/C++/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/C++ \ No newline at end of file diff --git a/Lang/C++/Catalan-numbers-Pascals-triangle b/Lang/C++/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..8d7b7d3d04 --- /dev/null +++ b/Lang/C++/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/C++ \ No newline at end of file diff --git a/Lang/C++/Catamorphism b/Lang/C++/Catamorphism new file mode 120000 index 0000000000..078dacdd57 --- /dev/null +++ b/Lang/C++/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/C++ \ No newline at end of file diff --git a/Lang/C++/Closures-Value-capture b/Lang/C++/Closures-Value-capture new file mode 120000 index 0000000000..9798b5b79b --- /dev/null +++ b/Lang/C++/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/C++ \ No newline at end of file diff --git a/Lang/C++/Comma-quibbling b/Lang/C++/Comma-quibbling new file mode 120000 index 0000000000..09b0bb2376 --- /dev/null +++ b/Lang/C++/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/C++ \ No newline at end of file diff --git a/Lang/C++/Digital-root-Multiplicative-digital-root b/Lang/C++/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..6a38b4d6b5 --- /dev/null +++ b/Lang/C++/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/C++ \ No newline at end of file diff --git a/Lang/C++/Draw-a-clock b/Lang/C++/Draw-a-clock new file mode 120000 index 0000000000..fb8f95f376 --- /dev/null +++ b/Lang/C++/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/C++ \ No newline at end of file diff --git a/Lang/C++/Fibonacci-word b/Lang/C++/Fibonacci-word new file mode 120000 index 0000000000..b961ee2974 --- /dev/null +++ b/Lang/C++/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/C++ \ No newline at end of file diff --git a/Lang/C++/Fibonacci-word-fractal b/Lang/C++/Fibonacci-word-fractal new file mode 120000 index 0000000000..8be7264c18 --- /dev/null +++ b/Lang/C++/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/C++ \ No newline at end of file diff --git a/Lang/C++/File-input-output b/Lang/C++/File-input-output new file mode 120000 index 0000000000..9d317b0253 --- /dev/null +++ b/Lang/C++/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/C++ \ No newline at end of file diff --git a/Lang/C++/Find-the-last-Sunday-of-each-month b/Lang/C++/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..06f15e89b0 --- /dev/null +++ b/Lang/C++/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/C++ \ No newline at end of file diff --git a/Lang/C++/Flipping-bits-game b/Lang/C++/Flipping-bits-game new file mode 120000 index 0000000000..5e8ed11bca --- /dev/null +++ b/Lang/C++/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/C++ \ No newline at end of file diff --git a/Lang/C++/Fractran b/Lang/C++/Fractran new file mode 120000 index 0000000000..9f767a92a8 --- /dev/null +++ b/Lang/C++/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/C++ \ No newline at end of file diff --git a/Lang/C++/Generate-Chess960-starting-position b/Lang/C++/Generate-Chess960-starting-position new file mode 120000 index 0000000000..67634e478a --- /dev/null +++ b/Lang/C++/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/C++ \ No newline at end of file diff --git a/Lang/C++/Generate-lower-case-ASCII-alphabet b/Lang/C++/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..7814ae2002 --- /dev/null +++ b/Lang/C++/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/C++ \ No newline at end of file diff --git a/Lang/C++/Hickerson-series-of-almost-integers b/Lang/C++/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..eb68eb9da7 --- /dev/null +++ b/Lang/C++/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/C++ \ No newline at end of file diff --git a/Lang/C++/IBAN b/Lang/C++/IBAN new file mode 120000 index 0000000000..1b12552486 --- /dev/null +++ b/Lang/C++/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/C++ \ No newline at end of file diff --git a/Lang/C++/Iterated-digits-squaring b/Lang/C++/Iterated-digits-squaring new file mode 120000 index 0000000000..c1c12b1a5c --- /dev/null +++ b/Lang/C++/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/C++ \ No newline at end of file diff --git a/Lang/C++/Longest-increasing-subsequence b/Lang/C++/Longest-increasing-subsequence new file mode 120000 index 0000000000..ee010f9bf1 --- /dev/null +++ b/Lang/C++/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/C++ \ No newline at end of file diff --git a/Lang/C++/Ludic-numbers b/Lang/C++/Ludic-numbers new file mode 120000 index 0000000000..ffa444c11f --- /dev/null +++ b/Lang/C++/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/C++ \ No newline at end of file diff --git a/Lang/C++/Magic-squares-of-odd-order b/Lang/C++/Magic-squares-of-odd-order new file mode 120000 index 0000000000..b7c54d1042 --- /dev/null +++ b/Lang/C++/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/C++ \ No newline at end of file diff --git a/Lang/C++/Maximum-triangle-path-sum b/Lang/C++/Maximum-triangle-path-sum new file mode 120000 index 0000000000..60d78740d8 --- /dev/null +++ b/Lang/C++/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/C++ \ No newline at end of file diff --git a/Lang/C++/Move-to-front-algorithm b/Lang/C++/Move-to-front-algorithm new file mode 120000 index 0000000000..7854b52031 --- /dev/null +++ b/Lang/C++/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/C++ \ No newline at end of file diff --git a/Lang/C++/Munching-squares b/Lang/C++/Munching-squares new file mode 120000 index 0000000000..eecf344cd9 --- /dev/null +++ b/Lang/C++/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/C++ \ No newline at end of file diff --git a/Lang/C++/Narcissistic-decimal-number b/Lang/C++/Narcissistic-decimal-number new file mode 120000 index 0000000000..f736f0dbd4 --- /dev/null +++ b/Lang/C++/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/C++ \ No newline at end of file diff --git a/Lang/C++/Odd-word-problem b/Lang/C++/Odd-word-problem new file mode 120000 index 0000000000..7172dac925 --- /dev/null +++ b/Lang/C++/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Penneys-game b/Lang/C++/Penneys-game new file mode 120000 index 0000000000..7acc8744ca --- /dev/null +++ b/Lang/C++/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/C++ \ No newline at end of file diff --git a/Lang/C++/Percolation-Mean-run-density b/Lang/C++/Percolation-Mean-run-density new file mode 120000 index 0000000000..8d8db2ecb7 --- /dev/null +++ b/Lang/C++/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/C++ \ No newline at end of file diff --git a/Lang/C++/Pernicious-numbers b/Lang/C++/Pernicious-numbers new file mode 120000 index 0000000000..b8b2e7ecdf --- /dev/null +++ b/Lang/C++/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/C++ \ No newline at end of file diff --git a/Lang/C++/Phrase-reversals b/Lang/C++/Phrase-reversals new file mode 120000 index 0000000000..b8fb2a3d01 --- /dev/null +++ b/Lang/C++/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/C++ \ No newline at end of file diff --git a/Lang/C++/Quickselect-algorithm b/Lang/C++/Quickselect-algorithm new file mode 120000 index 0000000000..8cad248221 --- /dev/null +++ b/Lang/C++/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/C++ \ No newline at end of file diff --git a/Lang/C++/Rep-string b/Lang/C++/Rep-string new file mode 120000 index 0000000000..7f5c6352e9 --- /dev/null +++ b/Lang/C++/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/C++ \ No newline at end of file diff --git a/Lang/C++/Reverse-words-in-a-string b/Lang/C++/Reverse-words-in-a-string new file mode 120000 index 0000000000..7d76932271 --- /dev/null +++ b/Lang/C++/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/C++ \ No newline at end of file diff --git a/Lang/C++/Semiprime b/Lang/C++/Semiprime new file mode 120000 index 0000000000..d725311471 --- /dev/null +++ b/Lang/C++/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/C++ \ No newline at end of file diff --git a/Lang/C++/Solve-a-Holy-Knights-tour b/Lang/C++/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..d1d8f48bf4 --- /dev/null +++ b/Lang/C++/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/C++ \ No newline at end of file diff --git a/Lang/C++/Solve-a-Hopido-puzzle b/Lang/C++/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..91f3c5d4c1 --- /dev/null +++ b/Lang/C++/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/C++ \ No newline at end of file diff --git a/Lang/C++/Solve-a-Numbrix-puzzle b/Lang/C++/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..fef94afa89 --- /dev/null +++ b/Lang/C++/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/C++ \ No newline at end of file diff --git a/Lang/C++/Sparkline-in-unicode b/Lang/C++/Sparkline-in-unicode new file mode 120000 index 0000000000..18739b0225 --- /dev/null +++ b/Lang/C++/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/C++ \ No newline at end of file diff --git a/Lang/C++/String-append b/Lang/C++/String-append new file mode 120000 index 0000000000..8095b1a214 --- /dev/null +++ b/Lang/C++/String-append @@ -0,0 +1 @@ +../../Task/String-append/C++ \ No newline at end of file diff --git a/Lang/C++/String-matching b/Lang/C++/String-matching new file mode 120000 index 0000000000..7c4d92bdac --- /dev/null +++ b/Lang/C++/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/C++ \ No newline at end of file diff --git a/Lang/C++/String-prepend b/Lang/C++/String-prepend new file mode 120000 index 0000000000..021f2ab069 --- /dev/null +++ b/Lang/C++/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/C++ \ No newline at end of file diff --git a/Lang/C++/Sum-multiples-of-3-and-5 b/Lang/C++/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..6b117e665b --- /dev/null +++ b/Lang/C++/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/C++ \ No newline at end of file diff --git a/Lang/C++/The-Twelve-Days-of-Christmas b/Lang/C++/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..b3fcc978bf --- /dev/null +++ b/Lang/C++/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/C++ \ No newline at end of file diff --git a/Lang/C++/Zero-to-the-zero-power b/Lang/C++/Zero-to-the-zero-power new file mode 120000 index 0000000000..06ccf77736 --- /dev/null +++ b/Lang/C++/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/C++ \ No newline at end of file diff --git a/Lang/C-sharp/ABC-Problem b/Lang/C-sharp/ABC-Problem new file mode 120000 index 0000000000..c073dc3e3a --- /dev/null +++ b/Lang/C-sharp/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Almost-prime b/Lang/C-sharp/Almost-prime new file mode 120000 index 0000000000..786e24d952 --- /dev/null +++ b/Lang/C-sharp/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Amb b/Lang/C-sharp/Amb new file mode 120000 index 0000000000..00596741c8 --- /dev/null +++ b/Lang/C-sharp/Amb @@ -0,0 +1 @@ +../../Task/Amb/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/CSV-data-manipulation b/Lang/C-sharp/CSV-data-manipulation new file mode 120000 index 0000000000..14a7ba0272 --- /dev/null +++ b/Lang/C-sharp/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Catamorphism b/Lang/C-sharp/Catamorphism new file mode 120000 index 0000000000..3c49f6b24b --- /dev/null +++ b/Lang/C-sharp/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Currying b/Lang/C-sharp/Currying new file mode 120000 index 0000000000..1878e43f29 --- /dev/null +++ b/Lang/C-sharp/Currying @@ -0,0 +1 @@ +../../Task/Currying/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Generate-lower-case-ASCII-alphabet b/Lang/C-sharp/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..79815d9f6b --- /dev/null +++ b/Lang/C-sharp/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Hash-join b/Lang/C-sharp/Hash-join new file mode 120000 index 0000000000..b5048f6675 --- /dev/null +++ b/Lang/C-sharp/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/IBAN b/Lang/C-sharp/IBAN new file mode 120000 index 0000000000..165bfdefab --- /dev/null +++ b/Lang/C-sharp/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Munching-squares b/Lang/C-sharp/Munching-squares new file mode 120000 index 0000000000..e63924f158 --- /dev/null +++ b/Lang/C-sharp/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/String-prepend b/Lang/C-sharp/String-prepend new file mode 120000 index 0000000000..0bf2459a4a --- /dev/null +++ b/Lang/C-sharp/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/The-ISAAC-Cipher b/Lang/C-sharp/The-ISAAC-Cipher new file mode 120000 index 0000000000..1c1e4e9587 --- /dev/null +++ b/Lang/C-sharp/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/C-sharp \ No newline at end of file diff --git a/Lang/C/9-billion-names-of-God-the-integer b/Lang/C/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..738edf38a6 --- /dev/null +++ b/Lang/C/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/C \ No newline at end of file diff --git a/Lang/C/ABC-Problem b/Lang/C/ABC-Problem new file mode 120000 index 0000000000..b085d03516 --- /dev/null +++ b/Lang/C/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/C \ No newline at end of file diff --git a/Lang/C/AKS-test-for-primes b/Lang/C/AKS-test-for-primes new file mode 120000 index 0000000000..8ed84c3054 --- /dev/null +++ b/Lang/C/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/C \ No newline at end of file diff --git a/Lang/C/Abundant,-deficient-and-perfect-number-classifications b/Lang/C/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..b71e4143d0 --- /dev/null +++ b/Lang/C/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/C \ No newline at end of file diff --git a/Lang/C/Almost-prime b/Lang/C/Almost-prime new file mode 120000 index 0000000000..14cda43503 --- /dev/null +++ b/Lang/C/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/C \ No newline at end of file diff --git a/Lang/C/Amb b/Lang/C/Amb new file mode 120000 index 0000000000..cea1af76e5 --- /dev/null +++ b/Lang/C/Amb @@ -0,0 +1 @@ +../../Task/Amb/C \ No newline at end of file diff --git a/Lang/C/Amicable-pairs b/Lang/C/Amicable-pairs new file mode 120000 index 0000000000..1692525888 --- /dev/null +++ b/Lang/C/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/C \ No newline at end of file diff --git a/Lang/C/Append-a-record-to-the-end-of-a-text-file b/Lang/C/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..9caa9544d5 --- /dev/null +++ b/Lang/C/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/C \ No newline at end of file diff --git a/Lang/C/Arithmetic-geometric-mean-Calculate-Pi b/Lang/C/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..484313b5cb --- /dev/null +++ b/Lang/C/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/C \ No newline at end of file diff --git a/Lang/C/Benfords-law b/Lang/C/Benfords-law new file mode 120000 index 0000000000..f7cc9a8540 --- /dev/null +++ b/Lang/C/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/C \ No newline at end of file diff --git a/Lang/C/Bernoulli-numbers b/Lang/C/Bernoulli-numbers new file mode 120000 index 0000000000..75a1a05738 --- /dev/null +++ b/Lang/C/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/C \ No newline at end of file diff --git a/Lang/C/Bitcoin-public-point-to-address b/Lang/C/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..c57a95efdd --- /dev/null +++ b/Lang/C/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/C \ No newline at end of file diff --git a/Lang/C/Catamorphism b/Lang/C/Catamorphism new file mode 120000 index 0000000000..47e47f0bc4 --- /dev/null +++ b/Lang/C/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/C \ No newline at end of file diff --git a/Lang/C/Chinese-remainder-theorem b/Lang/C/Chinese-remainder-theorem new file mode 120000 index 0000000000..5be65a6b03 --- /dev/null +++ b/Lang/C/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/C \ No newline at end of file diff --git a/Lang/C/Circles-of-given-radius-through-two-points b/Lang/C/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..7c1fe77f82 --- /dev/null +++ b/Lang/C/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/C \ No newline at end of file diff --git a/Lang/C/Closures-Value-capture b/Lang/C/Closures-Value-capture new file mode 120000 index 0000000000..b65029c443 --- /dev/null +++ b/Lang/C/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/C \ No newline at end of file diff --git a/Lang/C/Combinations-and-permutations b/Lang/C/Combinations-and-permutations new file mode 120000 index 0000000000..39450ab0ef --- /dev/null +++ b/Lang/C/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/C \ No newline at end of file diff --git a/Lang/C/Comma-quibbling b/Lang/C/Comma-quibbling new file mode 120000 index 0000000000..20af14abe8 --- /dev/null +++ b/Lang/C/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/C \ No newline at end of file diff --git a/Lang/C/Conjugate-transpose b/Lang/C/Conjugate-transpose new file mode 120000 index 0000000000..7b242426e0 --- /dev/null +++ b/Lang/C/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/C \ No newline at end of file diff --git a/Lang/C/Convert-decimal-number-to-rational b/Lang/C/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..f943894ebf --- /dev/null +++ b/Lang/C/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/C \ No newline at end of file diff --git a/Lang/C/Digital-root-Multiplicative-digital-root b/Lang/C/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..f5d01a66d9 --- /dev/null +++ b/Lang/C/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/C \ No newline at end of file diff --git a/Lang/C/Draw-a-clock b/Lang/C/Draw-a-clock new file mode 120000 index 0000000000..299cae1dad --- /dev/null +++ b/Lang/C/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/C \ No newline at end of file diff --git a/Lang/C/Extensible-prime-generator b/Lang/C/Extensible-prime-generator new file mode 120000 index 0000000000..246d14960b --- /dev/null +++ b/Lang/C/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/C \ No newline at end of file diff --git a/Lang/C/Fibonacci-word b/Lang/C/Fibonacci-word new file mode 120000 index 0000000000..724a901b66 --- /dev/null +++ b/Lang/C/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/C \ No newline at end of file diff --git a/Lang/C/File-input-output b/Lang/C/File-input-output new file mode 120000 index 0000000000..fac94c51d8 --- /dev/null +++ b/Lang/C/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/C \ No newline at end of file diff --git a/Lang/C/Flipping-bits-game b/Lang/C/Flipping-bits-game new file mode 120000 index 0000000000..c6f566e9f0 --- /dev/null +++ b/Lang/C/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/C \ No newline at end of file diff --git a/Lang/C/Fractran b/Lang/C/Fractran new file mode 120000 index 0000000000..b74bf80115 --- /dev/null +++ b/Lang/C/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/C \ No newline at end of file diff --git a/Lang/C/Gaussian-elimination b/Lang/C/Gaussian-elimination new file mode 120000 index 0000000000..2c3448b3d7 --- /dev/null +++ b/Lang/C/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/C \ No newline at end of file diff --git a/Lang/C/Generate-lower-case-ASCII-alphabet b/Lang/C/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b776471d04 --- /dev/null +++ b/Lang/C/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/C \ No newline at end of file diff --git a/Lang/C/Hickerson-series-of-almost-integers b/Lang/C/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..014107e679 --- /dev/null +++ b/Lang/C/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/C \ No newline at end of file diff --git a/Lang/C/IBAN b/Lang/C/IBAN new file mode 120000 index 0000000000..0e4821ae74 --- /dev/null +++ b/Lang/C/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/C \ No newline at end of file diff --git a/Lang/C/Integer-overflow b/Lang/C/Integer-overflow new file mode 120000 index 0000000000..f04aa188ee --- /dev/null +++ b/Lang/C/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/C \ No newline at end of file diff --git a/Lang/C/Iterated-digits-squaring b/Lang/C/Iterated-digits-squaring new file mode 120000 index 0000000000..b33eecabef --- /dev/null +++ b/Lang/C/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/C \ No newline at end of file diff --git a/Lang/C/K-d-tree b/Lang/C/K-d-tree new file mode 120000 index 0000000000..fc3772c129 --- /dev/null +++ b/Lang/C/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/C \ No newline at end of file diff --git a/Lang/C/Left-factorials b/Lang/C/Left-factorials new file mode 120000 index 0000000000..cb00422381 --- /dev/null +++ b/Lang/C/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/C \ No newline at end of file diff --git a/Lang/C/Longest-increasing-subsequence b/Lang/C/Longest-increasing-subsequence new file mode 120000 index 0000000000..e77223f626 --- /dev/null +++ b/Lang/C/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/C \ No newline at end of file diff --git a/Lang/C/Ludic-numbers b/Lang/C/Ludic-numbers new file mode 120000 index 0000000000..150acc3b99 --- /dev/null +++ b/Lang/C/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/C \ No newline at end of file diff --git a/Lang/C/Machine-code b/Lang/C/Machine-code new file mode 120000 index 0000000000..7ddfca9839 --- /dev/null +++ b/Lang/C/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/C \ No newline at end of file diff --git a/Lang/C/Magic-squares-of-odd-order b/Lang/C/Magic-squares-of-odd-order new file mode 120000 index 0000000000..727f46d1c7 --- /dev/null +++ b/Lang/C/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/C \ No newline at end of file diff --git a/Lang/C/Maximum-triangle-path-sum b/Lang/C/Maximum-triangle-path-sum new file mode 120000 index 0000000000..0e06ac46d8 --- /dev/null +++ b/Lang/C/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/C \ No newline at end of file diff --git a/Lang/C/Move-to-front-algorithm b/Lang/C/Move-to-front-algorithm new file mode 120000 index 0000000000..f44f0d61e4 --- /dev/null +++ b/Lang/C/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/C \ No newline at end of file diff --git a/Lang/C/Munching-squares b/Lang/C/Munching-squares new file mode 120000 index 0000000000..a9432d7190 --- /dev/null +++ b/Lang/C/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/C \ No newline at end of file diff --git a/Lang/C/Narcissistic-decimal-number b/Lang/C/Narcissistic-decimal-number new file mode 120000 index 0000000000..5da0f3b38c --- /dev/null +++ b/Lang/C/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/C \ No newline at end of file diff --git a/Lang/C/Natural-sorting b/Lang/C/Natural-sorting new file mode 120000 index 0000000000..7544473952 --- /dev/null +++ b/Lang/C/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/C \ No newline at end of file diff --git a/Lang/C/Nth b/Lang/C/Nth new file mode 120000 index 0000000000..a85ae760e6 --- /dev/null +++ b/Lang/C/Nth @@ -0,0 +1 @@ +../../Task/Nth/C \ No newline at end of file diff --git a/Lang/C/Odd-word-problem b/Lang/C/Odd-word-problem new file mode 120000 index 0000000000..c8bc19ffc8 --- /dev/null +++ b/Lang/C/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/C \ No newline at end of file diff --git a/Lang/C/Old-lady-swallowed-a-fly b/Lang/C/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..4786402edc --- /dev/null +++ b/Lang/C/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/C \ No newline at end of file diff --git a/Lang/C/Paraffins b/Lang/C/Paraffins new file mode 120000 index 0000000000..c64af40ea6 --- /dev/null +++ b/Lang/C/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/C \ No newline at end of file diff --git a/Lang/C/Parse-an-IP-Address b/Lang/C/Parse-an-IP-Address new file mode 120000 index 0000000000..4223e48ee5 --- /dev/null +++ b/Lang/C/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/C \ No newline at end of file diff --git a/Lang/C/Penneys-game b/Lang/C/Penneys-game new file mode 120000 index 0000000000..945ac4e35e --- /dev/null +++ b/Lang/C/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/C \ No newline at end of file diff --git a/Lang/C/Percolation-Bond-percolation b/Lang/C/Percolation-Bond-percolation new file mode 120000 index 0000000000..c7b0247fec --- /dev/null +++ b/Lang/C/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/C \ No newline at end of file diff --git a/Lang/C/Percolation-Mean-cluster-density b/Lang/C/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..c63538b332 --- /dev/null +++ b/Lang/C/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/C \ No newline at end of file diff --git a/Lang/C/Percolation-Mean-run-density b/Lang/C/Percolation-Mean-run-density new file mode 120000 index 0000000000..7f3da5c7bb --- /dev/null +++ b/Lang/C/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/C \ No newline at end of file diff --git a/Lang/C/Percolation-Site-percolation b/Lang/C/Percolation-Site-percolation new file mode 120000 index 0000000000..e9cb8f0340 --- /dev/null +++ b/Lang/C/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/C \ No newline at end of file diff --git a/Lang/C/Permutations-Rank-of-a-permutation b/Lang/C/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..bf624de1d1 --- /dev/null +++ b/Lang/C/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/C \ No newline at end of file diff --git a/Lang/C/Pernicious-numbers b/Lang/C/Pernicious-numbers new file mode 120000 index 0000000000..9face3994d --- /dev/null +++ b/Lang/C/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/C \ No newline at end of file diff --git a/Lang/C/Phrase-reversals b/Lang/C/Phrase-reversals new file mode 120000 index 0000000000..19b162f92a --- /dev/null +++ b/Lang/C/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/C \ No newline at end of file diff --git a/Lang/C/Quickselect-algorithm b/Lang/C/Quickselect-algorithm new file mode 120000 index 0000000000..8537bfc36a --- /dev/null +++ b/Lang/C/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/C \ No newline at end of file diff --git a/Lang/C/Rep-string b/Lang/C/Rep-string new file mode 120000 index 0000000000..84cb693941 --- /dev/null +++ b/Lang/C/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/C \ No newline at end of file diff --git a/Lang/C/Reverse-words-in-a-string b/Lang/C/Reverse-words-in-a-string new file mode 120000 index 0000000000..61bc3ce7ee --- /dev/null +++ b/Lang/C/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/C \ No newline at end of file diff --git a/Lang/C/Rosetta-Code-Find-bare-lang-tags b/Lang/C/Rosetta-Code-Find-bare-lang-tags new file mode 120000 index 0000000000..e0bc95da7b --- /dev/null +++ b/Lang/C/Rosetta-Code-Find-bare-lang-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-bare-lang-tags/C \ No newline at end of file diff --git a/Lang/C/Runge-Kutta-method b/Lang/C/Runge-Kutta-method new file mode 120000 index 0000000000..f2fcb1a937 --- /dev/null +++ b/Lang/C/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/C \ No newline at end of file diff --git a/Lang/C/Semiprime b/Lang/C/Semiprime new file mode 120000 index 0000000000..e7166161d0 --- /dev/null +++ b/Lang/C/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/C \ No newline at end of file diff --git a/Lang/C/State-name-puzzle b/Lang/C/State-name-puzzle new file mode 120000 index 0000000000..e64c664ee1 --- /dev/null +++ b/Lang/C/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/C \ No newline at end of file diff --git a/Lang/C/Statistics-Basic b/Lang/C/Statistics-Basic new file mode 120000 index 0000000000..d8ead05acd --- /dev/null +++ b/Lang/C/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/C \ No newline at end of file diff --git a/Lang/C/Stern-Brocot-sequence b/Lang/C/Stern-Brocot-sequence new file mode 120000 index 0000000000..a47f9a4c5d --- /dev/null +++ b/Lang/C/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/C \ No newline at end of file diff --git a/Lang/C/String-append b/Lang/C/String-append new file mode 120000 index 0000000000..9b73797433 --- /dev/null +++ b/Lang/C/String-append @@ -0,0 +1 @@ +../../Task/String-append/C \ No newline at end of file diff --git a/Lang/C/String-matching b/Lang/C/String-matching new file mode 120000 index 0000000000..fd0270e7b7 --- /dev/null +++ b/Lang/C/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/C \ No newline at end of file diff --git a/Lang/C/String-prepend b/Lang/C/String-prepend new file mode 120000 index 0000000000..de0d586b6e --- /dev/null +++ b/Lang/C/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/C \ No newline at end of file diff --git a/Lang/C/Sum-multiples-of-3-and-5 b/Lang/C/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..dffdbff8a6 --- /dev/null +++ b/Lang/C/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/C \ No newline at end of file diff --git a/Lang/C/The-ISAAC-Cipher b/Lang/C/The-ISAAC-Cipher new file mode 120000 index 0000000000..0d181e8777 --- /dev/null +++ b/Lang/C/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/C \ No newline at end of file diff --git a/Lang/C/The-Twelve-Days-of-Christmas b/Lang/C/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..fee4d66c5a --- /dev/null +++ b/Lang/C/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/C \ No newline at end of file diff --git a/Lang/C/Total-circles-area b/Lang/C/Total-circles-area new file mode 120000 index 0000000000..fa02f5bd82 --- /dev/null +++ b/Lang/C/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/C \ No newline at end of file diff --git a/Lang/C/Ulam-spiral--for-primes- b/Lang/C/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..e32f1e23b8 --- /dev/null +++ b/Lang/C/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/C \ No newline at end of file diff --git a/Lang/C/Unix-ls b/Lang/C/Unix-ls new file mode 120000 index 0000000000..81aa214ede --- /dev/null +++ b/Lang/C/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/C \ No newline at end of file diff --git a/Lang/C/Zero-to-the-zero-power b/Lang/C/Zero-to-the-zero-power new file mode 120000 index 0000000000..e13ecdf6c3 --- /dev/null +++ b/Lang/C/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/C \ No newline at end of file diff --git a/Lang/COBOL/Comma-quibbling b/Lang/COBOL/Comma-quibbling new file mode 120000 index 0000000000..71ea96f472 --- /dev/null +++ b/Lang/COBOL/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/COBOL \ No newline at end of file diff --git a/Lang/COBOL/File-input-output b/Lang/COBOL/File-input-output new file mode 120000 index 0000000000..943a9a917e --- /dev/null +++ b/Lang/COBOL/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Hello-world-Newbie b/Lang/COBOL/Hello-world-Newbie new file mode 120000 index 0000000000..0d2ec06a7a --- /dev/null +++ b/Lang/COBOL/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Hickerson-series-of-almost-integers b/Lang/COBOL/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..a336d6d21d --- /dev/null +++ b/Lang/COBOL/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/IBAN b/Lang/COBOL/IBAN new file mode 120000 index 0000000000..0692dbeedf --- /dev/null +++ b/Lang/COBOL/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Quickselect-algorithm b/Lang/COBOL/Quickselect-algorithm new file mode 120000 index 0000000000..228f991314 --- /dev/null +++ b/Lang/COBOL/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-prepend b/Lang/COBOL/String-prepend new file mode 120000 index 0000000000..6f5995c9f0 --- /dev/null +++ b/Lang/COBOL/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sum-multiples-of-3-and-5 b/Lang/COBOL/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..b959929db1 --- /dev/null +++ b/Lang/COBOL/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/COBOL \ No newline at end of file diff --git a/Lang/COBOL/The-Twelve-Days-of-Christmas b/Lang/COBOL/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..3662be5f3e --- /dev/null +++ b/Lang/COBOL/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/IBAN b/Lang/Cache-ObjectScript/IBAN new file mode 120000 index 0000000000..86ea2b63f6 --- /dev/null +++ b/Lang/Cache-ObjectScript/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Clean/File-input-output b/Lang/Clean/File-input-output new file mode 120000 index 0000000000..21d2cb4370 --- /dev/null +++ b/Lang/Clean/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Clean \ No newline at end of file diff --git a/Lang/Clojure/ABC-Problem b/Lang/Clojure/ABC-Problem new file mode 120000 index 0000000000..8b3d5c086b --- /dev/null +++ b/Lang/Clojure/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Clojure \ No newline at end of file diff --git a/Lang/Clojure/AKS-test-for-primes b/Lang/Clojure/AKS-test-for-primes new file mode 120000 index 0000000000..5c2026efc1 --- /dev/null +++ b/Lang/Clojure/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Amb b/Lang/Clojure/Amb new file mode 120000 index 0000000000..c159dca623 --- /dev/null +++ b/Lang/Clojure/Amb @@ -0,0 +1 @@ +../../Task/Amb/Clojure \ No newline at end of file diff --git a/Lang/Clojure/CSV-data-manipulation b/Lang/Clojure/CSV-data-manipulation new file mode 120000 index 0000000000..2b75ea9b07 --- /dev/null +++ b/Lang/Clojure/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Catamorphism b/Lang/Clojure/Catamorphism new file mode 120000 index 0000000000..309b700f51 --- /dev/null +++ b/Lang/Clojure/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Comma-quibbling b/Lang/Clojure/Comma-quibbling new file mode 120000 index 0000000000..aec5efba2b --- /dev/null +++ b/Lang/Clojure/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Fibonacci-word b/Lang/Clojure/Fibonacci-word new file mode 120000 index 0000000000..91ec300cb3 --- /dev/null +++ b/Lang/Clojure/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Clojure \ No newline at end of file diff --git a/Lang/Clojure/File-input-output b/Lang/Clojure/File-input-output new file mode 120000 index 0000000000..2abdf2f207 --- /dev/null +++ b/Lang/Clojure/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Find-the-last-Sunday-of-each-month b/Lang/Clojure/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..c8678082b4 --- /dev/null +++ b/Lang/Clojure/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Generate-lower-case-ASCII-alphabet b/Lang/Clojure/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..81bcd65dce --- /dev/null +++ b/Lang/Clojure/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hash-join b/Lang/Clojure/Hash-join new file mode 120000 index 0000000000..9751447898 --- /dev/null +++ b/Lang/Clojure/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hello-world-Newbie b/Lang/Clojure/Hello-world-Newbie new file mode 120000 index 0000000000..2dca9a3077 --- /dev/null +++ b/Lang/Clojure/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hickerson-series-of-almost-integers b/Lang/Clojure/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..273239974b --- /dev/null +++ b/Lang/Clojure/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Clojure \ No newline at end of file diff --git a/Lang/Clojure/IBAN b/Lang/Clojure/IBAN new file mode 120000 index 0000000000..e9760937bd --- /dev/null +++ b/Lang/Clojure/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Integer-overflow b/Lang/Clojure/Integer-overflow new file mode 120000 index 0000000000..bb4519ae4e --- /dev/null +++ b/Lang/Clojure/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Longest-increasing-subsequence b/Lang/Clojure/Longest-increasing-subsequence new file mode 120000 index 0000000000..11e642d5ce --- /dev/null +++ b/Lang/Clojure/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Ludic-numbers b/Lang/Clojure/Ludic-numbers new file mode 120000 index 0000000000..da0ead2439 --- /dev/null +++ b/Lang/Clojure/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Make-directory-path b/Lang/Clojure/Make-directory-path new file mode 120000 index 0000000000..f2e8f9233d --- /dev/null +++ b/Lang/Clojure/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Nth b/Lang/Clojure/Nth new file mode 120000 index 0000000000..22632912c6 --- /dev/null +++ b/Lang/Clojure/Nth @@ -0,0 +1 @@ +../../Task/Nth/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Odd-word-problem b/Lang/Clojure/Odd-word-problem new file mode 120000 index 0000000000..ac88ba5f7c --- /dev/null +++ b/Lang/Clojure/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Reverse-words-in-a-string b/Lang/Clojure/Reverse-words-in-a-string new file mode 120000 index 0000000000..4dd7ad1cfd --- /dev/null +++ b/Lang/Clojure/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Stern-Brocot-sequence b/Lang/Clojure/Stern-Brocot-sequence new file mode 120000 index 0000000000..15cf379504 --- /dev/null +++ b/Lang/Clojure/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-append b/Lang/Clojure/String-append new file mode 120000 index 0000000000..d4249298fd --- /dev/null +++ b/Lang/Clojure/String-append @@ -0,0 +1 @@ +../../Task/String-append/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-matching b/Lang/Clojure/String-matching new file mode 120000 index 0000000000..2a22f9aa6c --- /dev/null +++ b/Lang/Clojure/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-prepend b/Lang/Clojure/String-prepend new file mode 120000 index 0000000000..1a8f195e37 --- /dev/null +++ b/Lang/Clojure/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sum-multiples-of-3-and-5 b/Lang/Clojure/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..41655e0d3a --- /dev/null +++ b/Lang/Clojure/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Clojure \ No newline at end of file diff --git a/Lang/Clojure/The-Twelve-Days-of-Christmas b/Lang/Clojure/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..436b3a33c9 --- /dev/null +++ b/Lang/Clojure/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Unix-ls b/Lang/Clojure/Unix-ls new file mode 120000 index 0000000000..d7fd28353d --- /dev/null +++ b/Lang/Clojure/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/ABC-Problem b/Lang/CoffeeScript/ABC-Problem new file mode 120000 index 0000000000..02106bee9d --- /dev/null +++ b/Lang/CoffeeScript/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/AKS-test-for-primes b/Lang/CoffeeScript/AKS-test-for-primes new file mode 120000 index 0000000000..4a31748ede --- /dev/null +++ b/Lang/CoffeeScript/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Benfords-law b/Lang/CoffeeScript/Benfords-law new file mode 120000 index 0000000000..3e774dc075 --- /dev/null +++ b/Lang/CoffeeScript/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Closures-Value-capture b/Lang/CoffeeScript/Closures-Value-capture new file mode 120000 index 0000000000..50d43c1d3f --- /dev/null +++ b/Lang/CoffeeScript/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Comma-quibbling b/Lang/CoffeeScript/Comma-quibbling new file mode 120000 index 0000000000..d38b89d7b3 --- /dev/null +++ b/Lang/CoffeeScript/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Odd-word-problem b/Lang/CoffeeScript/Odd-word-problem new file mode 120000 index 0000000000..08f6d764cf --- /dev/null +++ b/Lang/CoffeeScript/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Statistics-Basic b/Lang/CoffeeScript/Statistics-Basic new file mode 120000 index 0000000000..f50b0bf330 --- /dev/null +++ b/Lang/CoffeeScript/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/String-matching b/Lang/CoffeeScript/String-matching new file mode 120000 index 0000000000..cb18c022d5 --- /dev/null +++ b/Lang/CoffeeScript/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/File-input-output b/Lang/ColdFusion/File-input-output new file mode 120000 index 0000000000..a9015534b0 --- /dev/null +++ b/Lang/ColdFusion/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/ColdFusion \ No newline at end of file diff --git a/Lang/Common-Lisp/9-billion-names-of-God-the-integer b/Lang/Common-Lisp/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..b07768de38 --- /dev/null +++ b/Lang/Common-Lisp/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/ABC-Problem b/Lang/Common-Lisp/ABC-Problem new file mode 120000 index 0000000000..1724857c12 --- /dev/null +++ b/Lang/Common-Lisp/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/AKS-test-for-primes b/Lang/Common-Lisp/AKS-test-for-primes new file mode 120000 index 0000000000..605534b17a --- /dev/null +++ b/Lang/Common-Lisp/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Almost-prime b/Lang/Common-Lisp/Almost-prime new file mode 120000 index 0000000000..8f05ddb60b --- /dev/null +++ b/Lang/Common-Lisp/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Amb b/Lang/Common-Lisp/Amb new file mode 120000 index 0000000000..1c503cd1f4 --- /dev/null +++ b/Lang/Common-Lisp/Amb @@ -0,0 +1 @@ +../../Task/Amb/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Benfords-law b/Lang/Common-Lisp/Benfords-law new file mode 120000 index 0000000000..621344e960 --- /dev/null +++ b/Lang/Common-Lisp/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Bernoulli-numbers b/Lang/Common-Lisp/Bernoulli-numbers new file mode 120000 index 0000000000..9cb84b9767 --- /dev/null +++ b/Lang/Common-Lisp/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/CSV-data-manipulation b/Lang/Common-Lisp/CSV-data-manipulation new file mode 120000 index 0000000000..4695fc224d --- /dev/null +++ b/Lang/Common-Lisp/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Casting-out-nines b/Lang/Common-Lisp/Casting-out-nines new file mode 120000 index 0000000000..f338a94326 --- /dev/null +++ b/Lang/Common-Lisp/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Catamorphism b/Lang/Common-Lisp/Catamorphism new file mode 120000 index 0000000000..43b68535a3 --- /dev/null +++ b/Lang/Common-Lisp/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Chinese-remainder-theorem b/Lang/Common-Lisp/Chinese-remainder-theorem new file mode 120000 index 0000000000..0ad124e1c2 --- /dev/null +++ b/Lang/Common-Lisp/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Closures-Value-capture b/Lang/Common-Lisp/Closures-Value-capture new file mode 120000 index 0000000000..3becd0b4ad --- /dev/null +++ b/Lang/Common-Lisp/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Comma-quibbling b/Lang/Common-Lisp/Comma-quibbling new file mode 120000 index 0000000000..916b4462a2 --- /dev/null +++ b/Lang/Common-Lisp/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Currying b/Lang/Common-Lisp/Currying new file mode 120000 index 0000000000..286ea864b6 --- /dev/null +++ b/Lang/Common-Lisp/Currying @@ -0,0 +1 @@ +../../Task/Currying/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Digital-root-Multiplicative-digital-root b/Lang/Common-Lisp/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..b00a7061ef --- /dev/null +++ b/Lang/Common-Lisp/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/File-input-output b/Lang/Common-Lisp/File-input-output new file mode 120000 index 0000000000..ca8005464d --- /dev/null +++ b/Lang/Common-Lisp/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Fractran b/Lang/Common-Lisp/Fractran new file mode 120000 index 0000000000..3342a4c852 --- /dev/null +++ b/Lang/Common-Lisp/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Generate-lower-case-ASCII-alphabet b/Lang/Common-Lisp/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..2f35fd2be5 --- /dev/null +++ b/Lang/Common-Lisp/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Hash-join b/Lang/Common-Lisp/Hash-join new file mode 120000 index 0000000000..ce7e920ed8 --- /dev/null +++ b/Lang/Common-Lisp/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/IBAN b/Lang/Common-Lisp/IBAN new file mode 120000 index 0000000000..c69e3a3e8f --- /dev/null +++ b/Lang/Common-Lisp/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Longest-increasing-subsequence b/Lang/Common-Lisp/Longest-increasing-subsequence new file mode 120000 index 0000000000..e9723c1815 --- /dev/null +++ b/Lang/Common-Lisp/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Machine-code b/Lang/Common-Lisp/Machine-code new file mode 120000 index 0000000000..4c3c816632 --- /dev/null +++ b/Lang/Common-Lisp/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Magic-squares-of-odd-order b/Lang/Common-Lisp/Magic-squares-of-odd-order new file mode 120000 index 0000000000..982636b03a --- /dev/null +++ b/Lang/Common-Lisp/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Maximum-triangle-path-sum b/Lang/Common-Lisp/Maximum-triangle-path-sum new file mode 120000 index 0000000000..72210126d6 --- /dev/null +++ b/Lang/Common-Lisp/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Move-to-front-algorithm b/Lang/Common-Lisp/Move-to-front-algorithm new file mode 120000 index 0000000000..32e22545a7 --- /dev/null +++ b/Lang/Common-Lisp/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Narcissistic-decimal-number b/Lang/Common-Lisp/Narcissistic-decimal-number new file mode 120000 index 0000000000..b47feb173b --- /dev/null +++ b/Lang/Common-Lisp/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Nth b/Lang/Common-Lisp/Nth new file mode 120000 index 0000000000..769a5d85b6 --- /dev/null +++ b/Lang/Common-Lisp/Nth @@ -0,0 +1 @@ +../../Task/Nth/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Odd-word-problem b/Lang/Common-Lisp/Odd-word-problem new file mode 120000 index 0000000000..8a874c8cce --- /dev/null +++ b/Lang/Common-Lisp/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Pernicious-numbers b/Lang/Common-Lisp/Pernicious-numbers new file mode 120000 index 0000000000..eefa41cdb9 --- /dev/null +++ b/Lang/Common-Lisp/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/RSA-code b/Lang/Common-Lisp/RSA-code new file mode 120000 index 0000000000..2d8077b2f7 --- /dev/null +++ b/Lang/Common-Lisp/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Reverse-words-in-a-string b/Lang/Common-Lisp/Reverse-words-in-a-string new file mode 120000 index 0000000000..bb2b455639 --- /dev/null +++ b/Lang/Common-Lisp/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Semiprime b/Lang/Common-Lisp/Semiprime new file mode 120000 index 0000000000..07dbef9d4d --- /dev/null +++ b/Lang/Common-Lisp/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-append b/Lang/Common-Lisp/String-append new file mode 120000 index 0000000000..a6f646b9c2 --- /dev/null +++ b/Lang/Common-Lisp/String-append @@ -0,0 +1 @@ +../../Task/String-append/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-matching b/Lang/Common-Lisp/String-matching new file mode 120000 index 0000000000..1ff51c4e63 --- /dev/null +++ b/Lang/Common-Lisp/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-prepend b/Lang/Common-Lisp/String-prepend new file mode 120000 index 0000000000..d973b94bdd --- /dev/null +++ b/Lang/Common-Lisp/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sum-multiples-of-3-and-5 b/Lang/Common-Lisp/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..92e11c6d9e --- /dev/null +++ b/Lang/Common-Lisp/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/String-matching b/Lang/Component-Pascal/String-matching new file mode 120000 index 0000000000..c14798f06f --- /dev/null +++ b/Lang/Component-Pascal/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Sum-multiples-of-3-and-5 b/Lang/Component-Pascal/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..e5fe012275 --- /dev/null +++ b/Lang/Component-Pascal/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Component-Pascal \ No newline at end of file diff --git a/Lang/D/9-billion-names-of-God-the-integer b/Lang/D/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..1eefd05c98 --- /dev/null +++ b/Lang/D/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/D \ No newline at end of file diff --git a/Lang/D/ABC-Problem b/Lang/D/ABC-Problem new file mode 120000 index 0000000000..7ed32356bd --- /dev/null +++ b/Lang/D/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/D \ No newline at end of file diff --git a/Lang/D/AKS-test-for-primes b/Lang/D/AKS-test-for-primes new file mode 120000 index 0000000000..37918836f8 --- /dev/null +++ b/Lang/D/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/D \ No newline at end of file diff --git a/Lang/D/Abundant,-deficient-and-perfect-number-classifications b/Lang/D/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..f73782ef9d --- /dev/null +++ b/Lang/D/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/D \ No newline at end of file diff --git a/Lang/D/Aliquot-sequence-classifications b/Lang/D/Aliquot-sequence-classifications new file mode 120000 index 0000000000..181ccff518 --- /dev/null +++ b/Lang/D/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/D \ No newline at end of file diff --git a/Lang/D/Almost-prime b/Lang/D/Almost-prime new file mode 120000 index 0000000000..577d8ac8c7 --- /dev/null +++ b/Lang/D/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/D \ No newline at end of file diff --git a/Lang/D/Amb b/Lang/D/Amb new file mode 120000 index 0000000000..ab35b0424e --- /dev/null +++ b/Lang/D/Amb @@ -0,0 +1 @@ +../../Task/Amb/D \ No newline at end of file diff --git a/Lang/D/Amicable-pairs b/Lang/D/Amicable-pairs new file mode 120000 index 0000000000..96082c090d --- /dev/null +++ b/Lang/D/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/D \ No newline at end of file diff --git a/Lang/D/Benfords-law b/Lang/D/Benfords-law new file mode 120000 index 0000000000..d5c7560b7b --- /dev/null +++ b/Lang/D/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/D \ No newline at end of file diff --git a/Lang/D/Bernoulli-numbers b/Lang/D/Bernoulli-numbers new file mode 120000 index 0000000000..384c621c0c --- /dev/null +++ b/Lang/D/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/D \ No newline at end of file diff --git a/Lang/D/Bitcoin-public-point-to-address b/Lang/D/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..81a4ae4d4c --- /dev/null +++ b/Lang/D/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/D \ No newline at end of file diff --git a/Lang/D/CSV-data-manipulation b/Lang/D/CSV-data-manipulation new file mode 120000 index 0000000000..df74dee649 --- /dev/null +++ b/Lang/D/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/D \ No newline at end of file diff --git a/Lang/D/Calendar---for-REAL-programmers b/Lang/D/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..ce8404ef14 --- /dev/null +++ b/Lang/D/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/D \ No newline at end of file diff --git a/Lang/D/Casting-out-nines b/Lang/D/Casting-out-nines new file mode 120000 index 0000000000..7a13f6b17a --- /dev/null +++ b/Lang/D/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/D \ No newline at end of file diff --git a/Lang/D/Catalan-numbers-Pascals-triangle b/Lang/D/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..1e13e60dc9 --- /dev/null +++ b/Lang/D/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/D \ No newline at end of file diff --git a/Lang/D/Catamorphism b/Lang/D/Catamorphism new file mode 120000 index 0000000000..107c6c1a86 --- /dev/null +++ b/Lang/D/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/D \ No newline at end of file diff --git a/Lang/D/Chinese-remainder-theorem b/Lang/D/Chinese-remainder-theorem new file mode 120000 index 0000000000..66a84e8e2e --- /dev/null +++ b/Lang/D/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/D \ No newline at end of file diff --git a/Lang/D/Circles-of-given-radius-through-two-points b/Lang/D/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..3676afbec6 --- /dev/null +++ b/Lang/D/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/D \ No newline at end of file diff --git a/Lang/D/Closures-Value-capture b/Lang/D/Closures-Value-capture new file mode 120000 index 0000000000..35a32caf08 --- /dev/null +++ b/Lang/D/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/D \ No newline at end of file diff --git a/Lang/D/Combinations-and-permutations b/Lang/D/Combinations-and-permutations new file mode 120000 index 0000000000..6c2439051e --- /dev/null +++ b/Lang/D/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/D \ No newline at end of file diff --git a/Lang/D/Comma-quibbling b/Lang/D/Comma-quibbling new file mode 120000 index 0000000000..794b4349e0 --- /dev/null +++ b/Lang/D/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/D \ No newline at end of file diff --git a/Lang/D/Conjugate-transpose b/Lang/D/Conjugate-transpose new file mode 120000 index 0000000000..a42441a64a --- /dev/null +++ b/Lang/D/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/D \ No newline at end of file diff --git a/Lang/D/Convert-decimal-number-to-rational b/Lang/D/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..e2e769f0ec --- /dev/null +++ b/Lang/D/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/D \ No newline at end of file diff --git a/Lang/D/Currying b/Lang/D/Currying new file mode 120000 index 0000000000..ad8df76b72 --- /dev/null +++ b/Lang/D/Currying @@ -0,0 +1 @@ +../../Task/Currying/D \ No newline at end of file diff --git a/Lang/D/Digital-root-Multiplicative-digital-root b/Lang/D/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..2437b7abef --- /dev/null +++ b/Lang/D/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/D \ No newline at end of file diff --git a/Lang/D/Extensible-prime-generator b/Lang/D/Extensible-prime-generator new file mode 120000 index 0000000000..10d2352cce --- /dev/null +++ b/Lang/D/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/D \ No newline at end of file diff --git a/Lang/D/Fibonacci-word b/Lang/D/Fibonacci-word new file mode 120000 index 0000000000..076d29a63f --- /dev/null +++ b/Lang/D/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/D \ No newline at end of file diff --git a/Lang/D/Fibonacci-word-fractal b/Lang/D/Fibonacci-word-fractal new file mode 120000 index 0000000000..f8cf77d0f6 --- /dev/null +++ b/Lang/D/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/D \ No newline at end of file diff --git a/Lang/D/File-input-output b/Lang/D/File-input-output new file mode 120000 index 0000000000..0c6237b89b --- /dev/null +++ b/Lang/D/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/D \ No newline at end of file diff --git a/Lang/D/Find-the-last-Sunday-of-each-month b/Lang/D/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..ba36aca845 --- /dev/null +++ b/Lang/D/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/D \ No newline at end of file diff --git a/Lang/D/Flipping-bits-game b/Lang/D/Flipping-bits-game new file mode 120000 index 0000000000..4bd85468d3 --- /dev/null +++ b/Lang/D/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/D \ No newline at end of file diff --git a/Lang/D/Fractran b/Lang/D/Fractran new file mode 120000 index 0000000000..97d633be71 --- /dev/null +++ b/Lang/D/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/D \ No newline at end of file diff --git a/Lang/D/Gaussian-elimination b/Lang/D/Gaussian-elimination new file mode 120000 index 0000000000..9751546a3b --- /dev/null +++ b/Lang/D/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/D \ No newline at end of file diff --git a/Lang/D/Generate-Chess960-starting-position b/Lang/D/Generate-Chess960-starting-position new file mode 120000 index 0000000000..8e34cba9e3 --- /dev/null +++ b/Lang/D/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/D \ No newline at end of file diff --git a/Lang/D/Generate-lower-case-ASCII-alphabet b/Lang/D/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d7c5fe9808 --- /dev/null +++ b/Lang/D/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/D \ No newline at end of file diff --git a/Lang/D/Hash-join b/Lang/D/Hash-join new file mode 120000 index 0000000000..cab729d5f2 --- /dev/null +++ b/Lang/D/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/D \ No newline at end of file diff --git a/Lang/D/Hello-world-Newbie b/Lang/D/Hello-world-Newbie new file mode 120000 index 0000000000..bb84052e6a --- /dev/null +++ b/Lang/D/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/D \ No newline at end of file diff --git a/Lang/D/Heronian-triangles b/Lang/D/Heronian-triangles new file mode 120000 index 0000000000..2b0976326c --- /dev/null +++ b/Lang/D/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/D \ No newline at end of file diff --git a/Lang/D/Hickerson-series-of-almost-integers b/Lang/D/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..c42872a6a9 --- /dev/null +++ b/Lang/D/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/D \ No newline at end of file diff --git a/Lang/D/IBAN b/Lang/D/IBAN new file mode 120000 index 0000000000..b043863505 --- /dev/null +++ b/Lang/D/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/D \ No newline at end of file diff --git a/Lang/D/Integer-overflow b/Lang/D/Integer-overflow new file mode 120000 index 0000000000..055c493755 --- /dev/null +++ b/Lang/D/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/D \ No newline at end of file diff --git a/Lang/D/Iterated-digits-squaring b/Lang/D/Iterated-digits-squaring new file mode 120000 index 0000000000..0bed83e462 --- /dev/null +++ b/Lang/D/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/D \ No newline at end of file diff --git a/Lang/D/K-d-tree b/Lang/D/K-d-tree new file mode 120000 index 0000000000..5e35282454 --- /dev/null +++ b/Lang/D/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/D \ No newline at end of file diff --git a/Lang/D/Left-factorials b/Lang/D/Left-factorials new file mode 120000 index 0000000000..f03f0e32fa --- /dev/null +++ b/Lang/D/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/D \ No newline at end of file diff --git a/Lang/D/Longest-increasing-subsequence b/Lang/D/Longest-increasing-subsequence new file mode 120000 index 0000000000..4a5dc99a88 --- /dev/null +++ b/Lang/D/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/D \ No newline at end of file diff --git a/Lang/D/Ludic-numbers b/Lang/D/Ludic-numbers new file mode 120000 index 0000000000..9e835c184e --- /dev/null +++ b/Lang/D/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/D \ No newline at end of file diff --git a/Lang/D/Machine-code b/Lang/D/Machine-code new file mode 120000 index 0000000000..3fc46ca634 --- /dev/null +++ b/Lang/D/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/D \ No newline at end of file diff --git a/Lang/D/Magic-squares-of-odd-order b/Lang/D/Magic-squares-of-odd-order new file mode 120000 index 0000000000..6a63554a40 --- /dev/null +++ b/Lang/D/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/D \ No newline at end of file diff --git a/Lang/D/Maximum-triangle-path-sum b/Lang/D/Maximum-triangle-path-sum new file mode 120000 index 0000000000..f2bdc7305b --- /dev/null +++ b/Lang/D/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/D \ No newline at end of file diff --git a/Lang/D/Move-to-front-algorithm b/Lang/D/Move-to-front-algorithm new file mode 120000 index 0000000000..a31ecf0e72 --- /dev/null +++ b/Lang/D/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/D \ No newline at end of file diff --git a/Lang/D/Munching-squares b/Lang/D/Munching-squares new file mode 120000 index 0000000000..b5a7fb5141 --- /dev/null +++ b/Lang/D/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/D \ No newline at end of file diff --git a/Lang/D/Narcissistic-decimal-number b/Lang/D/Narcissistic-decimal-number new file mode 120000 index 0000000000..fcd7b1b465 --- /dev/null +++ b/Lang/D/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/D \ No newline at end of file diff --git a/Lang/D/Natural-sorting b/Lang/D/Natural-sorting new file mode 120000 index 0000000000..e02279d6a1 --- /dev/null +++ b/Lang/D/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/D \ No newline at end of file diff --git a/Lang/D/Nth b/Lang/D/Nth new file mode 120000 index 0000000000..fb460b8553 --- /dev/null +++ b/Lang/D/Nth @@ -0,0 +1 @@ +../../Task/Nth/D \ No newline at end of file diff --git a/Lang/D/Odd-word-problem b/Lang/D/Odd-word-problem new file mode 120000 index 0000000000..ed7bc90fbe --- /dev/null +++ b/Lang/D/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/D \ No newline at end of file diff --git a/Lang/D/Old-lady-swallowed-a-fly b/Lang/D/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..55ae2ede92 --- /dev/null +++ b/Lang/D/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/D \ No newline at end of file diff --git a/Lang/D/Order-disjoint-list-items b/Lang/D/Order-disjoint-list-items new file mode 120000 index 0000000000..c0d76b707b --- /dev/null +++ b/Lang/D/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/D \ No newline at end of file diff --git a/Lang/D/Paraffins b/Lang/D/Paraffins new file mode 120000 index 0000000000..8d199f5710 --- /dev/null +++ b/Lang/D/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/D \ No newline at end of file diff --git a/Lang/D/Penneys-game b/Lang/D/Penneys-game new file mode 120000 index 0000000000..8382742f91 --- /dev/null +++ b/Lang/D/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/D \ No newline at end of file diff --git a/Lang/D/Percolation-Bond-percolation b/Lang/D/Percolation-Bond-percolation new file mode 120000 index 0000000000..e6a1091c90 --- /dev/null +++ b/Lang/D/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/D \ No newline at end of file diff --git a/Lang/D/Percolation-Mean-cluster-density b/Lang/D/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..2049e933f3 --- /dev/null +++ b/Lang/D/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/D \ No newline at end of file diff --git a/Lang/D/Percolation-Mean-run-density b/Lang/D/Percolation-Mean-run-density new file mode 120000 index 0000000000..ecafbdbd0a --- /dev/null +++ b/Lang/D/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/D \ No newline at end of file diff --git a/Lang/D/Percolation-Site-percolation b/Lang/D/Percolation-Site-percolation new file mode 120000 index 0000000000..981ee0378a --- /dev/null +++ b/Lang/D/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/D \ No newline at end of file diff --git a/Lang/D/Permutations-Rank-of-a-permutation b/Lang/D/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..1496e01d87 --- /dev/null +++ b/Lang/D/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/D \ No newline at end of file diff --git a/Lang/D/Pernicious-numbers b/Lang/D/Pernicious-numbers new file mode 120000 index 0000000000..b244ea525d --- /dev/null +++ b/Lang/D/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/D \ No newline at end of file diff --git a/Lang/D/Phrase-reversals b/Lang/D/Phrase-reversals new file mode 120000 index 0000000000..dd7ee84b02 --- /dev/null +++ b/Lang/D/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/D \ No newline at end of file diff --git a/Lang/D/Quickselect-algorithm b/Lang/D/Quickselect-algorithm new file mode 120000 index 0000000000..92b3b1ff83 --- /dev/null +++ b/Lang/D/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/D \ No newline at end of file diff --git a/Lang/D/RSA-code b/Lang/D/RSA-code new file mode 120000 index 0000000000..e401b73209 --- /dev/null +++ b/Lang/D/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/D \ No newline at end of file diff --git a/Lang/D/Rep-string b/Lang/D/Rep-string new file mode 120000 index 0000000000..83b5547319 --- /dev/null +++ b/Lang/D/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/D \ No newline at end of file diff --git a/Lang/D/Reverse-words-in-a-string b/Lang/D/Reverse-words-in-a-string new file mode 120000 index 0000000000..359e7227bf --- /dev/null +++ b/Lang/D/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/D \ No newline at end of file diff --git a/Lang/D/Runge-Kutta-method b/Lang/D/Runge-Kutta-method new file mode 120000 index 0000000000..690e6e3f17 --- /dev/null +++ b/Lang/D/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/D \ No newline at end of file diff --git a/Lang/D/Semiprime b/Lang/D/Semiprime new file mode 120000 index 0000000000..6aac10b5e5 --- /dev/null +++ b/Lang/D/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/D \ No newline at end of file diff --git a/Lang/D/Sequence-of-primes-by-Trial-Division b/Lang/D/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..85dabd19f5 --- /dev/null +++ b/Lang/D/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/D \ No newline at end of file diff --git a/Lang/D/Solve-a-Holy-Knights-tour b/Lang/D/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..4bb9116dec --- /dev/null +++ b/Lang/D/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/D \ No newline at end of file diff --git a/Lang/D/Solve-a-Hopido-puzzle b/Lang/D/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..da7ea028ab --- /dev/null +++ b/Lang/D/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/D \ No newline at end of file diff --git a/Lang/D/Solve-a-Numbrix-puzzle b/Lang/D/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..f4ab63037c --- /dev/null +++ b/Lang/D/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/D \ No newline at end of file diff --git a/Lang/D/Solve-the-no-connection-puzzle b/Lang/D/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d52e668496 --- /dev/null +++ b/Lang/D/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/D \ No newline at end of file diff --git a/Lang/D/Sparkline-in-unicode b/Lang/D/Sparkline-in-unicode new file mode 120000 index 0000000000..889eafb723 --- /dev/null +++ b/Lang/D/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/D \ No newline at end of file diff --git a/Lang/D/State-name-puzzle b/Lang/D/State-name-puzzle new file mode 120000 index 0000000000..c47ddcfb5a --- /dev/null +++ b/Lang/D/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/D \ No newline at end of file diff --git a/Lang/D/Statistics-Basic b/Lang/D/Statistics-Basic new file mode 120000 index 0000000000..e3908039aa --- /dev/null +++ b/Lang/D/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/D \ No newline at end of file diff --git a/Lang/D/Stern-Brocot-sequence b/Lang/D/Stern-Brocot-sequence new file mode 120000 index 0000000000..1b3a5e1ec9 --- /dev/null +++ b/Lang/D/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/D \ No newline at end of file diff --git a/Lang/D/String-append b/Lang/D/String-append new file mode 120000 index 0000000000..b5887faab7 --- /dev/null +++ b/Lang/D/String-append @@ -0,0 +1 @@ +../../Task/String-append/D \ No newline at end of file diff --git a/Lang/D/String-matching b/Lang/D/String-matching new file mode 120000 index 0000000000..752859736a --- /dev/null +++ b/Lang/D/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/D \ No newline at end of file diff --git a/Lang/D/String-prepend b/Lang/D/String-prepend new file mode 120000 index 0000000000..5f149627e7 --- /dev/null +++ b/Lang/D/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/D \ No newline at end of file diff --git a/Lang/D/Sum-multiples-of-3-and-5 b/Lang/D/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..a08348de6d --- /dev/null +++ b/Lang/D/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/D \ No newline at end of file diff --git a/Lang/D/The-ISAAC-Cipher b/Lang/D/The-ISAAC-Cipher new file mode 120000 index 0000000000..b8042642de --- /dev/null +++ b/Lang/D/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/D \ No newline at end of file diff --git a/Lang/D/The-Twelve-Days-of-Christmas b/Lang/D/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..409957da26 --- /dev/null +++ b/Lang/D/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/D \ No newline at end of file diff --git a/Lang/D/Total-circles-area b/Lang/D/Total-circles-area new file mode 120000 index 0000000000..30aaf31490 --- /dev/null +++ b/Lang/D/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/D \ No newline at end of file diff --git a/Lang/D/Ulam-spiral--for-primes- b/Lang/D/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..edb38271b6 --- /dev/null +++ b/Lang/D/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/D \ No newline at end of file diff --git a/Lang/D/Unix-ls b/Lang/D/Unix-ls new file mode 120000 index 0000000000..d866d79535 --- /dev/null +++ b/Lang/D/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/D \ No newline at end of file diff --git a/Lang/D/Vogels-approximation-method b/Lang/D/Vogels-approximation-method new file mode 120000 index 0000000000..a5a274e598 --- /dev/null +++ b/Lang/D/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/D \ No newline at end of file diff --git a/Lang/D/World-Cup-group-stage b/Lang/D/World-Cup-group-stage new file mode 120000 index 0000000000..8ecdfbe671 --- /dev/null +++ b/Lang/D/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/D \ No newline at end of file diff --git a/Lang/D/Zero-to-the-zero-power b/Lang/D/Zero-to-the-zero-power new file mode 120000 index 0000000000..a8509a72b1 --- /dev/null +++ b/Lang/D/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/D \ No newline at end of file diff --git a/Lang/D/Zhang-Suen-thinning-algorithm b/Lang/D/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..aeb869241c --- /dev/null +++ b/Lang/D/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/D \ No newline at end of file diff --git a/Lang/Dart/Runge-Kutta-method b/Lang/Dart/Runge-Kutta-method new file mode 120000 index 0000000000..1601ddcfd3 --- /dev/null +++ b/Lang/Dart/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Dart \ No newline at end of file diff --git a/Lang/Dart/Statistics-Basic b/Lang/Dart/Statistics-Basic new file mode 120000 index 0000000000..9af73ebc81 --- /dev/null +++ b/Lang/Dart/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Dart \ No newline at end of file diff --git a/Lang/Deja-Vu/Catamorphism b/Lang/Deja-Vu/Catamorphism new file mode 120000 index 0000000000..0a664c6e22 --- /dev/null +++ b/Lang/Deja-Vu/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Comma-quibbling b/Lang/Deja-Vu/Comma-quibbling new file mode 120000 index 0000000000..cc853c2631 --- /dev/null +++ b/Lang/Deja-Vu/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Hash-join b/Lang/Deja-Vu/Hash-join new file mode 120000 index 0000000000..44294a2d73 --- /dev/null +++ b/Lang/Deja-Vu/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Longest-increasing-subsequence b/Lang/Deja-Vu/Longest-increasing-subsequence new file mode 120000 index 0000000000..97e27bf03b --- /dev/null +++ b/Lang/Deja-Vu/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/String-prepend b/Lang/Deja-Vu/String-prepend new file mode 120000 index 0000000000..b51b6fb6e0 --- /dev/null +++ b/Lang/Deja-Vu/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Sum-multiples-of-3-and-5 b/Lang/Deja-Vu/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..c55f45044b --- /dev/null +++ b/Lang/Deja-Vu/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Deja-Vu \ No newline at end of file diff --git a/Lang/Delphi/ABC-Problem b/Lang/Delphi/ABC-Problem new file mode 120000 index 0000000000..d0567899ed --- /dev/null +++ b/Lang/Delphi/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Closures-Value-capture b/Lang/Delphi/Closures-Value-capture new file mode 120000 index 0000000000..488335ba32 --- /dev/null +++ b/Lang/Delphi/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Delphi \ No newline at end of file diff --git a/Lang/Delphi/File-input-output b/Lang/Delphi/File-input-output new file mode 120000 index 0000000000..355f8c3738 --- /dev/null +++ b/Lang/Delphi/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Generate-lower-case-ASCII-alphabet b/Lang/Delphi/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b14f1a9128 --- /dev/null +++ b/Lang/Delphi/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Delphi \ No newline at end of file diff --git a/Lang/Delphi/String-matching b/Lang/Delphi/String-matching new file mode 120000 index 0000000000..f3cbd84bd6 --- /dev/null +++ b/Lang/Delphi/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sum-multiples-of-3-and-5 b/Lang/Delphi/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..f3c83a9e0a --- /dev/null +++ b/Lang/Delphi/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Delphi \ No newline at end of file diff --git a/Lang/Delphi/The-ISAAC-Cipher b/Lang/Delphi/The-ISAAC-Cipher new file mode 120000 index 0000000000..c4a675db91 --- /dev/null +++ b/Lang/Delphi/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Delphi \ No newline at end of file diff --git a/Lang/E/Amb b/Lang/E/Amb new file mode 120000 index 0000000000..c7ff8bef1d --- /dev/null +++ b/Lang/E/Amb @@ -0,0 +1 @@ +../../Task/Amb/E \ No newline at end of file diff --git a/Lang/E/File-input-output b/Lang/E/File-input-output new file mode 120000 index 0000000000..aa5a919185 --- /dev/null +++ b/Lang/E/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/E \ No newline at end of file diff --git a/Lang/E/String-matching b/Lang/E/String-matching new file mode 120000 index 0000000000..c9ff746ee6 --- /dev/null +++ b/Lang/E/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/E \ No newline at end of file diff --git a/Lang/Eiffel/File-input-output b/Lang/Eiffel/File-input-output new file mode 120000 index 0000000000..81297fc377 --- /dev/null +++ b/Lang/Eiffel/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Ludic-numbers b/Lang/Eiffel/Ludic-numbers new file mode 120000 index 0000000000..aefd6e97c0 --- /dev/null +++ b/Lang/Eiffel/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sum-multiples-of-3-and-5 b/Lang/Eiffel/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..456b420565 --- /dev/null +++ b/Lang/Eiffel/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Eiffel \ No newline at end of file diff --git a/Lang/Ela/Amb b/Lang/Ela/Amb new file mode 120000 index 0000000000..a638d37f1c --- /dev/null +++ b/Lang/Ela/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ela \ No newline at end of file diff --git a/Lang/Elena/Amb b/Lang/Elena/Amb new file mode 120000 index 0000000000..b8a20a821e --- /dev/null +++ b/Lang/Elena/Amb @@ -0,0 +1 @@ +../../Task/Amb/Elena \ No newline at end of file diff --git a/Lang/Elena/Calendar---for-REAL-programmers b/Lang/Elena/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..297243a77f --- /dev/null +++ b/Lang/Elena/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Elena \ No newline at end of file diff --git a/Lang/Elena/String-matching b/Lang/Elena/String-matching new file mode 120000 index 0000000000..ad2671beb2 --- /dev/null +++ b/Lang/Elena/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Elena \ No newline at end of file diff --git a/Lang/Elixir/Reverse-words-in-a-string b/Lang/Elixir/Reverse-words-in-a-string new file mode 120000 index 0000000000..09dc631a3d --- /dev/null +++ b/Lang/Elixir/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sparkline-in-unicode b/Lang/Elixir/Sparkline-in-unicode new file mode 120000 index 0000000000..6f333f4607 --- /dev/null +++ b/Lang/Elixir/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-matching b/Lang/Elixir/String-matching new file mode 120000 index 0000000000..d08323d893 --- /dev/null +++ b/Lang/Elixir/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Closures-Value-capture b/Lang/Emacs-Lisp/Closures-Value-capture new file mode 120000 index 0000000000..ed20163935 --- /dev/null +++ b/Lang/Emacs-Lisp/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/9-billion-names-of-God-the-integer b/Lang/Erlang/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..60b34d5011 --- /dev/null +++ b/Lang/Erlang/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Erlang \ No newline at end of file diff --git a/Lang/Erlang/ABC-Problem b/Lang/Erlang/ABC-Problem new file mode 120000 index 0000000000..71aa4b0059 --- /dev/null +++ b/Lang/Erlang/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/AKS-test-for-primes b/Lang/Erlang/AKS-test-for-primes new file mode 120000 index 0000000000..78653a66e6 --- /dev/null +++ b/Lang/Erlang/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Benfords-law b/Lang/Erlang/Benfords-law new file mode 120000 index 0000000000..edd05b8d64 --- /dev/null +++ b/Lang/Erlang/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Erlang \ No newline at end of file diff --git a/Lang/Erlang/CSV-data-manipulation b/Lang/Erlang/CSV-data-manipulation new file mode 120000 index 0000000000..0b36bcd81d --- /dev/null +++ b/Lang/Erlang/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Chinese-remainder-theorem b/Lang/Erlang/Chinese-remainder-theorem new file mode 120000 index 0000000000..a676df2ea7 --- /dev/null +++ b/Lang/Erlang/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Closures-Value-capture b/Lang/Erlang/Closures-Value-capture new file mode 120000 index 0000000000..41a0452680 --- /dev/null +++ b/Lang/Erlang/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Comma-quibbling b/Lang/Erlang/Comma-quibbling new file mode 120000 index 0000000000..a4bc841352 --- /dev/null +++ b/Lang/Erlang/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Currying b/Lang/Erlang/Currying new file mode 120000 index 0000000000..77fc0039c7 --- /dev/null +++ b/Lang/Erlang/Currying @@ -0,0 +1 @@ +../../Task/Currying/Erlang \ No newline at end of file diff --git a/Lang/Erlang/File-input-output b/Lang/Erlang/File-input-output new file mode 120000 index 0000000000..cfcb068240 --- /dev/null +++ b/Lang/Erlang/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Find-the-last-Sunday-of-each-month b/Lang/Erlang/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..c4d6802beb --- /dev/null +++ b/Lang/Erlang/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Hash-join b/Lang/Erlang/Hash-join new file mode 120000 index 0000000000..641289b7a8 --- /dev/null +++ b/Lang/Erlang/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Hello-world-Newbie b/Lang/Erlang/Hello-world-Newbie new file mode 120000 index 0000000000..2c889eedbd --- /dev/null +++ b/Lang/Erlang/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Odd-word-problem b/Lang/Erlang/Odd-word-problem new file mode 120000 index 0000000000..27a087c45a --- /dev/null +++ b/Lang/Erlang/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/String-matching b/Lang/Erlang/String-matching new file mode 120000 index 0000000000..20d26cb70b --- /dev/null +++ b/Lang/Erlang/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sum-multiples-of-3-and-5 b/Lang/Erlang/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..a496efa2a8 --- /dev/null +++ b/Lang/Erlang/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Erlang \ No newline at end of file diff --git a/Lang/Erlang/World-Cup-group-stage b/Lang/Erlang/World-Cup-group-stage new file mode 120000 index 0000000000..812575ac40 --- /dev/null +++ b/Lang/Erlang/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/ABC-Problem b/Lang/Euphoria/ABC-Problem new file mode 120000 index 0000000000..8b616a5b84 --- /dev/null +++ b/Lang/Euphoria/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/File-input-output b/Lang/Euphoria/File-input-output new file mode 120000 index 0000000000..e6a241792e --- /dev/null +++ b/Lang/Euphoria/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/String-append b/Lang/Euphoria/String-append new file mode 120000 index 0000000000..28dcd7bc84 --- /dev/null +++ b/Lang/Euphoria/String-append @@ -0,0 +1 @@ +../../Task/String-append/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/String-matching b/Lang/Euphoria/String-matching new file mode 120000 index 0000000000..b45aca4de4 --- /dev/null +++ b/Lang/Euphoria/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Euphoria \ No newline at end of file diff --git a/Lang/F-Sharp/Runge-Kutta-method b/Lang/F-Sharp/Runge-Kutta-method new file mode 120000 index 0000000000..700f9da07d --- /dev/null +++ b/Lang/F-Sharp/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/F-Sharp \ No newline at end of file diff --git a/Lang/FALSE/Odd-word-problem b/Lang/FALSE/Odd-word-problem new file mode 120000 index 0000000000..c6d850545b --- /dev/null +++ b/Lang/FALSE/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Sparkline-in-unicode b/Lang/FALSE/Sparkline-in-unicode new file mode 120000 index 0000000000..a210fa9987 --- /dev/null +++ b/Lang/FALSE/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/FALSE \ No newline at end of file diff --git a/Lang/FBSL/ABC-Problem b/Lang/FBSL/ABC-Problem new file mode 120000 index 0000000000..c7b642afde --- /dev/null +++ b/Lang/FBSL/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Find-the-last-Sunday-of-each-month b/Lang/FBSL/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..b02ec9e11a --- /dev/null +++ b/Lang/FBSL/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/FBSL \ No newline at end of file diff --git a/Lang/FBSL/String-matching b/Lang/FBSL/String-matching new file mode 120000 index 0000000000..d7c29bba77 --- /dev/null +++ b/Lang/FBSL/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Sum-multiples-of-3-and-5 b/Lang/FBSL/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..5296225bad --- /dev/null +++ b/Lang/FBSL/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/FBSL \ No newline at end of file diff --git a/Lang/Factor/Amb b/Lang/Factor/Amb new file mode 120000 index 0000000000..424ee95675 --- /dev/null +++ b/Lang/Factor/Amb @@ -0,0 +1 @@ +../../Task/Amb/Factor \ No newline at end of file diff --git a/Lang/Factor/Closures-Value-capture b/Lang/Factor/Closures-Value-capture new file mode 120000 index 0000000000..b25670cb38 --- /dev/null +++ b/Lang/Factor/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Factor \ No newline at end of file diff --git a/Lang/Factor/Conjugate-transpose b/Lang/Factor/Conjugate-transpose new file mode 120000 index 0000000000..4489280ab6 --- /dev/null +++ b/Lang/Factor/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Factor \ No newline at end of file diff --git a/Lang/Factor/File-input-output b/Lang/Factor/File-input-output new file mode 120000 index 0000000000..75833a01f0 --- /dev/null +++ b/Lang/Factor/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Factor \ No newline at end of file diff --git a/Lang/Factor/Generate-lower-case-ASCII-alphabet b/Lang/Factor/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b125f0364f --- /dev/null +++ b/Lang/Factor/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Factor \ No newline at end of file diff --git a/Lang/Factor/Odd-word-problem b/Lang/Factor/Odd-word-problem new file mode 120000 index 0000000000..7b284d8a7f --- /dev/null +++ b/Lang/Factor/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Factor \ No newline at end of file diff --git a/Lang/Factor/Old-lady-swallowed-a-fly b/Lang/Factor/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..5a1ca27647 --- /dev/null +++ b/Lang/Factor/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Factor \ No newline at end of file diff --git a/Lang/Factor/String-prepend b/Lang/Factor/String-prepend new file mode 120000 index 0000000000..6b5f657fa5 --- /dev/null +++ b/Lang/Factor/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Factor \ No newline at end of file diff --git a/Lang/Factor/Zero-to-the-zero-power b/Lang/Factor/Zero-to-the-zero-power new file mode 120000 index 0000000000..795503d315 --- /dev/null +++ b/Lang/Factor/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Factor \ No newline at end of file diff --git a/Lang/Fantom/Closures-Value-capture b/Lang/Fantom/Closures-Value-capture new file mode 120000 index 0000000000..278a848d89 --- /dev/null +++ b/Lang/Fantom/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Fantom \ No newline at end of file diff --git a/Lang/Fantom/String-matching b/Lang/Fantom/String-matching new file mode 120000 index 0000000000..65e631852d --- /dev/null +++ b/Lang/Fantom/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Fantom \ No newline at end of file diff --git a/Lang/Forth/Benfords-law b/Lang/Forth/Benfords-law new file mode 120000 index 0000000000..604610fde0 --- /dev/null +++ b/Lang/Forth/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Forth \ No newline at end of file diff --git a/Lang/Forth/CSV-data-manipulation b/Lang/Forth/CSV-data-manipulation new file mode 120000 index 0000000000..7ffac648ae --- /dev/null +++ b/Lang/Forth/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Forth \ No newline at end of file diff --git a/Lang/Forth/Chinese-remainder-theorem b/Lang/Forth/Chinese-remainder-theorem new file mode 120000 index 0000000000..1bc0fe2b98 --- /dev/null +++ b/Lang/Forth/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Forth \ No newline at end of file diff --git a/Lang/Forth/Currying b/Lang/Forth/Currying new file mode 120000 index 0000000000..d6292c8d4a --- /dev/null +++ b/Lang/Forth/Currying @@ -0,0 +1 @@ +../../Task/Currying/Forth \ No newline at end of file diff --git a/Lang/Forth/File-input-output b/Lang/Forth/File-input-output new file mode 120000 index 0000000000..624167a8a6 --- /dev/null +++ b/Lang/Forth/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Forth \ No newline at end of file diff --git a/Lang/Forth/Nth b/Lang/Forth/Nth new file mode 120000 index 0000000000..86a67605e4 --- /dev/null +++ b/Lang/Forth/Nth @@ -0,0 +1 @@ +../../Task/Nth/Forth \ No newline at end of file diff --git a/Lang/Forth/Odd-word-problem b/Lang/Forth/Odd-word-problem new file mode 120000 index 0000000000..1281fb7277 --- /dev/null +++ b/Lang/Forth/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Forth \ No newline at end of file diff --git a/Lang/Forth/Old-lady-swallowed-a-fly b/Lang/Forth/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..4c3e06db33 --- /dev/null +++ b/Lang/Forth/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Forth \ No newline at end of file diff --git a/Lang/Forth/Semiprime b/Lang/Forth/Semiprime new file mode 120000 index 0000000000..3b3566ff84 --- /dev/null +++ b/Lang/Forth/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Forth \ No newline at end of file diff --git a/Lang/Forth/String-matching b/Lang/Forth/String-matching new file mode 120000 index 0000000000..8660c31ce5 --- /dev/null +++ b/Lang/Forth/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Forth \ No newline at end of file diff --git a/Lang/Forth/Sum-multiples-of-3-and-5 b/Lang/Forth/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..ade94de8ba --- /dev/null +++ b/Lang/Forth/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Forth \ No newline at end of file diff --git a/Lang/Forth/Unix-ls b/Lang/Forth/Unix-ls new file mode 120000 index 0000000000..4f3089980e --- /dev/null +++ b/Lang/Forth/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Forth \ No newline at end of file diff --git a/Lang/Forth/Zero-to-the-zero-power b/Lang/Forth/Zero-to-the-zero-power new file mode 120000 index 0000000000..e65b502334 --- /dev/null +++ b/Lang/Forth/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Forth \ No newline at end of file diff --git a/Lang/Fortran/ABC-Problem b/Lang/Fortran/ABC-Problem new file mode 120000 index 0000000000..95659ac1d7 --- /dev/null +++ b/Lang/Fortran/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Benfords-law b/Lang/Fortran/Benfords-law new file mode 120000 index 0000000000..d233da455e --- /dev/null +++ b/Lang/Fortran/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Circles-of-given-radius-through-two-points b/Lang/Fortran/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..f1552ffa7b --- /dev/null +++ b/Lang/Fortran/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Conjugate-transpose b/Lang/Fortran/Conjugate-transpose new file mode 120000 index 0000000000..56066fc848 --- /dev/null +++ b/Lang/Fortran/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Digital-root-Multiplicative-digital-root b/Lang/Fortran/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..89b0c31b5a --- /dev/null +++ b/Lang/Fortran/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Draw-a-clock b/Lang/Fortran/Draw-a-clock new file mode 120000 index 0000000000..5c45d70453 --- /dev/null +++ b/Lang/Fortran/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Fortran \ No newline at end of file diff --git a/Lang/Fortran/File-input-output b/Lang/Fortran/File-input-output new file mode 120000 index 0000000000..e66ce3c66c --- /dev/null +++ b/Lang/Fortran/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Flipping-bits-game b/Lang/Fortran/Flipping-bits-game new file mode 120000 index 0000000000..9f5b16df63 --- /dev/null +++ b/Lang/Fortran/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Gaussian-elimination b/Lang/Fortran/Gaussian-elimination new file mode 120000 index 0000000000..e7928cde6c --- /dev/null +++ b/Lang/Fortran/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Generate-lower-case-ASCII-alphabet b/Lang/Fortran/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..deb8beee2d --- /dev/null +++ b/Lang/Fortran/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Hickerson-series-of-almost-integers b/Lang/Fortran/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..41d6ed1769 --- /dev/null +++ b/Lang/Fortran/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Nth b/Lang/Fortran/Nth new file mode 120000 index 0000000000..edc9c53081 --- /dev/null +++ b/Lang/Fortran/Nth @@ -0,0 +1 @@ +../../Task/Nth/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Percolation-Mean-run-density b/Lang/Fortran/Percolation-Mean-run-density new file mode 120000 index 0000000000..574c639137 --- /dev/null +++ b/Lang/Fortran/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Percolation-Site-percolation b/Lang/Fortran/Percolation-Site-percolation new file mode 120000 index 0000000000..b148284b98 --- /dev/null +++ b/Lang/Fortran/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Runge-Kutta-method b/Lang/Fortran/Runge-Kutta-method new file mode 120000 index 0000000000..32c1e19b33 --- /dev/null +++ b/Lang/Fortran/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Statistics-Basic b/Lang/Fortran/Statistics-Basic new file mode 120000 index 0000000000..2054c88b60 --- /dev/null +++ b/Lang/Fortran/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Zero-to-the-zero-power b/Lang/Fortran/Zero-to-the-zero-power new file mode 120000 index 0000000000..04bffb464b --- /dev/null +++ b/Lang/Fortran/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Fortran \ No newline at end of file diff --git a/Lang/Frege/Old-lady-swallowed-a-fly b/Lang/Frege/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..86718def3c --- /dev/null +++ b/Lang/Frege/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Frege \ No newline at end of file diff --git a/Lang/Frink/9-billion-names-of-God-the-integer b/Lang/Frink/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..95d41908b2 --- /dev/null +++ b/Lang/Frink/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Frink \ No newline at end of file diff --git a/Lang/Frink/File-input-output b/Lang/Frink/File-input-output new file mode 120000 index 0000000000..f52bbfaaac --- /dev/null +++ b/Lang/Frink/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Frink \ No newline at end of file diff --git a/Lang/GAP/File-input-output b/Lang/GAP/File-input-output new file mode 120000 index 0000000000..929c223f18 --- /dev/null +++ b/Lang/GAP/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/GAP \ No newline at end of file diff --git a/Lang/GML/File-input-output b/Lang/GML/File-input-output new file mode 120000 index 0000000000..7c1e86c9c9 --- /dev/null +++ b/Lang/GML/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/GML \ No newline at end of file diff --git a/Lang/GML/String-matching b/Lang/GML/String-matching new file mode 120000 index 0000000000..7f4235f481 --- /dev/null +++ b/Lang/GML/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/GML \ No newline at end of file diff --git a/Lang/GUISS/Calendar---for-REAL-programmers b/Lang/GUISS/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..ac423977fc --- /dev/null +++ b/Lang/GUISS/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Draw-a-clock b/Lang/GUISS/Draw-a-clock new file mode 120000 index 0000000000..c308af377f --- /dev/null +++ b/Lang/GUISS/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/GUISS \ No newline at end of file diff --git a/Lang/GUISS/File-input-output b/Lang/GUISS/File-input-output new file mode 120000 index 0000000000..56e6aab700 --- /dev/null +++ b/Lang/GUISS/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/GUISS \ No newline at end of file diff --git a/Lang/Gnuplot/Munching-squares b/Lang/Gnuplot/Munching-squares new file mode 120000 index 0000000000..afa477d667 --- /dev/null +++ b/Lang/Gnuplot/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Gnuplot \ No newline at end of file diff --git a/Lang/Go/ABC-Problem b/Lang/Go/ABC-Problem new file mode 120000 index 0000000000..73c4cad955 --- /dev/null +++ b/Lang/Go/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Go \ No newline at end of file diff --git a/Lang/Go/AKS-test-for-primes b/Lang/Go/AKS-test-for-primes new file mode 120000 index 0000000000..549f8c04c5 --- /dev/null +++ b/Lang/Go/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Go \ No newline at end of file diff --git a/Lang/Go/Almost-prime b/Lang/Go/Almost-prime new file mode 120000 index 0000000000..1631082788 --- /dev/null +++ b/Lang/Go/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Go \ No newline at end of file diff --git a/Lang/Go/Amb b/Lang/Go/Amb new file mode 120000 index 0000000000..c4fc56d05e --- /dev/null +++ b/Lang/Go/Amb @@ -0,0 +1 @@ +../../Task/Amb/Go \ No newline at end of file diff --git a/Lang/Go/Append-a-record-to-the-end-of-a-text-file b/Lang/Go/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..35d3058e72 --- /dev/null +++ b/Lang/Go/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Go \ No newline at end of file diff --git a/Lang/Go/Benfords-law b/Lang/Go/Benfords-law new file mode 120000 index 0000000000..a13db99e0b --- /dev/null +++ b/Lang/Go/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Go \ No newline at end of file diff --git a/Lang/Go/Bernoulli-numbers b/Lang/Go/Bernoulli-numbers new file mode 120000 index 0000000000..43db0cb429 --- /dev/null +++ b/Lang/Go/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Go \ No newline at end of file diff --git a/Lang/Go/Bitcoin-public-point-to-address b/Lang/Go/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..38057e555b --- /dev/null +++ b/Lang/Go/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Go \ No newline at end of file diff --git a/Lang/Go/CSV-data-manipulation b/Lang/Go/CSV-data-manipulation new file mode 120000 index 0000000000..b74399a22c --- /dev/null +++ b/Lang/Go/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Go \ No newline at end of file diff --git a/Lang/Go/Casting-out-nines b/Lang/Go/Casting-out-nines new file mode 120000 index 0000000000..acf491a607 --- /dev/null +++ b/Lang/Go/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Go \ No newline at end of file diff --git a/Lang/Go/Catamorphism b/Lang/Go/Catamorphism new file mode 120000 index 0000000000..d308a11282 --- /dev/null +++ b/Lang/Go/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Go \ No newline at end of file diff --git a/Lang/Go/Chinese-remainder-theorem b/Lang/Go/Chinese-remainder-theorem new file mode 120000 index 0000000000..f3037a71a9 --- /dev/null +++ b/Lang/Go/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Go \ No newline at end of file diff --git a/Lang/Go/Circles-of-given-radius-through-two-points b/Lang/Go/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..967316ccd7 --- /dev/null +++ b/Lang/Go/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Go \ No newline at end of file diff --git a/Lang/Go/Closures-Value-capture b/Lang/Go/Closures-Value-capture new file mode 120000 index 0000000000..aae9620899 --- /dev/null +++ b/Lang/Go/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Go \ No newline at end of file diff --git a/Lang/Go/Comma-quibbling b/Lang/Go/Comma-quibbling new file mode 120000 index 0000000000..05538f0be1 --- /dev/null +++ b/Lang/Go/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Go \ No newline at end of file diff --git a/Lang/Go/Conjugate-transpose b/Lang/Go/Conjugate-transpose new file mode 120000 index 0000000000..a7fed33408 --- /dev/null +++ b/Lang/Go/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Go \ No newline at end of file diff --git a/Lang/Go/Convert-decimal-number-to-rational b/Lang/Go/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..4b4a2c232d --- /dev/null +++ b/Lang/Go/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Go \ No newline at end of file diff --git a/Lang/Go/Currying b/Lang/Go/Currying new file mode 120000 index 0000000000..9ed1d19dbd --- /dev/null +++ b/Lang/Go/Currying @@ -0,0 +1 @@ +../../Task/Currying/Go \ No newline at end of file diff --git a/Lang/Go/Digital-root-Multiplicative-digital-root b/Lang/Go/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..188420354f --- /dev/null +++ b/Lang/Go/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Go \ No newline at end of file diff --git a/Lang/Go/Draw-a-clock b/Lang/Go/Draw-a-clock new file mode 120000 index 0000000000..18443c1f5e --- /dev/null +++ b/Lang/Go/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Go \ No newline at end of file diff --git a/Lang/Go/Extensible-prime-generator b/Lang/Go/Extensible-prime-generator new file mode 120000 index 0000000000..c4fdcc58a1 --- /dev/null +++ b/Lang/Go/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Go \ No newline at end of file diff --git a/Lang/Go/Fibonacci-word b/Lang/Go/Fibonacci-word new file mode 120000 index 0000000000..e673d2577e --- /dev/null +++ b/Lang/Go/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Go \ No newline at end of file diff --git a/Lang/Go/File-input-output b/Lang/Go/File-input-output new file mode 120000 index 0000000000..f61c276cd7 --- /dev/null +++ b/Lang/Go/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Go \ No newline at end of file diff --git a/Lang/Go/Find-the-last-Sunday-of-each-month b/Lang/Go/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..7725ca1aa8 --- /dev/null +++ b/Lang/Go/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Go \ No newline at end of file diff --git a/Lang/Go/Flipping-bits-game b/Lang/Go/Flipping-bits-game new file mode 120000 index 0000000000..4cf25e44e7 --- /dev/null +++ b/Lang/Go/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Go \ No newline at end of file diff --git a/Lang/Go/Fractran b/Lang/Go/Fractran new file mode 120000 index 0000000000..de656d70ad --- /dev/null +++ b/Lang/Go/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Go \ No newline at end of file diff --git a/Lang/Go/Gaussian-elimination b/Lang/Go/Gaussian-elimination new file mode 120000 index 0000000000..9752dc8a97 --- /dev/null +++ b/Lang/Go/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Go \ No newline at end of file diff --git a/Lang/Go/Generate-Chess960-starting-position b/Lang/Go/Generate-Chess960-starting-position new file mode 120000 index 0000000000..94d04be832 --- /dev/null +++ b/Lang/Go/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Go \ No newline at end of file diff --git a/Lang/Go/Generate-lower-case-ASCII-alphabet b/Lang/Go/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..7d84031434 --- /dev/null +++ b/Lang/Go/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Go \ No newline at end of file diff --git a/Lang/Go/Hash-join b/Lang/Go/Hash-join new file mode 120000 index 0000000000..6d91ff30a5 --- /dev/null +++ b/Lang/Go/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Go \ No newline at end of file diff --git a/Lang/Go/Hickerson-series-of-almost-integers b/Lang/Go/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..510a950da3 --- /dev/null +++ b/Lang/Go/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Go \ No newline at end of file diff --git a/Lang/Go/IBAN b/Lang/Go/IBAN new file mode 120000 index 0000000000..3801c2867b --- /dev/null +++ b/Lang/Go/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Go \ No newline at end of file diff --git a/Lang/Go/Integer-overflow b/Lang/Go/Integer-overflow new file mode 120000 index 0000000000..16ba237c92 --- /dev/null +++ b/Lang/Go/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Go \ No newline at end of file diff --git a/Lang/Go/Iterated-digits-squaring b/Lang/Go/Iterated-digits-squaring new file mode 120000 index 0000000000..836fcc6eb8 --- /dev/null +++ b/Lang/Go/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Go \ No newline at end of file diff --git a/Lang/Go/K-d-tree b/Lang/Go/K-d-tree new file mode 120000 index 0000000000..424be83984 --- /dev/null +++ b/Lang/Go/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Go \ No newline at end of file diff --git a/Lang/Go/Left-factorials b/Lang/Go/Left-factorials new file mode 120000 index 0000000000..8c90ec21f1 --- /dev/null +++ b/Lang/Go/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Go \ No newline at end of file diff --git a/Lang/Go/Longest-increasing-subsequence b/Lang/Go/Longest-increasing-subsequence new file mode 120000 index 0000000000..d09199dc75 --- /dev/null +++ b/Lang/Go/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Go \ No newline at end of file diff --git a/Lang/Go/Ludic-numbers b/Lang/Go/Ludic-numbers new file mode 120000 index 0000000000..1c8abf5c07 --- /dev/null +++ b/Lang/Go/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Go \ No newline at end of file diff --git a/Lang/Go/Magic-squares-of-odd-order b/Lang/Go/Magic-squares-of-odd-order new file mode 120000 index 0000000000..37091a7c96 --- /dev/null +++ b/Lang/Go/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Go \ No newline at end of file diff --git a/Lang/Go/Make-directory-path b/Lang/Go/Make-directory-path new file mode 120000 index 0000000000..8b2619e1dd --- /dev/null +++ b/Lang/Go/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Go \ No newline at end of file diff --git a/Lang/Go/Maximum-triangle-path-sum b/Lang/Go/Maximum-triangle-path-sum new file mode 120000 index 0000000000..38183f9773 --- /dev/null +++ b/Lang/Go/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Go \ No newline at end of file diff --git a/Lang/Go/Move-to-front-algorithm b/Lang/Go/Move-to-front-algorithm new file mode 120000 index 0000000000..f5d553b4f2 --- /dev/null +++ b/Lang/Go/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Go \ No newline at end of file diff --git a/Lang/Go/Munching-squares b/Lang/Go/Munching-squares new file mode 120000 index 0000000000..d4d4409da7 --- /dev/null +++ b/Lang/Go/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Go \ No newline at end of file diff --git a/Lang/Go/Narcissistic-decimal-number b/Lang/Go/Narcissistic-decimal-number new file mode 120000 index 0000000000..1fbe448d2a --- /dev/null +++ b/Lang/Go/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Go \ No newline at end of file diff --git a/Lang/Go/Natural-sorting b/Lang/Go/Natural-sorting new file mode 120000 index 0000000000..97e3ac5aaf --- /dev/null +++ b/Lang/Go/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Go \ No newline at end of file diff --git a/Lang/Go/Nth b/Lang/Go/Nth new file mode 120000 index 0000000000..e9fb44c3f0 --- /dev/null +++ b/Lang/Go/Nth @@ -0,0 +1 @@ +../../Task/Nth/Go \ No newline at end of file diff --git a/Lang/Go/Odd-word-problem b/Lang/Go/Odd-word-problem new file mode 120000 index 0000000000..6c15202a6b --- /dev/null +++ b/Lang/Go/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Go \ No newline at end of file diff --git a/Lang/Go/Order-disjoint-list-items b/Lang/Go/Order-disjoint-list-items new file mode 120000 index 0000000000..ec33a70ec7 --- /dev/null +++ b/Lang/Go/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Go \ No newline at end of file diff --git a/Lang/Go/Paraffins b/Lang/Go/Paraffins new file mode 120000 index 0000000000..a5e7d10b98 --- /dev/null +++ b/Lang/Go/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Go \ No newline at end of file diff --git a/Lang/Go/Parse-an-IP-Address b/Lang/Go/Parse-an-IP-Address new file mode 120000 index 0000000000..176ebb593e --- /dev/null +++ b/Lang/Go/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Go \ No newline at end of file diff --git a/Lang/Go/Percolation-Bond-percolation b/Lang/Go/Percolation-Bond-percolation new file mode 120000 index 0000000000..f85800608f --- /dev/null +++ b/Lang/Go/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Go \ No newline at end of file diff --git a/Lang/Go/Percolation-Site-percolation b/Lang/Go/Percolation-Site-percolation new file mode 120000 index 0000000000..f989c8ac48 --- /dev/null +++ b/Lang/Go/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Go \ No newline at end of file diff --git a/Lang/Go/Permutations-Rank-of-a-permutation b/Lang/Go/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..d62b470629 --- /dev/null +++ b/Lang/Go/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Go \ No newline at end of file diff --git a/Lang/Go/Pernicious-numbers b/Lang/Go/Pernicious-numbers new file mode 120000 index 0000000000..9bdbfd1f42 --- /dev/null +++ b/Lang/Go/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Go \ No newline at end of file diff --git a/Lang/Go/Phrase-reversals b/Lang/Go/Phrase-reversals new file mode 120000 index 0000000000..1d7767f86f --- /dev/null +++ b/Lang/Go/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Go \ No newline at end of file diff --git a/Lang/Go/Quickselect-algorithm b/Lang/Go/Quickselect-algorithm new file mode 120000 index 0000000000..8ea67e90a1 --- /dev/null +++ b/Lang/Go/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Go \ No newline at end of file diff --git a/Lang/Go/RSA-code b/Lang/Go/RSA-code new file mode 120000 index 0000000000..0636f97c6a --- /dev/null +++ b/Lang/Go/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Go \ No newline at end of file diff --git a/Lang/Go/Ranking-methods b/Lang/Go/Ranking-methods new file mode 120000 index 0000000000..6580f6f715 --- /dev/null +++ b/Lang/Go/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Go \ No newline at end of file diff --git a/Lang/Go/Rep-string b/Lang/Go/Rep-string new file mode 120000 index 0000000000..ff5c570049 --- /dev/null +++ b/Lang/Go/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Go \ No newline at end of file diff --git a/Lang/Go/Reverse-words-in-a-string b/Lang/Go/Reverse-words-in-a-string new file mode 120000 index 0000000000..9b375bbd5a --- /dev/null +++ b/Lang/Go/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Go \ No newline at end of file diff --git a/Lang/Go/Runge-Kutta-method b/Lang/Go/Runge-Kutta-method new file mode 120000 index 0000000000..bfd8ab8395 --- /dev/null +++ b/Lang/Go/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Go \ No newline at end of file diff --git a/Lang/Go/Semiprime b/Lang/Go/Semiprime new file mode 120000 index 0000000000..fa9ec48945 --- /dev/null +++ b/Lang/Go/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Go \ No newline at end of file diff --git a/Lang/Go/Sequence-of-primes-by-Trial-Division b/Lang/Go/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..75d7bbc1b4 --- /dev/null +++ b/Lang/Go/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Go \ No newline at end of file diff --git a/Lang/Go/Solve-the-no-connection-puzzle b/Lang/Go/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..1b0d1a9f97 --- /dev/null +++ b/Lang/Go/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Sparkline-in-unicode b/Lang/Go/Sparkline-in-unicode new file mode 120000 index 0000000000..ad83fb27f6 --- /dev/null +++ b/Lang/Go/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Go \ No newline at end of file diff --git a/Lang/Go/State-name-puzzle b/Lang/Go/State-name-puzzle new file mode 120000 index 0000000000..37295f34b2 --- /dev/null +++ b/Lang/Go/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Statistics-Basic b/Lang/Go/Statistics-Basic new file mode 120000 index 0000000000..d4374e52e2 --- /dev/null +++ b/Lang/Go/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Go \ No newline at end of file diff --git a/Lang/Go/Stern-Brocot-sequence b/Lang/Go/Stern-Brocot-sequence new file mode 120000 index 0000000000..fd78c888dc --- /dev/null +++ b/Lang/Go/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Go \ No newline at end of file diff --git a/Lang/Go/String-append b/Lang/Go/String-append new file mode 120000 index 0000000000..8b8320f036 --- /dev/null +++ b/Lang/Go/String-append @@ -0,0 +1 @@ +../../Task/String-append/Go \ No newline at end of file diff --git a/Lang/Go/String-matching b/Lang/Go/String-matching new file mode 120000 index 0000000000..972eee2708 --- /dev/null +++ b/Lang/Go/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Go \ No newline at end of file diff --git a/Lang/Go/String-prepend b/Lang/Go/String-prepend new file mode 120000 index 0000000000..03c7a697b5 --- /dev/null +++ b/Lang/Go/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Go \ No newline at end of file diff --git a/Lang/Go/Sum-multiples-of-3-and-5 b/Lang/Go/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1d94982fec --- /dev/null +++ b/Lang/Go/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Go \ No newline at end of file diff --git a/Lang/Go/Textonyms b/Lang/Go/Textonyms new file mode 120000 index 0000000000..b7947b7c9b --- /dev/null +++ b/Lang/Go/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Go \ No newline at end of file diff --git a/Lang/Go/The-ISAAC-Cipher b/Lang/Go/The-ISAAC-Cipher new file mode 120000 index 0000000000..fdba2e9ec2 --- /dev/null +++ b/Lang/Go/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Go \ No newline at end of file diff --git a/Lang/Go/The-Twelve-Days-of-Christmas b/Lang/Go/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..30c96895ba --- /dev/null +++ b/Lang/Go/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Go \ No newline at end of file diff --git a/Lang/Go/Total-circles-area b/Lang/Go/Total-circles-area new file mode 120000 index 0000000000..74647e668b --- /dev/null +++ b/Lang/Go/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Go \ No newline at end of file diff --git a/Lang/Go/Unix-ls b/Lang/Go/Unix-ls new file mode 120000 index 0000000000..d8b771b31b --- /dev/null +++ b/Lang/Go/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Go \ No newline at end of file diff --git a/Lang/Go/Zero-to-the-zero-power b/Lang/Go/Zero-to-the-zero-power new file mode 120000 index 0000000000..5b1245ebd5 --- /dev/null +++ b/Lang/Go/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Go \ No newline at end of file diff --git a/Lang/Go/Zhang-Suen-thinning-algorithm b/Lang/Go/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..42dde2687b --- /dev/null +++ b/Lang/Go/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Go \ No newline at end of file diff --git a/Lang/Groovy/ABC-Problem b/Lang/Groovy/ABC-Problem new file mode 120000 index 0000000000..9f28b2a954 --- /dev/null +++ b/Lang/Groovy/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Append-a-record-to-the-end-of-a-text-file b/Lang/Groovy/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..14ef3448fa --- /dev/null +++ b/Lang/Groovy/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Groovy \ No newline at end of file diff --git a/Lang/Groovy/CSV-data-manipulation b/Lang/Groovy/CSV-data-manipulation new file mode 120000 index 0000000000..6b65c628e6 --- /dev/null +++ b/Lang/Groovy/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Closures-Value-capture b/Lang/Groovy/Closures-Value-capture new file mode 120000 index 0000000000..db38c0a572 --- /dev/null +++ b/Lang/Groovy/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Comma-quibbling b/Lang/Groovy/Comma-quibbling new file mode 120000 index 0000000000..606470c1d7 --- /dev/null +++ b/Lang/Groovy/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Currying b/Lang/Groovy/Currying new file mode 120000 index 0000000000..8cf92a749e --- /dev/null +++ b/Lang/Groovy/Currying @@ -0,0 +1 @@ +../../Task/Currying/Groovy \ No newline at end of file diff --git a/Lang/Groovy/File-input-output b/Lang/Groovy/File-input-output new file mode 120000 index 0000000000..f118310eb3 --- /dev/null +++ b/Lang/Groovy/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Find-the-last-Sunday-of-each-month b/Lang/Groovy/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..aee907af87 --- /dev/null +++ b/Lang/Groovy/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Generate-lower-case-ASCII-alphabet b/Lang/Groovy/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..165e4aad7c --- /dev/null +++ b/Lang/Groovy/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Hash-join b/Lang/Groovy/Hash-join new file mode 120000 index 0000000000..06e676db72 --- /dev/null +++ b/Lang/Groovy/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Groovy \ No newline at end of file diff --git a/Lang/Groovy/IBAN b/Lang/Groovy/IBAN new file mode 120000 index 0000000000..46d22eba49 --- /dev/null +++ b/Lang/Groovy/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Phrase-reversals b/Lang/Groovy/Phrase-reversals new file mode 120000 index 0000000000..d44ac4ccf7 --- /dev/null +++ b/Lang/Groovy/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Reverse-words-in-a-string b/Lang/Groovy/Reverse-words-in-a-string new file mode 120000 index 0000000000..33f7135289 --- /dev/null +++ b/Lang/Groovy/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sparkline-in-unicode b/Lang/Groovy/Sparkline-in-unicode new file mode 120000 index 0000000000..0fee9284ce --- /dev/null +++ b/Lang/Groovy/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-matching b/Lang/Groovy/String-matching new file mode 120000 index 0000000000..7d39c56151 --- /dev/null +++ b/Lang/Groovy/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sum-multiples-of-3-and-5 b/Lang/Groovy/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..8bad6987e1 --- /dev/null +++ b/Lang/Groovy/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Groovy \ No newline at end of file diff --git a/Lang/Groovy/The-Twelve-Days-of-Christmas b/Lang/Groovy/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..541b1849dc --- /dev/null +++ b/Lang/Groovy/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Zero-to-the-zero-power b/Lang/Groovy/Zero-to-the-zero-power new file mode 120000 index 0000000000..8a174896bc --- /dev/null +++ b/Lang/Groovy/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Zhang-Suen-thinning-algorithm b/Lang/Groovy/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..c0076ba5e0 --- /dev/null +++ b/Lang/Groovy/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Groovy \ No newline at end of file diff --git a/Lang/Haskell/9-billion-names-of-God-the-integer b/Lang/Haskell/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..6092490a58 --- /dev/null +++ b/Lang/Haskell/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Haskell \ No newline at end of file diff --git a/Lang/Haskell/ABC-Problem b/Lang/Haskell/ABC-Problem new file mode 120000 index 0000000000..ee6a433e2a --- /dev/null +++ b/Lang/Haskell/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Haskell \ No newline at end of file diff --git a/Lang/Haskell/AKS-test-for-primes b/Lang/Haskell/AKS-test-for-primes new file mode 120000 index 0000000000..aac1609f63 --- /dev/null +++ b/Lang/Haskell/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Abundant,-deficient-and-perfect-number-classifications b/Lang/Haskell/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..8e08fc03da --- /dev/null +++ b/Lang/Haskell/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Aliquot-sequence-classifications b/Lang/Haskell/Aliquot-sequence-classifications new file mode 120000 index 0000000000..a548a674d8 --- /dev/null +++ b/Lang/Haskell/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Almost-prime b/Lang/Haskell/Almost-prime new file mode 120000 index 0000000000..6f43c3ecb5 --- /dev/null +++ b/Lang/Haskell/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Amb b/Lang/Haskell/Amb new file mode 120000 index 0000000000..6eb7bd4eba --- /dev/null +++ b/Lang/Haskell/Amb @@ -0,0 +1 @@ +../../Task/Amb/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Amicable-pairs b/Lang/Haskell/Amicable-pairs new file mode 120000 index 0000000000..dafa82d669 --- /dev/null +++ b/Lang/Haskell/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Append-a-record-to-the-end-of-a-text-file b/Lang/Haskell/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..9b0ce0ebfd --- /dev/null +++ b/Lang/Haskell/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Haskell/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..bb43e32793 --- /dev/null +++ b/Lang/Haskell/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Benfords-law b/Lang/Haskell/Benfords-law new file mode 120000 index 0000000000..a4679f702d --- /dev/null +++ b/Lang/Haskell/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Bernoulli-numbers b/Lang/Haskell/Bernoulli-numbers new file mode 120000 index 0000000000..729bd74bd8 --- /dev/null +++ b/Lang/Haskell/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/CSV-data-manipulation b/Lang/Haskell/CSV-data-manipulation new file mode 120000 index 0000000000..c1e748a1c9 --- /dev/null +++ b/Lang/Haskell/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Catamorphism b/Lang/Haskell/Catamorphism new file mode 120000 index 0000000000..65dc9bcab2 --- /dev/null +++ b/Lang/Haskell/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Chinese-remainder-theorem b/Lang/Haskell/Chinese-remainder-theorem new file mode 120000 index 0000000000..d78667b66f --- /dev/null +++ b/Lang/Haskell/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Circles-of-given-radius-through-two-points b/Lang/Haskell/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..012e404718 --- /dev/null +++ b/Lang/Haskell/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Closures-Value-capture b/Lang/Haskell/Closures-Value-capture new file mode 120000 index 0000000000..4b08187bd8 --- /dev/null +++ b/Lang/Haskell/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Comma-quibbling b/Lang/Haskell/Comma-quibbling new file mode 120000 index 0000000000..c8440bb602 --- /dev/null +++ b/Lang/Haskell/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Convert-decimal-number-to-rational b/Lang/Haskell/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..d422c4821e --- /dev/null +++ b/Lang/Haskell/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Currying b/Lang/Haskell/Currying new file mode 120000 index 0000000000..3c45a63adb --- /dev/null +++ b/Lang/Haskell/Currying @@ -0,0 +1 @@ +../../Task/Currying/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Digital-root-Multiplicative-digital-root b/Lang/Haskell/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..ec002b69c8 --- /dev/null +++ b/Lang/Haskell/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Draw-a-clock b/Lang/Haskell/Draw-a-clock new file mode 120000 index 0000000000..c91a27d1e2 --- /dev/null +++ b/Lang/Haskell/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Extensible-prime-generator b/Lang/Haskell/Extensible-prime-generator new file mode 120000 index 0000000000..a3b61ad14e --- /dev/null +++ b/Lang/Haskell/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Fibonacci-word b/Lang/Haskell/Fibonacci-word new file mode 120000 index 0000000000..cef0c52deb --- /dev/null +++ b/Lang/Haskell/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Haskell \ No newline at end of file diff --git a/Lang/Haskell/File-input-output b/Lang/Haskell/File-input-output new file mode 120000 index 0000000000..9e472d51d2 --- /dev/null +++ b/Lang/Haskell/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Flipping-bits-game b/Lang/Haskell/Flipping-bits-game new file mode 120000 index 0000000000..23e16398cc --- /dev/null +++ b/Lang/Haskell/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Fractran b/Lang/Haskell/Fractran new file mode 120000 index 0000000000..c65bab74a3 --- /dev/null +++ b/Lang/Haskell/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Generate-Chess960-starting-position b/Lang/Haskell/Generate-Chess960-starting-position new file mode 120000 index 0000000000..114614fdb4 --- /dev/null +++ b/Lang/Haskell/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Generate-lower-case-ASCII-alphabet b/Lang/Haskell/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..ecfba8d533 --- /dev/null +++ b/Lang/Haskell/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Hash-join b/Lang/Haskell/Hash-join new file mode 120000 index 0000000000..d760e9725c --- /dev/null +++ b/Lang/Haskell/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Hello-world-Newbie b/Lang/Haskell/Hello-world-Newbie new file mode 120000 index 0000000000..88abda2273 --- /dev/null +++ b/Lang/Haskell/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Heronian-triangles b/Lang/Haskell/Heronian-triangles new file mode 120000 index 0000000000..2e7f015be1 --- /dev/null +++ b/Lang/Haskell/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Haskell \ No newline at end of file diff --git a/Lang/Haskell/IBAN b/Lang/Haskell/IBAN new file mode 120000 index 0000000000..5579cce5ad --- /dev/null +++ b/Lang/Haskell/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Integer-overflow b/Lang/Haskell/Integer-overflow new file mode 120000 index 0000000000..f88423a885 --- /dev/null +++ b/Lang/Haskell/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Iterated-digits-squaring b/Lang/Haskell/Iterated-digits-squaring new file mode 120000 index 0000000000..aa1c315b2e --- /dev/null +++ b/Lang/Haskell/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Haskell \ No newline at end of file diff --git a/Lang/Haskell/K-d-tree b/Lang/Haskell/K-d-tree new file mode 120000 index 0000000000..11e51a2458 --- /dev/null +++ b/Lang/Haskell/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Left-factorials b/Lang/Haskell/Left-factorials new file mode 120000 index 0000000000..7530883f2a --- /dev/null +++ b/Lang/Haskell/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Longest-increasing-subsequence b/Lang/Haskell/Longest-increasing-subsequence new file mode 120000 index 0000000000..3dc0509755 --- /dev/null +++ b/Lang/Haskell/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Ludic-numbers b/Lang/Haskell/Ludic-numbers new file mode 120000 index 0000000000..5eb46db5a0 --- /dev/null +++ b/Lang/Haskell/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Magic-squares-of-odd-order b/Lang/Haskell/Magic-squares-of-odd-order new file mode 120000 index 0000000000..b60090c3c9 --- /dev/null +++ b/Lang/Haskell/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Maximum-triangle-path-sum b/Lang/Haskell/Maximum-triangle-path-sum new file mode 120000 index 0000000000..110b58305c --- /dev/null +++ b/Lang/Haskell/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Move-to-front-algorithm b/Lang/Haskell/Move-to-front-algorithm new file mode 120000 index 0000000000..baa93c12de --- /dev/null +++ b/Lang/Haskell/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Munching-squares b/Lang/Haskell/Munching-squares new file mode 120000 index 0000000000..0e144d9a81 --- /dev/null +++ b/Lang/Haskell/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Narcissistic-decimal-number b/Lang/Haskell/Narcissistic-decimal-number new file mode 120000 index 0000000000..f6ca561a49 --- /dev/null +++ b/Lang/Haskell/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Nth b/Lang/Haskell/Nth new file mode 120000 index 0000000000..d8868ee602 --- /dev/null +++ b/Lang/Haskell/Nth @@ -0,0 +1 @@ +../../Task/Nth/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Odd-word-problem b/Lang/Haskell/Odd-word-problem new file mode 120000 index 0000000000..32ad010935 --- /dev/null +++ b/Lang/Haskell/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Old-lady-swallowed-a-fly b/Lang/Haskell/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..c7aee3c0ff --- /dev/null +++ b/Lang/Haskell/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Paraffins b/Lang/Haskell/Paraffins new file mode 120000 index 0000000000..bd1ebc66d0 --- /dev/null +++ b/Lang/Haskell/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Penneys-game b/Lang/Haskell/Penneys-game new file mode 120000 index 0000000000..81b6b10c7f --- /dev/null +++ b/Lang/Haskell/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Percolation-Mean-run-density b/Lang/Haskell/Percolation-Mean-run-density new file mode 120000 index 0000000000..9f5595b9ac --- /dev/null +++ b/Lang/Haskell/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Permutations-Rank-of-a-permutation b/Lang/Haskell/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..1df0db0d36 --- /dev/null +++ b/Lang/Haskell/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Pernicious-numbers b/Lang/Haskell/Pernicious-numbers new file mode 120000 index 0000000000..a33046bc18 --- /dev/null +++ b/Lang/Haskell/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Phrase-reversals b/Lang/Haskell/Phrase-reversals new file mode 120000 index 0000000000..49c5ecbbb7 --- /dev/null +++ b/Lang/Haskell/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Quickselect-algorithm b/Lang/Haskell/Quickselect-algorithm new file mode 120000 index 0000000000..c292258cda --- /dev/null +++ b/Lang/Haskell/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Ranking-methods b/Lang/Haskell/Ranking-methods new file mode 120000 index 0000000000..04c872bf01 --- /dev/null +++ b/Lang/Haskell/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Rep-string b/Lang/Haskell/Rep-string new file mode 120000 index 0000000000..5a478fb081 --- /dev/null +++ b/Lang/Haskell/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Reverse-words-in-a-string b/Lang/Haskell/Reverse-words-in-a-string new file mode 120000 index 0000000000..b398f63a19 --- /dev/null +++ b/Lang/Haskell/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Runge-Kutta-method b/Lang/Haskell/Runge-Kutta-method new file mode 120000 index 0000000000..96e0981b75 --- /dev/null +++ b/Lang/Haskell/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Semiprime b/Lang/Haskell/Semiprime new file mode 120000 index 0000000000..acfdcd4bff --- /dev/null +++ b/Lang/Haskell/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sequence-of-primes-by-Trial-Division b/Lang/Haskell/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..d15794c551 --- /dev/null +++ b/Lang/Haskell/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Solve-a-Holy-Knights-tour b/Lang/Haskell/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..1f7febcdba --- /dev/null +++ b/Lang/Haskell/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sparkline-in-unicode b/Lang/Haskell/Sparkline-in-unicode new file mode 120000 index 0000000000..81aebd5eeb --- /dev/null +++ b/Lang/Haskell/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Stern-Brocot-sequence b/Lang/Haskell/Stern-Brocot-sequence new file mode 120000 index 0000000000..b345656767 --- /dev/null +++ b/Lang/Haskell/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-append b/Lang/Haskell/String-append new file mode 120000 index 0000000000..e2cd241cc9 --- /dev/null +++ b/Lang/Haskell/String-append @@ -0,0 +1 @@ +../../Task/String-append/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-matching b/Lang/Haskell/String-matching new file mode 120000 index 0000000000..c551180abd --- /dev/null +++ b/Lang/Haskell/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-prepend b/Lang/Haskell/String-prepend new file mode 120000 index 0000000000..c5836ecd50 --- /dev/null +++ b/Lang/Haskell/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sum-multiples-of-3-and-5 b/Lang/Haskell/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1e80ed1af3 --- /dev/null +++ b/Lang/Haskell/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Haskell \ No newline at end of file diff --git a/Lang/Haskell/The-ISAAC-Cipher b/Lang/Haskell/The-ISAAC-Cipher new file mode 120000 index 0000000000..32bf316a4b --- /dev/null +++ b/Lang/Haskell/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Total-circles-area b/Lang/Haskell/Total-circles-area new file mode 120000 index 0000000000..9df1636ef3 --- /dev/null +++ b/Lang/Haskell/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Unix-ls b/Lang/Haskell/Unix-ls new file mode 120000 index 0000000000..89dbd1ef0a --- /dev/null +++ b/Lang/Haskell/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Zero-to-the-zero-power b/Lang/Haskell/Zero-to-the-zero-power new file mode 120000 index 0000000000..f53f6d8b90 --- /dev/null +++ b/Lang/Haskell/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Zhang-Suen-thinning-algorithm b/Lang/Haskell/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..d490998a9e --- /dev/null +++ b/Lang/Haskell/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Haskell \ No newline at end of file diff --git a/Lang/Haxe/Amb b/Lang/Haxe/Amb new file mode 120000 index 0000000000..0b26ae446e --- /dev/null +++ b/Lang/Haxe/Amb @@ -0,0 +1 @@ +../../Task/Amb/Haxe \ No newline at end of file diff --git a/Lang/Haxe/The-ISAAC-Cipher b/Lang/Haxe/The-ISAAC-Cipher new file mode 120000 index 0000000000..8b320ebc6f --- /dev/null +++ b/Lang/Haxe/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Haxe \ No newline at end of file diff --git a/Lang/HicEst/File-input-output b/Lang/HicEst/File-input-output new file mode 120000 index 0000000000..6d24b9522e --- /dev/null +++ b/Lang/HicEst/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/HicEst \ No newline at end of file diff --git a/Lang/IDL/File-input-output b/Lang/IDL/File-input-output new file mode 120000 index 0000000000..1d959e4c2f --- /dev/null +++ b/Lang/IDL/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/IDL \ No newline at end of file diff --git a/Lang/Icon/ABC-Problem b/Lang/Icon/ABC-Problem new file mode 120000 index 0000000000..427b195d91 --- /dev/null +++ b/Lang/Icon/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Almost-prime b/Lang/Icon/Almost-prime new file mode 120000 index 0000000000..0d05d6b3c3 --- /dev/null +++ b/Lang/Icon/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Icon \ No newline at end of file diff --git a/Lang/Icon/Amb b/Lang/Icon/Amb new file mode 120000 index 0000000000..390f1a1a25 --- /dev/null +++ b/Lang/Icon/Amb @@ -0,0 +1 @@ +../../Task/Amb/Icon \ No newline at end of file diff --git a/Lang/Icon/Append-a-record-to-the-end-of-a-text-file b/Lang/Icon/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..6594626bc3 --- /dev/null +++ b/Lang/Icon/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Icon \ No newline at end of file diff --git a/Lang/Icon/Benfords-law b/Lang/Icon/Benfords-law new file mode 120000 index 0000000000..9148df1a23 --- /dev/null +++ b/Lang/Icon/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Icon \ No newline at end of file diff --git a/Lang/Icon/Bernoulli-numbers b/Lang/Icon/Bernoulli-numbers new file mode 120000 index 0000000000..790fe99e33 --- /dev/null +++ b/Lang/Icon/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/CSV-data-manipulation b/Lang/Icon/CSV-data-manipulation new file mode 120000 index 0000000000..da290460e5 --- /dev/null +++ b/Lang/Icon/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Icon \ No newline at end of file diff --git a/Lang/Icon/Calendar---for-REAL-programmers b/Lang/Icon/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..1dcbeda0a7 --- /dev/null +++ b/Lang/Icon/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Icon \ No newline at end of file diff --git a/Lang/Icon/Catalan-numbers-Pascals-triangle b/Lang/Icon/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..dd2583e70c --- /dev/null +++ b/Lang/Icon/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Icon \ No newline at end of file diff --git a/Lang/Icon/Catamorphism b/Lang/Icon/Catamorphism new file mode 120000 index 0000000000..3f3f93ffe1 --- /dev/null +++ b/Lang/Icon/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Icon \ No newline at end of file diff --git a/Lang/Icon/Chinese-remainder-theorem b/Lang/Icon/Chinese-remainder-theorem new file mode 120000 index 0000000000..8c63077264 --- /dev/null +++ b/Lang/Icon/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Icon \ No newline at end of file diff --git a/Lang/Icon/Circles-of-given-radius-through-two-points b/Lang/Icon/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..f9fad1bf7f --- /dev/null +++ b/Lang/Icon/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Icon \ No newline at end of file diff --git a/Lang/Icon/Closures-Value-capture b/Lang/Icon/Closures-Value-capture new file mode 120000 index 0000000000..53978a1a40 --- /dev/null +++ b/Lang/Icon/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Icon \ No newline at end of file diff --git a/Lang/Icon/Combinations-and-permutations b/Lang/Icon/Combinations-and-permutations new file mode 120000 index 0000000000..e4f4b4364a --- /dev/null +++ b/Lang/Icon/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Icon \ No newline at end of file diff --git a/Lang/Icon/Comma-quibbling b/Lang/Icon/Comma-quibbling new file mode 120000 index 0000000000..16431b3c91 --- /dev/null +++ b/Lang/Icon/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Icon \ No newline at end of file diff --git a/Lang/Icon/Digital-root-Multiplicative-digital-root b/Lang/Icon/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..83f04c7032 --- /dev/null +++ b/Lang/Icon/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Icon \ No newline at end of file diff --git a/Lang/Icon/Fibonacci-word b/Lang/Icon/Fibonacci-word new file mode 120000 index 0000000000..f20e85b38b --- /dev/null +++ b/Lang/Icon/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Icon \ No newline at end of file diff --git a/Lang/Icon/Fibonacci-word-fractal b/Lang/Icon/Fibonacci-word-fractal new file mode 120000 index 0000000000..b428c2caee --- /dev/null +++ b/Lang/Icon/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Icon \ No newline at end of file diff --git a/Lang/Icon/File-input-output b/Lang/Icon/File-input-output new file mode 120000 index 0000000000..c076ab8ce6 --- /dev/null +++ b/Lang/Icon/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Icon \ No newline at end of file diff --git a/Lang/Icon/Find-the-last-Sunday-of-each-month b/Lang/Icon/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..075fae448b --- /dev/null +++ b/Lang/Icon/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Icon \ No newline at end of file diff --git a/Lang/Icon/Fractran b/Lang/Icon/Fractran new file mode 120000 index 0000000000..6d49132383 --- /dev/null +++ b/Lang/Icon/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Icon \ No newline at end of file diff --git a/Lang/Icon/Generate-lower-case-ASCII-alphabet b/Lang/Icon/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b64e18917d --- /dev/null +++ b/Lang/Icon/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Icon \ No newline at end of file diff --git a/Lang/Icon/Left-factorials b/Lang/Icon/Left-factorials new file mode 120000 index 0000000000..7c4e0d4299 --- /dev/null +++ b/Lang/Icon/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Icon \ No newline at end of file diff --git a/Lang/Icon/Longest-increasing-subsequence b/Lang/Icon/Longest-increasing-subsequence new file mode 120000 index 0000000000..5b40cb9455 --- /dev/null +++ b/Lang/Icon/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Icon \ No newline at end of file diff --git a/Lang/Icon/Ludic-numbers b/Lang/Icon/Ludic-numbers new file mode 120000 index 0000000000..97ad63237f --- /dev/null +++ b/Lang/Icon/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Move-to-front-algorithm b/Lang/Icon/Move-to-front-algorithm new file mode 120000 index 0000000000..ae075ba53c --- /dev/null +++ b/Lang/Icon/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Icon \ No newline at end of file diff --git a/Lang/Icon/Munching-squares b/Lang/Icon/Munching-squares new file mode 120000 index 0000000000..9b514ef441 --- /dev/null +++ b/Lang/Icon/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Icon \ No newline at end of file diff --git a/Lang/Icon/Narcissistic-decimal-number b/Lang/Icon/Narcissistic-decimal-number new file mode 120000 index 0000000000..0559306c42 --- /dev/null +++ b/Lang/Icon/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Icon \ No newline at end of file diff --git a/Lang/Icon/Nth b/Lang/Icon/Nth new file mode 120000 index 0000000000..8f6f46ca3e --- /dev/null +++ b/Lang/Icon/Nth @@ -0,0 +1 @@ +../../Task/Nth/Icon \ No newline at end of file diff --git a/Lang/Icon/Odd-word-problem b/Lang/Icon/Odd-word-problem new file mode 120000 index 0000000000..a2a8f3b3bf --- /dev/null +++ b/Lang/Icon/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Old-lady-swallowed-a-fly b/Lang/Icon/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..222a310275 --- /dev/null +++ b/Lang/Icon/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Icon \ No newline at end of file diff --git a/Lang/Icon/Order-disjoint-list-items b/Lang/Icon/Order-disjoint-list-items new file mode 120000 index 0000000000..a5fcfe3807 --- /dev/null +++ b/Lang/Icon/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Icon \ No newline at end of file diff --git a/Lang/Icon/Parse-an-IP-Address b/Lang/Icon/Parse-an-IP-Address new file mode 120000 index 0000000000..13465acbf9 --- /dev/null +++ b/Lang/Icon/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Icon \ No newline at end of file diff --git a/Lang/Icon/Percolation-Mean-run-density b/Lang/Icon/Percolation-Mean-run-density new file mode 120000 index 0000000000..75f0a34fc2 --- /dev/null +++ b/Lang/Icon/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Icon \ No newline at end of file diff --git a/Lang/Icon/Pernicious-numbers b/Lang/Icon/Pernicious-numbers new file mode 120000 index 0000000000..47f0baa3d2 --- /dev/null +++ b/Lang/Icon/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Quickselect-algorithm b/Lang/Icon/Quickselect-algorithm new file mode 120000 index 0000000000..0616d9b90a --- /dev/null +++ b/Lang/Icon/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Icon \ No newline at end of file diff --git a/Lang/Icon/RSA-code b/Lang/Icon/RSA-code new file mode 120000 index 0000000000..46477e19ee --- /dev/null +++ b/Lang/Icon/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Icon \ No newline at end of file diff --git a/Lang/Icon/Rep-string b/Lang/Icon/Rep-string new file mode 120000 index 0000000000..9440acf6d3 --- /dev/null +++ b/Lang/Icon/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Reverse-words-in-a-string b/Lang/Icon/Reverse-words-in-a-string new file mode 120000 index 0000000000..f29ccf75d7 --- /dev/null +++ b/Lang/Icon/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Semiprime b/Lang/Icon/Semiprime new file mode 120000 index 0000000000..52b4c00a0c --- /dev/null +++ b/Lang/Icon/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Icon \ No newline at end of file diff --git a/Lang/Icon/State-name-puzzle b/Lang/Icon/State-name-puzzle new file mode 120000 index 0000000000..5b8f5905de --- /dev/null +++ b/Lang/Icon/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Icon \ No newline at end of file diff --git a/Lang/Icon/Statistics-Basic b/Lang/Icon/Statistics-Basic new file mode 120000 index 0000000000..7719a870ac --- /dev/null +++ b/Lang/Icon/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Icon \ No newline at end of file diff --git a/Lang/Icon/String-append b/Lang/Icon/String-append new file mode 120000 index 0000000000..b523b2c310 --- /dev/null +++ b/Lang/Icon/String-append @@ -0,0 +1 @@ +../../Task/String-append/Icon \ No newline at end of file diff --git a/Lang/Icon/String-prepend b/Lang/Icon/String-prepend new file mode 120000 index 0000000000..f383ce6096 --- /dev/null +++ b/Lang/Icon/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Icon \ No newline at end of file diff --git a/Lang/Icon/Sum-multiples-of-3-and-5 b/Lang/Icon/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..371dad824c --- /dev/null +++ b/Lang/Icon/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Icon \ No newline at end of file diff --git a/Lang/Icon/The-Twelve-Days-of-Christmas b/Lang/Icon/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..8bbc2576ef --- /dev/null +++ b/Lang/Icon/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Icon \ No newline at end of file diff --git a/Lang/Icon/Zero-to-the-zero-power b/Lang/Icon/Zero-to-the-zero-power new file mode 120000 index 0000000000..a789d93a0f --- /dev/null +++ b/Lang/Icon/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Icon \ No newline at end of file diff --git a/Lang/Io/Currying b/Lang/Io/Currying new file mode 120000 index 0000000000..4505f834e3 --- /dev/null +++ b/Lang/Io/Currying @@ -0,0 +1 @@ +../../Task/Currying/Io \ No newline at end of file diff --git a/Lang/Io/File-input-output b/Lang/Io/File-input-output new file mode 120000 index 0000000000..b64e5cfb83 --- /dev/null +++ b/Lang/Io/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Io \ No newline at end of file diff --git a/Lang/J/9-billion-names-of-God-the-integer b/Lang/J/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..3bd5697ff7 --- /dev/null +++ b/Lang/J/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/J \ No newline at end of file diff --git a/Lang/J/ABC-Problem b/Lang/J/ABC-Problem new file mode 120000 index 0000000000..066df3fb21 --- /dev/null +++ b/Lang/J/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/J \ No newline at end of file diff --git a/Lang/J/AKS-test-for-primes b/Lang/J/AKS-test-for-primes new file mode 120000 index 0000000000..31072f4fed --- /dev/null +++ b/Lang/J/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/J \ No newline at end of file diff --git a/Lang/J/Abundant,-deficient-and-perfect-number-classifications b/Lang/J/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..624c7d4aa0 --- /dev/null +++ b/Lang/J/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/J \ No newline at end of file diff --git a/Lang/J/Aliquot-sequence-classifications b/Lang/J/Aliquot-sequence-classifications new file mode 120000 index 0000000000..7b4da0ecbe --- /dev/null +++ b/Lang/J/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/J \ No newline at end of file diff --git a/Lang/J/Almost-prime b/Lang/J/Almost-prime new file mode 120000 index 0000000000..569d4fb7aa --- /dev/null +++ b/Lang/J/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/J \ No newline at end of file diff --git a/Lang/J/Amb b/Lang/J/Amb new file mode 120000 index 0000000000..694fb9ed30 --- /dev/null +++ b/Lang/J/Amb @@ -0,0 +1 @@ +../../Task/Amb/J \ No newline at end of file diff --git a/Lang/J/Amicable-pairs b/Lang/J/Amicable-pairs new file mode 120000 index 0000000000..d515672834 --- /dev/null +++ b/Lang/J/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/J \ No newline at end of file diff --git a/Lang/J/Append-a-record-to-the-end-of-a-text-file b/Lang/J/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..7e42242961 --- /dev/null +++ b/Lang/J/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/J \ No newline at end of file diff --git a/Lang/J/Arithmetic-geometric-mean-Calculate-Pi b/Lang/J/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..7ea33655a4 --- /dev/null +++ b/Lang/J/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/J \ No newline at end of file diff --git a/Lang/J/Benfords-law b/Lang/J/Benfords-law new file mode 120000 index 0000000000..b54b85f22e --- /dev/null +++ b/Lang/J/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/J \ No newline at end of file diff --git a/Lang/J/Bernoulli-numbers b/Lang/J/Bernoulli-numbers new file mode 120000 index 0000000000..4c43470691 --- /dev/null +++ b/Lang/J/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/J \ No newline at end of file diff --git a/Lang/J/CSV-data-manipulation b/Lang/J/CSV-data-manipulation new file mode 120000 index 0000000000..b2f893a1da --- /dev/null +++ b/Lang/J/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/J \ No newline at end of file diff --git a/Lang/J/Calendar---for-REAL-programmers b/Lang/J/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..08ddbac2a2 --- /dev/null +++ b/Lang/J/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/J \ No newline at end of file diff --git a/Lang/J/Casting-out-nines b/Lang/J/Casting-out-nines new file mode 120000 index 0000000000..2ef590267b --- /dev/null +++ b/Lang/J/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/J \ No newline at end of file diff --git a/Lang/J/Catalan-numbers-Pascals-triangle b/Lang/J/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..67904f885d --- /dev/null +++ b/Lang/J/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/J \ No newline at end of file diff --git a/Lang/J/Catamorphism b/Lang/J/Catamorphism new file mode 120000 index 0000000000..2eba577c91 --- /dev/null +++ b/Lang/J/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/J \ No newline at end of file diff --git a/Lang/J/Chinese-remainder-theorem b/Lang/J/Chinese-remainder-theorem new file mode 120000 index 0000000000..bd51b076b1 --- /dev/null +++ b/Lang/J/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/J \ No newline at end of file diff --git a/Lang/J/Circles-of-given-radius-through-two-points b/Lang/J/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..05e01e3abd --- /dev/null +++ b/Lang/J/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/J \ No newline at end of file diff --git a/Lang/J/Closures-Value-capture b/Lang/J/Closures-Value-capture new file mode 120000 index 0000000000..ccc37d9d7f --- /dev/null +++ b/Lang/J/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/J \ No newline at end of file diff --git a/Lang/J/Combinations-and-permutations b/Lang/J/Combinations-and-permutations new file mode 120000 index 0000000000..d1f02c5c30 --- /dev/null +++ b/Lang/J/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/J \ No newline at end of file diff --git a/Lang/J/Comma-quibbling b/Lang/J/Comma-quibbling new file mode 120000 index 0000000000..e1b258516d --- /dev/null +++ b/Lang/J/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/J \ No newline at end of file diff --git a/Lang/J/Conjugate-transpose b/Lang/J/Conjugate-transpose new file mode 120000 index 0000000000..5683e6c89a --- /dev/null +++ b/Lang/J/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/J \ No newline at end of file diff --git a/Lang/J/Convert-decimal-number-to-rational b/Lang/J/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..ae6e7b55df --- /dev/null +++ b/Lang/J/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/J \ No newline at end of file diff --git a/Lang/J/Currying b/Lang/J/Currying new file mode 120000 index 0000000000..d2ae47cd2b --- /dev/null +++ b/Lang/J/Currying @@ -0,0 +1 @@ +../../Task/Currying/J \ No newline at end of file diff --git a/Lang/J/Digital-root-Multiplicative-digital-root b/Lang/J/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..3e2057a0b5 --- /dev/null +++ b/Lang/J/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/J \ No newline at end of file diff --git a/Lang/J/Draw-a-clock b/Lang/J/Draw-a-clock new file mode 120000 index 0000000000..4d9652b237 --- /dev/null +++ b/Lang/J/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/J \ No newline at end of file diff --git a/Lang/J/Extensible-prime-generator b/Lang/J/Extensible-prime-generator new file mode 120000 index 0000000000..ceb47f3f3d --- /dev/null +++ b/Lang/J/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/J \ No newline at end of file diff --git a/Lang/J/Fibonacci-word b/Lang/J/Fibonacci-word new file mode 120000 index 0000000000..b8d0a923cd --- /dev/null +++ b/Lang/J/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/J \ No newline at end of file diff --git a/Lang/J/Fibonacci-word-fractal b/Lang/J/Fibonacci-word-fractal new file mode 120000 index 0000000000..32bca68082 --- /dev/null +++ b/Lang/J/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/J \ No newline at end of file diff --git a/Lang/J/File-input-output b/Lang/J/File-input-output new file mode 120000 index 0000000000..c74bf9e3f7 --- /dev/null +++ b/Lang/J/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/J \ No newline at end of file diff --git a/Lang/J/Find-the-last-Sunday-of-each-month b/Lang/J/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..32c8218b24 --- /dev/null +++ b/Lang/J/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/J \ No newline at end of file diff --git a/Lang/J/Flipping-bits-game b/Lang/J/Flipping-bits-game new file mode 120000 index 0000000000..833c0f2785 --- /dev/null +++ b/Lang/J/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/J \ No newline at end of file diff --git a/Lang/J/Fractran b/Lang/J/Fractran new file mode 120000 index 0000000000..ebf667bb5d --- /dev/null +++ b/Lang/J/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/J \ No newline at end of file diff --git a/Lang/J/Gaussian-elimination b/Lang/J/Gaussian-elimination new file mode 120000 index 0000000000..f18cf1a77c --- /dev/null +++ b/Lang/J/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/J \ No newline at end of file diff --git a/Lang/J/Generate-Chess960-starting-position b/Lang/J/Generate-Chess960-starting-position new file mode 120000 index 0000000000..59d1691ca7 --- /dev/null +++ b/Lang/J/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/J \ No newline at end of file diff --git a/Lang/J/Generate-lower-case-ASCII-alphabet b/Lang/J/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b2644532ec --- /dev/null +++ b/Lang/J/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/J \ No newline at end of file diff --git a/Lang/J/Hash-join b/Lang/J/Hash-join new file mode 120000 index 0000000000..8335657638 --- /dev/null +++ b/Lang/J/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/J \ No newline at end of file diff --git a/Lang/J/Hello-world-Newbie b/Lang/J/Hello-world-Newbie new file mode 120000 index 0000000000..7c9bbb755e --- /dev/null +++ b/Lang/J/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/J \ No newline at end of file diff --git a/Lang/J/Heronian-triangles b/Lang/J/Heronian-triangles new file mode 120000 index 0000000000..27ba92c448 --- /dev/null +++ b/Lang/J/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/J \ No newline at end of file diff --git a/Lang/J/Hickerson-series-of-almost-integers b/Lang/J/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..e2431ed8c3 --- /dev/null +++ b/Lang/J/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/J \ No newline at end of file diff --git a/Lang/J/IBAN b/Lang/J/IBAN new file mode 120000 index 0000000000..df3ddf81d2 --- /dev/null +++ b/Lang/J/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/J \ No newline at end of file diff --git a/Lang/J/Integer-overflow b/Lang/J/Integer-overflow new file mode 120000 index 0000000000..1d760c2eaa --- /dev/null +++ b/Lang/J/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/J \ No newline at end of file diff --git a/Lang/J/Iterated-digits-squaring b/Lang/J/Iterated-digits-squaring new file mode 120000 index 0000000000..7123a654e3 --- /dev/null +++ b/Lang/J/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/J \ No newline at end of file diff --git a/Lang/J/K-d-tree b/Lang/J/K-d-tree new file mode 120000 index 0000000000..9311ea887f --- /dev/null +++ b/Lang/J/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/J \ No newline at end of file diff --git a/Lang/J/Left-factorials b/Lang/J/Left-factorials new file mode 120000 index 0000000000..d010643697 --- /dev/null +++ b/Lang/J/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/J \ No newline at end of file diff --git a/Lang/J/Longest-increasing-subsequence b/Lang/J/Longest-increasing-subsequence new file mode 120000 index 0000000000..1fc0402b03 --- /dev/null +++ b/Lang/J/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/J \ No newline at end of file diff --git a/Lang/J/Ludic-numbers b/Lang/J/Ludic-numbers new file mode 120000 index 0000000000..ffc3f065fc --- /dev/null +++ b/Lang/J/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/J \ No newline at end of file diff --git a/Lang/J/Magic-squares-of-odd-order b/Lang/J/Magic-squares-of-odd-order new file mode 120000 index 0000000000..995c444cfb --- /dev/null +++ b/Lang/J/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/J \ No newline at end of file diff --git a/Lang/J/Maximum-triangle-path-sum b/Lang/J/Maximum-triangle-path-sum new file mode 120000 index 0000000000..e1b03efff0 --- /dev/null +++ b/Lang/J/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/J \ No newline at end of file diff --git a/Lang/J/Move-to-front-algorithm b/Lang/J/Move-to-front-algorithm new file mode 120000 index 0000000000..284d508264 --- /dev/null +++ b/Lang/J/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/J \ No newline at end of file diff --git a/Lang/J/Munching-squares b/Lang/J/Munching-squares new file mode 120000 index 0000000000..b7437b28e1 --- /dev/null +++ b/Lang/J/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/J \ No newline at end of file diff --git a/Lang/J/Narcissistic-decimal-number b/Lang/J/Narcissistic-decimal-number new file mode 120000 index 0000000000..c5686b5c30 --- /dev/null +++ b/Lang/J/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/J \ No newline at end of file diff --git a/Lang/J/Natural-sorting b/Lang/J/Natural-sorting new file mode 120000 index 0000000000..4f1f68573c --- /dev/null +++ b/Lang/J/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/J \ No newline at end of file diff --git a/Lang/J/Nth b/Lang/J/Nth new file mode 120000 index 0000000000..c77a90cbbe --- /dev/null +++ b/Lang/J/Nth @@ -0,0 +1 @@ +../../Task/Nth/J \ No newline at end of file diff --git a/Lang/J/Odd-word-problem b/Lang/J/Odd-word-problem new file mode 120000 index 0000000000..b818f10aa4 --- /dev/null +++ b/Lang/J/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/J \ No newline at end of file diff --git a/Lang/J/Old-lady-swallowed-a-fly b/Lang/J/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..2dc6c8ddfd --- /dev/null +++ b/Lang/J/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/J \ No newline at end of file diff --git a/Lang/J/Order-disjoint-list-items b/Lang/J/Order-disjoint-list-items new file mode 120000 index 0000000000..87378833d0 --- /dev/null +++ b/Lang/J/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/J \ No newline at end of file diff --git a/Lang/J/Paraffins b/Lang/J/Paraffins new file mode 120000 index 0000000000..56287a8421 --- /dev/null +++ b/Lang/J/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/J \ No newline at end of file diff --git a/Lang/J/Parse-an-IP-Address b/Lang/J/Parse-an-IP-Address new file mode 120000 index 0000000000..40220362f7 --- /dev/null +++ b/Lang/J/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/J \ No newline at end of file diff --git a/Lang/J/Penneys-game b/Lang/J/Penneys-game new file mode 120000 index 0000000000..3055f7ef44 --- /dev/null +++ b/Lang/J/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/J \ No newline at end of file diff --git a/Lang/J/Percolation-Mean-cluster-density b/Lang/J/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..0b1d8015a0 --- /dev/null +++ b/Lang/J/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/J \ No newline at end of file diff --git a/Lang/J/Percolation-Mean-run-density b/Lang/J/Percolation-Mean-run-density new file mode 120000 index 0000000000..f38669ad9d --- /dev/null +++ b/Lang/J/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/J \ No newline at end of file diff --git a/Lang/J/Percolation-Site-percolation b/Lang/J/Percolation-Site-percolation new file mode 120000 index 0000000000..e62e3873b6 --- /dev/null +++ b/Lang/J/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/J \ No newline at end of file diff --git a/Lang/J/Permutations-Rank-of-a-permutation b/Lang/J/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..ba6e54490d --- /dev/null +++ b/Lang/J/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/J \ No newline at end of file diff --git a/Lang/J/Pernicious-numbers b/Lang/J/Pernicious-numbers new file mode 120000 index 0000000000..647565af2e --- /dev/null +++ b/Lang/J/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/J \ No newline at end of file diff --git a/Lang/J/Phrase-reversals b/Lang/J/Phrase-reversals new file mode 120000 index 0000000000..2d964d1f6c --- /dev/null +++ b/Lang/J/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/J \ No newline at end of file diff --git a/Lang/J/Quickselect-algorithm b/Lang/J/Quickselect-algorithm new file mode 120000 index 0000000000..63233fe362 --- /dev/null +++ b/Lang/J/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/J \ No newline at end of file diff --git a/Lang/J/RSA-code b/Lang/J/RSA-code new file mode 120000 index 0000000000..984ea5270d --- /dev/null +++ b/Lang/J/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/J \ No newline at end of file diff --git a/Lang/J/Ranking-methods b/Lang/J/Ranking-methods new file mode 120000 index 0000000000..831a516905 --- /dev/null +++ b/Lang/J/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/J \ No newline at end of file diff --git a/Lang/J/Rep-string b/Lang/J/Rep-string new file mode 120000 index 0000000000..588f9e4378 --- /dev/null +++ b/Lang/J/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/J \ No newline at end of file diff --git a/Lang/J/Reverse-words-in-a-string b/Lang/J/Reverse-words-in-a-string new file mode 120000 index 0000000000..0dd30d1204 --- /dev/null +++ b/Lang/J/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/J \ No newline at end of file diff --git a/Lang/J/Runge-Kutta-method b/Lang/J/Runge-Kutta-method new file mode 120000 index 0000000000..cdb0e6a889 --- /dev/null +++ b/Lang/J/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/J \ No newline at end of file diff --git a/Lang/J/Semiprime b/Lang/J/Semiprime new file mode 120000 index 0000000000..478fb1046b --- /dev/null +++ b/Lang/J/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/J \ No newline at end of file diff --git a/Lang/J/Sequence-of-primes-by-Trial-Division b/Lang/J/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..dcdb21460a --- /dev/null +++ b/Lang/J/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/J \ No newline at end of file diff --git a/Lang/J/Solve-a-Holy-Knights-tour b/Lang/J/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..af555a4d23 --- /dev/null +++ b/Lang/J/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/J \ No newline at end of file diff --git a/Lang/J/Solve-the-no-connection-puzzle b/Lang/J/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d6eb73ece2 --- /dev/null +++ b/Lang/J/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/J \ No newline at end of file diff --git a/Lang/J/Sparkline-in-unicode b/Lang/J/Sparkline-in-unicode new file mode 120000 index 0000000000..c8f060efb1 --- /dev/null +++ b/Lang/J/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/J \ No newline at end of file diff --git a/Lang/J/State-name-puzzle b/Lang/J/State-name-puzzle new file mode 120000 index 0000000000..69e97c1b69 --- /dev/null +++ b/Lang/J/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/J \ No newline at end of file diff --git a/Lang/J/Statistics-Basic b/Lang/J/Statistics-Basic new file mode 120000 index 0000000000..56eeaa6068 --- /dev/null +++ b/Lang/J/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/J \ No newline at end of file diff --git a/Lang/J/Stern-Brocot-sequence b/Lang/J/Stern-Brocot-sequence new file mode 120000 index 0000000000..e609bc388a --- /dev/null +++ b/Lang/J/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/J \ No newline at end of file diff --git a/Lang/J/String-append b/Lang/J/String-append new file mode 120000 index 0000000000..049fcea2f0 --- /dev/null +++ b/Lang/J/String-append @@ -0,0 +1 @@ +../../Task/String-append/J \ No newline at end of file diff --git a/Lang/J/String-matching b/Lang/J/String-matching new file mode 120000 index 0000000000..017c2ac0bd --- /dev/null +++ b/Lang/J/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/J \ No newline at end of file diff --git a/Lang/J/String-prepend b/Lang/J/String-prepend new file mode 120000 index 0000000000..d70b0344de --- /dev/null +++ b/Lang/J/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/J \ No newline at end of file diff --git a/Lang/J/Sum-multiples-of-3-and-5 b/Lang/J/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..4eb3738203 --- /dev/null +++ b/Lang/J/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/J \ No newline at end of file diff --git a/Lang/J/Textonyms b/Lang/J/Textonyms new file mode 120000 index 0000000000..5073340b4e --- /dev/null +++ b/Lang/J/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/J \ No newline at end of file diff --git a/Lang/J/The-Twelve-Days-of-Christmas b/Lang/J/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..7be5a30796 --- /dev/null +++ b/Lang/J/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/J \ No newline at end of file diff --git a/Lang/J/Total-circles-area b/Lang/J/Total-circles-area new file mode 120000 index 0000000000..39ece4b6a0 --- /dev/null +++ b/Lang/J/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/J \ No newline at end of file diff --git a/Lang/J/Ulam-spiral--for-primes- b/Lang/J/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..37f383d2a8 --- /dev/null +++ b/Lang/J/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/J \ No newline at end of file diff --git a/Lang/J/Unix-ls b/Lang/J/Unix-ls new file mode 120000 index 0000000000..4734b7924b --- /dev/null +++ b/Lang/J/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/J \ No newline at end of file diff --git a/Lang/J/World-Cup-group-stage b/Lang/J/World-Cup-group-stage new file mode 120000 index 0000000000..3a6eb21509 --- /dev/null +++ b/Lang/J/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/J \ No newline at end of file diff --git a/Lang/J/Zero-to-the-zero-power b/Lang/J/Zero-to-the-zero-power new file mode 120000 index 0000000000..e8cdbf5982 --- /dev/null +++ b/Lang/J/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/J \ No newline at end of file diff --git a/Lang/J/Zhang-Suen-thinning-algorithm b/Lang/J/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..2322f9fc25 --- /dev/null +++ b/Lang/J/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/J \ No newline at end of file diff --git a/Lang/Java/ABC-Problem b/Lang/Java/ABC-Problem new file mode 120000 index 0000000000..0f38f01e33 --- /dev/null +++ b/Lang/Java/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Java \ No newline at end of file diff --git a/Lang/Java/Append-a-record-to-the-end-of-a-text-file b/Lang/Java/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..6ef51378f2 --- /dev/null +++ b/Lang/Java/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Java \ No newline at end of file diff --git a/Lang/Java/Benfords-law b/Lang/Java/Benfords-law new file mode 120000 index 0000000000..503c2e839a --- /dev/null +++ b/Lang/Java/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Java \ No newline at end of file diff --git a/Lang/Java/CSV-data-manipulation b/Lang/Java/CSV-data-manipulation new file mode 120000 index 0000000000..8cdc504be8 --- /dev/null +++ b/Lang/Java/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Java \ No newline at end of file diff --git a/Lang/Java/Catamorphism b/Lang/Java/Catamorphism new file mode 120000 index 0000000000..869534ef88 --- /dev/null +++ b/Lang/Java/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Java \ No newline at end of file diff --git a/Lang/Java/Closures-Value-capture b/Lang/Java/Closures-Value-capture new file mode 120000 index 0000000000..1c328799bb --- /dev/null +++ b/Lang/Java/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Java \ No newline at end of file diff --git a/Lang/Java/Comma-quibbling b/Lang/Java/Comma-quibbling new file mode 120000 index 0000000000..66becaf21e --- /dev/null +++ b/Lang/Java/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Java \ No newline at end of file diff --git a/Lang/Java/Currying b/Lang/Java/Currying new file mode 120000 index 0000000000..997de98810 --- /dev/null +++ b/Lang/Java/Currying @@ -0,0 +1 @@ +../../Task/Currying/Java \ No newline at end of file diff --git a/Lang/Java/Digital-root-Multiplicative-digital-root b/Lang/Java/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..87f2d2011a --- /dev/null +++ b/Lang/Java/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Java \ No newline at end of file diff --git a/Lang/Java/Draw-a-clock b/Lang/Java/Draw-a-clock new file mode 120000 index 0000000000..8717fe405f --- /dev/null +++ b/Lang/Java/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Java \ No newline at end of file diff --git a/Lang/Java/Fibonacci-word b/Lang/Java/Fibonacci-word new file mode 120000 index 0000000000..a83d14eb26 --- /dev/null +++ b/Lang/Java/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Java \ No newline at end of file diff --git a/Lang/Java/File-input-output b/Lang/Java/File-input-output new file mode 120000 index 0000000000..51242e9ec1 --- /dev/null +++ b/Lang/Java/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Java \ No newline at end of file diff --git a/Lang/Java/Find-the-last-Sunday-of-each-month b/Lang/Java/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..00becc2969 --- /dev/null +++ b/Lang/Java/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Java \ No newline at end of file diff --git a/Lang/Java/Fractran b/Lang/Java/Fractran new file mode 120000 index 0000000000..09b253c49f --- /dev/null +++ b/Lang/Java/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Java \ No newline at end of file diff --git a/Lang/Java/Generate-Chess960-starting-position b/Lang/Java/Generate-Chess960-starting-position new file mode 120000 index 0000000000..4c1b83bee7 --- /dev/null +++ b/Lang/Java/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Java \ No newline at end of file diff --git a/Lang/Java/Generate-lower-case-ASCII-alphabet b/Lang/Java/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..f710ed9bb0 --- /dev/null +++ b/Lang/Java/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Java \ No newline at end of file diff --git a/Lang/Java/Heronian-triangles b/Lang/Java/Heronian-triangles new file mode 120000 index 0000000000..2bceb9ef0b --- /dev/null +++ b/Lang/Java/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Java \ No newline at end of file diff --git a/Lang/Java/IBAN b/Lang/Java/IBAN new file mode 120000 index 0000000000..092054cc1f --- /dev/null +++ b/Lang/Java/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Java \ No newline at end of file diff --git a/Lang/Java/Integer-overflow b/Lang/Java/Integer-overflow new file mode 120000 index 0000000000..6d6c2378bf --- /dev/null +++ b/Lang/Java/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Java \ No newline at end of file diff --git a/Lang/Java/Iterated-digits-squaring b/Lang/Java/Iterated-digits-squaring new file mode 120000 index 0000000000..cb9ace82a8 --- /dev/null +++ b/Lang/Java/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Java \ No newline at end of file diff --git a/Lang/Java/Left-factorials b/Lang/Java/Left-factorials new file mode 120000 index 0000000000..a1f4daaafd --- /dev/null +++ b/Lang/Java/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Java \ No newline at end of file diff --git a/Lang/Java/Longest-increasing-subsequence b/Lang/Java/Longest-increasing-subsequence new file mode 120000 index 0000000000..f01d8b99be --- /dev/null +++ b/Lang/Java/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Java \ No newline at end of file diff --git a/Lang/Java/Ludic-numbers b/Lang/Java/Ludic-numbers new file mode 120000 index 0000000000..09890d09b3 --- /dev/null +++ b/Lang/Java/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Magic-squares-of-odd-order b/Lang/Java/Magic-squares-of-odd-order new file mode 120000 index 0000000000..5ab81fc3c3 --- /dev/null +++ b/Lang/Java/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Java \ No newline at end of file diff --git a/Lang/Java/Make-directory-path b/Lang/Java/Make-directory-path new file mode 120000 index 0000000000..c05086159c --- /dev/null +++ b/Lang/Java/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Java \ No newline at end of file diff --git a/Lang/Java/Maximum-triangle-path-sum b/Lang/Java/Maximum-triangle-path-sum new file mode 120000 index 0000000000..5b3dc25b72 --- /dev/null +++ b/Lang/Java/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Java \ No newline at end of file diff --git a/Lang/Java/Move-to-front-algorithm b/Lang/Java/Move-to-front-algorithm new file mode 120000 index 0000000000..c8ff8bda77 --- /dev/null +++ b/Lang/Java/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Munching-squares b/Lang/Java/Munching-squares new file mode 120000 index 0000000000..e88ff0bdc2 --- /dev/null +++ b/Lang/Java/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Java \ No newline at end of file diff --git a/Lang/Java/Narcissistic-decimal-number b/Lang/Java/Narcissistic-decimal-number new file mode 120000 index 0000000000..99680f5838 --- /dev/null +++ b/Lang/Java/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Java \ No newline at end of file diff --git a/Lang/Java/Nth b/Lang/Java/Nth new file mode 120000 index 0000000000..c5c563193d --- /dev/null +++ b/Lang/Java/Nth @@ -0,0 +1 @@ +../../Task/Nth/Java \ No newline at end of file diff --git a/Lang/Java/Odd-word-problem b/Lang/Java/Odd-word-problem new file mode 120000 index 0000000000..fadc5bcf1b --- /dev/null +++ b/Lang/Java/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Java \ No newline at end of file diff --git a/Lang/Java/Old-lady-swallowed-a-fly b/Lang/Java/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..93fdc4dbeb --- /dev/null +++ b/Lang/Java/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Java \ No newline at end of file diff --git a/Lang/Java/Order-disjoint-list-items b/Lang/Java/Order-disjoint-list-items new file mode 120000 index 0000000000..850b070381 --- /dev/null +++ b/Lang/Java/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Java \ No newline at end of file diff --git a/Lang/Java/Parse-an-IP-Address b/Lang/Java/Parse-an-IP-Address new file mode 120000 index 0000000000..5534ddad96 --- /dev/null +++ b/Lang/Java/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Java \ No newline at end of file diff --git a/Lang/Java/Penneys-game b/Lang/Java/Penneys-game new file mode 120000 index 0000000000..b88d31c705 --- /dev/null +++ b/Lang/Java/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Java \ No newline at end of file diff --git a/Lang/Java/Permutations-Rank-of-a-permutation b/Lang/Java/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..62ff10d0a3 --- /dev/null +++ b/Lang/Java/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Java \ No newline at end of file diff --git a/Lang/Java/Pernicious-numbers b/Lang/Java/Pernicious-numbers new file mode 120000 index 0000000000..ddf5e13b4b --- /dev/null +++ b/Lang/Java/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Phrase-reversals b/Lang/Java/Phrase-reversals new file mode 120000 index 0000000000..6be6cc96e6 --- /dev/null +++ b/Lang/Java/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Java \ No newline at end of file diff --git a/Lang/Java/Quickselect-algorithm b/Lang/Java/Quickselect-algorithm new file mode 120000 index 0000000000..d1651b89d2 --- /dev/null +++ b/Lang/Java/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Ranking-methods b/Lang/Java/Ranking-methods new file mode 120000 index 0000000000..997cd57482 --- /dev/null +++ b/Lang/Java/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Java \ No newline at end of file diff --git a/Lang/Java/Rep-string b/Lang/Java/Rep-string new file mode 120000 index 0000000000..4d0d14dd33 --- /dev/null +++ b/Lang/Java/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Java \ No newline at end of file diff --git a/Lang/Java/Reverse-words-in-a-string b/Lang/Java/Reverse-words-in-a-string new file mode 120000 index 0000000000..85f3d0ddcd --- /dev/null +++ b/Lang/Java/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Java \ No newline at end of file diff --git a/Lang/Java/Semiprime b/Lang/Java/Semiprime new file mode 120000 index 0000000000..5af34453e0 --- /dev/null +++ b/Lang/Java/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Java \ No newline at end of file diff --git a/Lang/Java/Sparkline-in-unicode b/Lang/Java/Sparkline-in-unicode new file mode 120000 index 0000000000..fb704756af --- /dev/null +++ b/Lang/Java/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Java \ No newline at end of file diff --git a/Lang/Java/State-name-puzzle b/Lang/Java/State-name-puzzle new file mode 120000 index 0000000000..074ea3c7a0 --- /dev/null +++ b/Lang/Java/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Java \ No newline at end of file diff --git a/Lang/Java/Stern-Brocot-sequence b/Lang/Java/Stern-Brocot-sequence new file mode 120000 index 0000000000..4efcf3fcfd --- /dev/null +++ b/Lang/Java/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Java \ No newline at end of file diff --git a/Lang/Java/String-append b/Lang/Java/String-append new file mode 120000 index 0000000000..977c1973c7 --- /dev/null +++ b/Lang/Java/String-append @@ -0,0 +1 @@ +../../Task/String-append/Java \ No newline at end of file diff --git a/Lang/Java/String-matching b/Lang/Java/String-matching new file mode 120000 index 0000000000..a853a60049 --- /dev/null +++ b/Lang/Java/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Java \ No newline at end of file diff --git a/Lang/Java/String-prepend b/Lang/Java/String-prepend new file mode 120000 index 0000000000..bd244c9c51 --- /dev/null +++ b/Lang/Java/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Java \ No newline at end of file diff --git a/Lang/Java/Sum-multiples-of-3-and-5 b/Lang/Java/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..27541ceacc --- /dev/null +++ b/Lang/Java/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Java \ No newline at end of file diff --git a/Lang/Java/The-ISAAC-Cipher b/Lang/Java/The-ISAAC-Cipher new file mode 120000 index 0000000000..b8fba1d087 --- /dev/null +++ b/Lang/Java/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Java \ No newline at end of file diff --git a/Lang/Java/The-Twelve-Days-of-Christmas b/Lang/Java/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..27c1a52847 --- /dev/null +++ b/Lang/Java/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Java \ No newline at end of file diff --git a/Lang/Java/Ulam-spiral--for-primes- b/Lang/Java/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..695f6f4b64 --- /dev/null +++ b/Lang/Java/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Java \ No newline at end of file diff --git a/Lang/Java/Vogels-approximation-method b/Lang/Java/Vogels-approximation-method new file mode 120000 index 0000000000..28470d8f01 --- /dev/null +++ b/Lang/Java/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Java \ No newline at end of file diff --git a/Lang/Java/World-Cup-group-stage b/Lang/Java/World-Cup-group-stage new file mode 120000 index 0000000000..d7d9576773 --- /dev/null +++ b/Lang/Java/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Java \ No newline at end of file diff --git a/Lang/Java/Zero-to-the-zero-power b/Lang/Java/Zero-to-the-zero-power new file mode 120000 index 0000000000..9e23ed0b8c --- /dev/null +++ b/Lang/Java/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Java \ No newline at end of file diff --git a/Lang/Java/Zhang-Suen-thinning-algorithm b/Lang/Java/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..b9305ce629 --- /dev/null +++ b/Lang/Java/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Java \ No newline at end of file diff --git a/Lang/JavaScript/9-billion-names-of-God-the-integer b/Lang/JavaScript/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..49112dfb19 --- /dev/null +++ b/Lang/JavaScript/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/ABC-Problem b/Lang/JavaScript/ABC-Problem new file mode 120000 index 0000000000..911953e53b --- /dev/null +++ b/Lang/JavaScript/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/AKS-test-for-primes b/Lang/JavaScript/AKS-test-for-primes new file mode 120000 index 0000000000..5b28db7567 --- /dev/null +++ b/Lang/JavaScript/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Amb b/Lang/JavaScript/Amb new file mode 120000 index 0000000000..468b13d07f --- /dev/null +++ b/Lang/JavaScript/Amb @@ -0,0 +1 @@ +../../Task/Amb/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Catamorphism b/Lang/JavaScript/Catamorphism new file mode 120000 index 0000000000..15b23471f3 --- /dev/null +++ b/Lang/JavaScript/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Closures-Value-capture b/Lang/JavaScript/Closures-Value-capture new file mode 120000 index 0000000000..f6c654d079 --- /dev/null +++ b/Lang/JavaScript/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Comma-quibbling b/Lang/JavaScript/Comma-quibbling new file mode 120000 index 0000000000..f5e0ba5c6a --- /dev/null +++ b/Lang/JavaScript/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Currying b/Lang/JavaScript/Currying new file mode 120000 index 0000000000..bba78289df --- /dev/null +++ b/Lang/JavaScript/Currying @@ -0,0 +1 @@ +../../Task/Currying/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Draw-a-clock b/Lang/JavaScript/Draw-a-clock new file mode 120000 index 0000000000..c0cd3b8672 --- /dev/null +++ b/Lang/JavaScript/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/File-input-output b/Lang/JavaScript/File-input-output new file mode 120000 index 0000000000..da29042f90 --- /dev/null +++ b/Lang/JavaScript/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Fractran b/Lang/JavaScript/Fractran new file mode 120000 index 0000000000..9acc8dc0cc --- /dev/null +++ b/Lang/JavaScript/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Generate-lower-case-ASCII-alphabet b/Lang/JavaScript/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..f821dfe998 --- /dev/null +++ b/Lang/JavaScript/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Heronian-triangles b/Lang/JavaScript/Heronian-triangles new file mode 120000 index 0000000000..027e1cade4 --- /dev/null +++ b/Lang/JavaScript/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Longest-increasing-subsequence b/Lang/JavaScript/Longest-increasing-subsequence new file mode 120000 index 0000000000..5fc525f084 --- /dev/null +++ b/Lang/JavaScript/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Make-directory-path b/Lang/JavaScript/Make-directory-path new file mode 120000 index 0000000000..7f207a3e0c --- /dev/null +++ b/Lang/JavaScript/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Move-to-front-algorithm b/Lang/JavaScript/Move-to-front-algorithm new file mode 120000 index 0000000000..7f6f54991a --- /dev/null +++ b/Lang/JavaScript/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Runge-Kutta-method b/Lang/JavaScript/Runge-Kutta-method new file mode 120000 index 0000000000..0d597b7a71 --- /dev/null +++ b/Lang/JavaScript/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-append b/Lang/JavaScript/String-append new file mode 120000 index 0000000000..99ceade32f --- /dev/null +++ b/Lang/JavaScript/String-append @@ -0,0 +1 @@ +../../Task/String-append/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-matching b/Lang/JavaScript/String-matching new file mode 120000 index 0000000000..455c6debf2 --- /dev/null +++ b/Lang/JavaScript/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/The-Twelve-Days-of-Christmas b/Lang/JavaScript/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..605d992a91 --- /dev/null +++ b/Lang/JavaScript/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Zero-to-the-zero-power b/Lang/JavaScript/Zero-to-the-zero-power new file mode 120000 index 0000000000..1ba361b9ad --- /dev/null +++ b/Lang/JavaScript/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/JavaScript \ No newline at end of file diff --git a/Lang/Julia/ABC-Problem b/Lang/Julia/ABC-Problem new file mode 120000 index 0000000000..ad18242335 --- /dev/null +++ b/Lang/Julia/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Almost-prime b/Lang/Julia/Almost-prime new file mode 120000 index 0000000000..367f6b481d --- /dev/null +++ b/Lang/Julia/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Julia \ No newline at end of file diff --git a/Lang/Julia/Benfords-law b/Lang/Julia/Benfords-law new file mode 120000 index 0000000000..802ae943f2 --- /dev/null +++ b/Lang/Julia/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Julia \ No newline at end of file diff --git a/Lang/Julia/Casting-out-nines b/Lang/Julia/Casting-out-nines new file mode 120000 index 0000000000..b1039017dc --- /dev/null +++ b/Lang/Julia/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Julia \ No newline at end of file diff --git a/Lang/Julia/Closures-Value-capture b/Lang/Julia/Closures-Value-capture new file mode 120000 index 0000000000..e1a0dd3276 --- /dev/null +++ b/Lang/Julia/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Julia \ No newline at end of file diff --git a/Lang/Julia/Comma-quibbling b/Lang/Julia/Comma-quibbling new file mode 120000 index 0000000000..775d273a38 --- /dev/null +++ b/Lang/Julia/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Julia \ No newline at end of file diff --git a/Lang/Julia/Conjugate-transpose b/Lang/Julia/Conjugate-transpose new file mode 120000 index 0000000000..a10795a052 --- /dev/null +++ b/Lang/Julia/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Julia \ No newline at end of file diff --git a/Lang/Julia/Convert-decimal-number-to-rational b/Lang/Julia/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..3f465bb1f9 --- /dev/null +++ b/Lang/Julia/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Julia \ No newline at end of file diff --git a/Lang/Julia/File-input-output b/Lang/Julia/File-input-output new file mode 120000 index 0000000000..7340c55bb0 --- /dev/null +++ b/Lang/Julia/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Julia \ No newline at end of file diff --git a/Lang/Julia/Gaussian-elimination b/Lang/Julia/Gaussian-elimination new file mode 120000 index 0000000000..6f00b6d183 --- /dev/null +++ b/Lang/Julia/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Julia \ No newline at end of file diff --git a/Lang/Julia/Generate-lower-case-ASCII-alphabet b/Lang/Julia/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..3a72021875 --- /dev/null +++ b/Lang/Julia/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Julia \ No newline at end of file diff --git a/Lang/Julia/Iterated-digits-squaring b/Lang/Julia/Iterated-digits-squaring new file mode 120000 index 0000000000..eb7a0b58fd --- /dev/null +++ b/Lang/Julia/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Julia \ No newline at end of file diff --git a/Lang/Julia/Left-factorials b/Lang/Julia/Left-factorials new file mode 120000 index 0000000000..6af24c2b36 --- /dev/null +++ b/Lang/Julia/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Julia \ No newline at end of file diff --git a/Lang/Julia/Reverse-words-in-a-string b/Lang/Julia/Reverse-words-in-a-string new file mode 120000 index 0000000000..0744f788e2 --- /dev/null +++ b/Lang/Julia/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Runge-Kutta-method b/Lang/Julia/Runge-Kutta-method new file mode 120000 index 0000000000..eefbcbd459 --- /dev/null +++ b/Lang/Julia/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Julia \ No newline at end of file diff --git a/Lang/Julia/Semiprime b/Lang/Julia/Semiprime new file mode 120000 index 0000000000..c2dc69dc10 --- /dev/null +++ b/Lang/Julia/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Julia \ No newline at end of file diff --git a/Lang/Julia/String-append b/Lang/Julia/String-append new file mode 120000 index 0000000000..8481dd9eb0 --- /dev/null +++ b/Lang/Julia/String-append @@ -0,0 +1 @@ +../../Task/String-append/Julia \ No newline at end of file diff --git a/Lang/Julia/String-matching b/Lang/Julia/String-matching new file mode 120000 index 0000000000..59e82fde16 --- /dev/null +++ b/Lang/Julia/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Julia \ No newline at end of file diff --git a/Lang/Julia/String-prepend b/Lang/Julia/String-prepend new file mode 120000 index 0000000000..355c64561d --- /dev/null +++ b/Lang/Julia/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Julia \ No newline at end of file diff --git a/Lang/Julia/Sum-multiples-of-3-and-5 b/Lang/Julia/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..55c17bfc00 --- /dev/null +++ b/Lang/Julia/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Julia \ No newline at end of file diff --git a/Lang/Julia/Total-circles-area b/Lang/Julia/Total-circles-area new file mode 120000 index 0000000000..98b9e92b33 --- /dev/null +++ b/Lang/Julia/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Julia \ No newline at end of file diff --git a/Lang/K/File-input-output b/Lang/K/File-input-output new file mode 120000 index 0000000000..cdb9ccbb30 --- /dev/null +++ b/Lang/K/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/K \ No newline at end of file diff --git a/Lang/K/String-matching b/Lang/K/String-matching new file mode 120000 index 0000000000..c42411e5f2 --- /dev/null +++ b/Lang/K/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/K \ No newline at end of file diff --git a/Lang/LOLCODE/Catamorphism b/Lang/LOLCODE/Catamorphism new file mode 120000 index 0000000000..d34d5e1678 --- /dev/null +++ b/Lang/LOLCODE/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/The-Twelve-Days-of-Christmas b/Lang/LOLCODE/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..47b1587171 --- /dev/null +++ b/Lang/LOLCODE/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/LOLCODE \ No newline at end of file diff --git a/Lang/Lang5/File-input-output b/Lang/Lang5/File-input-output new file mode 120000 index 0000000000..78e4360ca3 --- /dev/null +++ b/Lang/Lang5/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/String-matching b/Lang/Lang5/String-matching new file mode 120000 index 0000000000..3b022ef28e --- /dev/null +++ b/Lang/Lang5/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Lang5 \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Benfords-law b/Lang/Liberty-BASIC/Benfords-law new file mode 120000 index 0000000000..c7b89d3064 --- /dev/null +++ b/Lang/Liberty-BASIC/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Convert-decimal-number-to-rational b/Lang/Liberty-BASIC/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..e8f4be6fa5 --- /dev/null +++ b/Lang/Liberty-BASIC/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Draw-a-clock b/Lang/Liberty-BASIC/Draw-a-clock new file mode 120000 index 0000000000..faf542e3e1 --- /dev/null +++ b/Lang/Liberty-BASIC/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/File-input-output b/Lang/Liberty-BASIC/File-input-output new file mode 120000 index 0000000000..1b6f9d1fc1 --- /dev/null +++ b/Lang/Liberty-BASIC/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Munching-squares b/Lang/Liberty-BASIC/Munching-squares new file mode 120000 index 0000000000..71696dd5f5 --- /dev/null +++ b/Lang/Liberty-BASIC/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Statistics-Basic b/Lang/Liberty-BASIC/Statistics-Basic new file mode 120000 index 0000000000..47366e28bc --- /dev/null +++ b/Lang/Liberty-BASIC/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/String-matching b/Lang/Liberty-BASIC/String-matching new file mode 120000 index 0000000000..9bf62a50e3 --- /dev/null +++ b/Lang/Liberty-BASIC/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Limbo/Sum-multiples-of-3-and-5 b/Lang/Limbo/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..2153c4650f --- /dev/null +++ b/Lang/Limbo/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Limbo \ No newline at end of file diff --git a/Lang/Lisaac/File-input-output b/Lang/Lisaac/File-input-output new file mode 120000 index 0000000000..ae6b8e449e --- /dev/null +++ b/Lang/Lisaac/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Lisaac \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Draw-a-clock b/Lang/Locomotive-Basic/Draw-a-clock new file mode 120000 index 0000000000..1362e3c041 --- /dev/null +++ b/Lang/Locomotive-Basic/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Hello-world-Newbie b/Lang/Locomotive-Basic/Hello-world-Newbie new file mode 120000 index 0000000000..04f92e8eab --- /dev/null +++ b/Lang/Locomotive-Basic/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Logo/ABC-Problem b/Lang/Logo/ABC-Problem new file mode 120000 index 0000000000..451bbb55c4 --- /dev/null +++ b/Lang/Logo/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Logo \ No newline at end of file diff --git a/Lang/Logo/Comma-quibbling b/Lang/Logo/Comma-quibbling new file mode 120000 index 0000000000..1cacf9aac6 --- /dev/null +++ b/Lang/Logo/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Logo \ No newline at end of file diff --git a/Lang/Logo/Fibonacci-word-fractal b/Lang/Logo/Fibonacci-word-fractal new file mode 120000 index 0000000000..83ca23b35e --- /dev/null +++ b/Lang/Logo/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Logo \ No newline at end of file diff --git a/Lang/Logo/File-input-output b/Lang/Logo/File-input-output new file mode 120000 index 0000000000..26228ff370 --- /dev/null +++ b/Lang/Logo/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Logo \ No newline at end of file diff --git a/Lang/Logo/Generate-lower-case-ASCII-alphabet b/Lang/Logo/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..b6c6d52c51 --- /dev/null +++ b/Lang/Logo/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Logo \ No newline at end of file diff --git a/Lang/Logo/String-matching b/Lang/Logo/String-matching new file mode 120000 index 0000000000..03a01a0abf --- /dev/null +++ b/Lang/Logo/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Logo \ No newline at end of file diff --git a/Lang/Logo/The-Twelve-Days-of-Christmas b/Lang/Logo/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..6d0f432ea4 --- /dev/null +++ b/Lang/Logo/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Logo \ No newline at end of file diff --git a/Lang/Logtalk/Catamorphism b/Lang/Logtalk/Catamorphism new file mode 120000 index 0000000000..4564450adc --- /dev/null +++ b/Lang/Logtalk/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Closures-Value-capture b/Lang/Logtalk/Closures-Value-capture new file mode 120000 index 0000000000..4929765112 --- /dev/null +++ b/Lang/Logtalk/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Logtalk \ No newline at end of file diff --git a/Lang/Lua/Amb b/Lang/Lua/Amb new file mode 120000 index 0000000000..88d825375d --- /dev/null +++ b/Lang/Lua/Amb @@ -0,0 +1 @@ +../../Task/Amb/Lua \ No newline at end of file diff --git a/Lang/Lua/Benfords-law b/Lang/Lua/Benfords-law new file mode 120000 index 0000000000..f02de17c2d --- /dev/null +++ b/Lang/Lua/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Lua \ No newline at end of file diff --git a/Lang/Lua/CSV-data-manipulation b/Lang/Lua/CSV-data-manipulation new file mode 120000 index 0000000000..d3b21f0f92 --- /dev/null +++ b/Lang/Lua/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Lua \ No newline at end of file diff --git a/Lang/Lua/Closures-Value-capture b/Lang/Lua/Closures-Value-capture new file mode 120000 index 0000000000..405855d202 --- /dev/null +++ b/Lang/Lua/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Lua \ No newline at end of file diff --git a/Lang/Lua/File-input-output b/Lang/Lua/File-input-output new file mode 120000 index 0000000000..f26f35c1d4 --- /dev/null +++ b/Lang/Lua/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Lua \ No newline at end of file diff --git a/Lang/Lua/Iterated-digits-squaring b/Lang/Lua/Iterated-digits-squaring new file mode 120000 index 0000000000..7780456a84 --- /dev/null +++ b/Lang/Lua/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Lua \ No newline at end of file diff --git a/Lang/Lua/Longest-increasing-subsequence b/Lang/Lua/Longest-increasing-subsequence new file mode 120000 index 0000000000..04b3823c68 --- /dev/null +++ b/Lang/Lua/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Lua \ No newline at end of file diff --git a/Lang/Lua/Reverse-words-in-a-string b/Lang/Lua/Reverse-words-in-a-string new file mode 120000 index 0000000000..98525df98b --- /dev/null +++ b/Lang/Lua/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Lua \ No newline at end of file diff --git a/Lang/Lua/String-matching b/Lang/Lua/String-matching new file mode 120000 index 0000000000..2fe0857a6c --- /dev/null +++ b/Lang/Lua/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Lua \ No newline at end of file diff --git a/Lang/Lua/String-prepend b/Lang/Lua/String-prepend new file mode 120000 index 0000000000..a099d53eaa --- /dev/null +++ b/Lang/Lua/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Lua \ No newline at end of file diff --git a/Lang/Lua/The-Twelve-Days-of-Christmas b/Lang/Lua/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..e35a218802 --- /dev/null +++ b/Lang/Lua/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Lua \ No newline at end of file diff --git a/Lang/MATLAB/ABC-Problem b/Lang/MATLAB/ABC-Problem new file mode 120000 index 0000000000..95e424918d --- /dev/null +++ b/Lang/MATLAB/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Append-a-record-to-the-end-of-a-text-file b/Lang/MATLAB/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..b13bc7dc69 --- /dev/null +++ b/Lang/MATLAB/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/CSV-data-manipulation b/Lang/MATLAB/CSV-data-manipulation new file mode 120000 index 0000000000..c04f12bed9 --- /dev/null +++ b/Lang/MATLAB/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Catalan-numbers-Pascals-triangle b/Lang/MATLAB/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..ab540af8d0 --- /dev/null +++ b/Lang/MATLAB/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Convert-decimal-number-to-rational b/Lang/MATLAB/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..4cee297a5a --- /dev/null +++ b/Lang/MATLAB/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Draw-a-clock b/Lang/MATLAB/Draw-a-clock new file mode 120000 index 0000000000..d1184918b6 --- /dev/null +++ b/Lang/MATLAB/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Flipping-bits-game b/Lang/MATLAB/Flipping-bits-game new file mode 120000 index 0000000000..d30463ee63 --- /dev/null +++ b/Lang/MATLAB/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Gaussian-elimination b/Lang/MATLAB/Gaussian-elimination new file mode 120000 index 0000000000..52dea23f01 --- /dev/null +++ b/Lang/MATLAB/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/IBAN b/Lang/MATLAB/IBAN new file mode 120000 index 0000000000..d79b299e31 --- /dev/null +++ b/Lang/MATLAB/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Move-to-front-algorithm b/Lang/MATLAB/Move-to-front-algorithm new file mode 120000 index 0000000000..a16b6312e3 --- /dev/null +++ b/Lang/MATLAB/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Munching-squares b/Lang/MATLAB/Munching-squares new file mode 120000 index 0000000000..c5d9bc48d3 --- /dev/null +++ b/Lang/MATLAB/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Narcissistic-decimal-number b/Lang/MATLAB/Narcissistic-decimal-number new file mode 120000 index 0000000000..84d0c7c16e --- /dev/null +++ b/Lang/MATLAB/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Nth b/Lang/MATLAB/Nth new file mode 120000 index 0000000000..c4d29462d3 --- /dev/null +++ b/Lang/MATLAB/Nth @@ -0,0 +1 @@ +../../Task/Nth/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Reverse-words-in-a-string b/Lang/MATLAB/Reverse-words-in-a-string new file mode 120000 index 0000000000..3591b1aa34 --- /dev/null +++ b/Lang/MATLAB/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Runge-Kutta-method b/Lang/MATLAB/Runge-Kutta-method new file mode 120000 index 0000000000..8cf6271e96 --- /dev/null +++ b/Lang/MATLAB/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Statistics-Basic b/Lang/MATLAB/Statistics-Basic new file mode 120000 index 0000000000..904edc10de --- /dev/null +++ b/Lang/MATLAB/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/String-matching b/Lang/MATLAB/String-matching new file mode 120000 index 0000000000..225ee64759 --- /dev/null +++ b/Lang/MATLAB/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sum-multiples-of-3-and-5 b/Lang/MATLAB/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3e7a1f58da --- /dev/null +++ b/Lang/MATLAB/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Total-circles-area b/Lang/MATLAB/Total-circles-area new file mode 120000 index 0000000000..5f4d4d2f2e --- /dev/null +++ b/Lang/MATLAB/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/MATLAB \ No newline at end of file diff --git a/Lang/MAXScript/ABC-Problem b/Lang/MAXScript/ABC-Problem new file mode 120000 index 0000000000..901baea91a --- /dev/null +++ b/Lang/MAXScript/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Comma-quibbling b/Lang/MAXScript/Comma-quibbling new file mode 120000 index 0000000000..8e4a5fd50e --- /dev/null +++ b/Lang/MAXScript/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/File-input-output b/Lang/MAXScript/File-input-output new file mode 120000 index 0000000000..f087ab6065 --- /dev/null +++ b/Lang/MAXScript/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/MAXScript \ No newline at end of file diff --git a/Lang/Maple/AKS-test-for-primes b/Lang/Maple/AKS-test-for-primes new file mode 120000 index 0000000000..03b9d4f3e4 --- /dev/null +++ b/Lang/Maple/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Maple \ No newline at end of file diff --git a/Lang/Maple/Bernoulli-numbers b/Lang/Maple/Bernoulli-numbers new file mode 120000 index 0000000000..a7901d3c35 --- /dev/null +++ b/Lang/Maple/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Maple \ No newline at end of file diff --git a/Lang/Maple/CSV-data-manipulation b/Lang/Maple/CSV-data-manipulation new file mode 120000 index 0000000000..8e28d6b7b1 --- /dev/null +++ b/Lang/Maple/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Maple \ No newline at end of file diff --git a/Lang/Maple/Catamorphism b/Lang/Maple/Catamorphism new file mode 120000 index 0000000000..a7c8aa3906 --- /dev/null +++ b/Lang/Maple/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Maple \ No newline at end of file diff --git a/Lang/Maple/Chinese-remainder-theorem b/Lang/Maple/Chinese-remainder-theorem new file mode 120000 index 0000000000..20af2d8bd4 --- /dev/null +++ b/Lang/Maple/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Maple \ No newline at end of file diff --git a/Lang/Maple/Closures-Value-capture b/Lang/Maple/Closures-Value-capture new file mode 120000 index 0000000000..fa63615065 --- /dev/null +++ b/Lang/Maple/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Maple \ No newline at end of file diff --git a/Lang/Maple/Comma-quibbling b/Lang/Maple/Comma-quibbling new file mode 120000 index 0000000000..820e1a1c81 --- /dev/null +++ b/Lang/Maple/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Maple \ No newline at end of file diff --git a/Lang/Maple/Conjugate-transpose b/Lang/Maple/Conjugate-transpose new file mode 120000 index 0000000000..8812e09532 --- /dev/null +++ b/Lang/Maple/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Maple \ No newline at end of file diff --git a/Lang/Maple/Convert-decimal-number-to-rational b/Lang/Maple/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..edfb829e3d --- /dev/null +++ b/Lang/Maple/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Maple \ No newline at end of file diff --git a/Lang/Maple/Rep-string b/Lang/Maple/Rep-string new file mode 120000 index 0000000000..da8aeaa341 --- /dev/null +++ b/Lang/Maple/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Maple \ No newline at end of file diff --git a/Lang/Maple/String-matching b/Lang/Maple/String-matching new file mode 120000 index 0000000000..0a2bd2e159 --- /dev/null +++ b/Lang/Maple/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Maple \ No newline at end of file diff --git a/Lang/Maple/Sum-multiples-of-3-and-5 b/Lang/Maple/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3177aae93e --- /dev/null +++ b/Lang/Maple/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Maple \ No newline at end of file diff --git a/Lang/Maple/Zero-to-the-zero-power b/Lang/Maple/Zero-to-the-zero-power new file mode 120000 index 0000000000..39af8fd572 --- /dev/null +++ b/Lang/Maple/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Maple \ No newline at end of file diff --git a/Lang/Mathematica/9-billion-names-of-God-the-integer b/Lang/Mathematica/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..064a2840e5 --- /dev/null +++ b/Lang/Mathematica/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/ABC-Problem b/Lang/Mathematica/ABC-Problem new file mode 120000 index 0000000000..71890e718f --- /dev/null +++ b/Lang/Mathematica/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/AKS-test-for-primes b/Lang/Mathematica/AKS-test-for-primes new file mode 120000 index 0000000000..0f947890b7 --- /dev/null +++ b/Lang/Mathematica/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Abundant,-deficient-and-perfect-number-classifications b/Lang/Mathematica/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..294be92d9d --- /dev/null +++ b/Lang/Mathematica/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Almost-prime b/Lang/Mathematica/Almost-prime new file mode 120000 index 0000000000..3151c6a9b7 --- /dev/null +++ b/Lang/Mathematica/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Amb b/Lang/Mathematica/Amb new file mode 120000 index 0000000000..0da1d49a91 --- /dev/null +++ b/Lang/Mathematica/Amb @@ -0,0 +1 @@ +../../Task/Amb/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Amicable-pairs b/Lang/Mathematica/Amicable-pairs new file mode 120000 index 0000000000..7078edf427 --- /dev/null +++ b/Lang/Mathematica/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Mathematica/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..b6e827db4f --- /dev/null +++ b/Lang/Mathematica/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Benfords-law b/Lang/Mathematica/Benfords-law new file mode 120000 index 0000000000..623ee1d326 --- /dev/null +++ b/Lang/Mathematica/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Bernoulli-numbers b/Lang/Mathematica/Bernoulli-numbers new file mode 120000 index 0000000000..8c62892e24 --- /dev/null +++ b/Lang/Mathematica/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/CSV-data-manipulation b/Lang/Mathematica/CSV-data-manipulation new file mode 120000 index 0000000000..afc1102fed --- /dev/null +++ b/Lang/Mathematica/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Catalan-numbers-Pascals-triangle b/Lang/Mathematica/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..4c1cc5b34e --- /dev/null +++ b/Lang/Mathematica/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Catamorphism b/Lang/Mathematica/Catamorphism new file mode 120000 index 0000000000..f629f66120 --- /dev/null +++ b/Lang/Mathematica/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Chinese-remainder-theorem b/Lang/Mathematica/Chinese-remainder-theorem new file mode 120000 index 0000000000..9fc21603f2 --- /dev/null +++ b/Lang/Mathematica/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Closures-Value-capture b/Lang/Mathematica/Closures-Value-capture new file mode 120000 index 0000000000..c59191890c --- /dev/null +++ b/Lang/Mathematica/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Combinations-and-permutations b/Lang/Mathematica/Combinations-and-permutations new file mode 120000 index 0000000000..8982a6d483 --- /dev/null +++ b/Lang/Mathematica/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Comma-quibbling b/Lang/Mathematica/Comma-quibbling new file mode 120000 index 0000000000..d8ead722ed --- /dev/null +++ b/Lang/Mathematica/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Conjugate-transpose b/Lang/Mathematica/Conjugate-transpose new file mode 120000 index 0000000000..b54ed5881b --- /dev/null +++ b/Lang/Mathematica/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Convert-decimal-number-to-rational b/Lang/Mathematica/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..586ab4b0ec --- /dev/null +++ b/Lang/Mathematica/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Digital-root-Multiplicative-digital-root b/Lang/Mathematica/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..419e5eb837 --- /dev/null +++ b/Lang/Mathematica/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Draw-a-clock b/Lang/Mathematica/Draw-a-clock new file mode 120000 index 0000000000..662c86b8d2 --- /dev/null +++ b/Lang/Mathematica/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Extensible-prime-generator b/Lang/Mathematica/Extensible-prime-generator new file mode 120000 index 0000000000..2959c7464c --- /dev/null +++ b/Lang/Mathematica/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Fibonacci-word b/Lang/Mathematica/Fibonacci-word new file mode 120000 index 0000000000..ba7becfb31 --- /dev/null +++ b/Lang/Mathematica/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Fibonacci-word-fractal b/Lang/Mathematica/Fibonacci-word-fractal new file mode 120000 index 0000000000..4f048850c4 --- /dev/null +++ b/Lang/Mathematica/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/File-input-output b/Lang/Mathematica/File-input-output new file mode 120000 index 0000000000..3d1bc63efa --- /dev/null +++ b/Lang/Mathematica/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Find-the-last-Sunday-of-each-month b/Lang/Mathematica/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..cfe0c7f6ac --- /dev/null +++ b/Lang/Mathematica/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Fractran b/Lang/Mathematica/Fractran new file mode 120000 index 0000000000..c123b6f531 --- /dev/null +++ b/Lang/Mathematica/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Gaussian-elimination b/Lang/Mathematica/Gaussian-elimination new file mode 120000 index 0000000000..fd96cc7840 --- /dev/null +++ b/Lang/Mathematica/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Generate-lower-case-ASCII-alphabet b/Lang/Mathematica/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d4f31b565b --- /dev/null +++ b/Lang/Mathematica/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Hash-join b/Lang/Mathematica/Hash-join new file mode 120000 index 0000000000..d04a8dd562 --- /dev/null +++ b/Lang/Mathematica/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Hickerson-series-of-almost-integers b/Lang/Mathematica/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..9f6028ddca --- /dev/null +++ b/Lang/Mathematica/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/IBAN b/Lang/Mathematica/IBAN new file mode 120000 index 0000000000..c22efea29b --- /dev/null +++ b/Lang/Mathematica/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Iterated-digits-squaring b/Lang/Mathematica/Iterated-digits-squaring new file mode 120000 index 0000000000..df0c581cb1 --- /dev/null +++ b/Lang/Mathematica/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Left-factorials b/Lang/Mathematica/Left-factorials new file mode 120000 index 0000000000..c0e86fa5ff --- /dev/null +++ b/Lang/Mathematica/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Longest-increasing-subsequence b/Lang/Mathematica/Longest-increasing-subsequence new file mode 120000 index 0000000000..79dbfc410d --- /dev/null +++ b/Lang/Mathematica/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Ludic-numbers b/Lang/Mathematica/Ludic-numbers new file mode 120000 index 0000000000..6c06a5f749 --- /dev/null +++ b/Lang/Mathematica/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Magic-squares-of-odd-order b/Lang/Mathematica/Magic-squares-of-odd-order new file mode 120000 index 0000000000..ca36c92094 --- /dev/null +++ b/Lang/Mathematica/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Make-directory-path b/Lang/Mathematica/Make-directory-path new file mode 120000 index 0000000000..39760a0515 --- /dev/null +++ b/Lang/Mathematica/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Maximum-triangle-path-sum b/Lang/Mathematica/Maximum-triangle-path-sum new file mode 120000 index 0000000000..071ce666a1 --- /dev/null +++ b/Lang/Mathematica/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Move-to-front-algorithm b/Lang/Mathematica/Move-to-front-algorithm new file mode 120000 index 0000000000..362cc3d4a9 --- /dev/null +++ b/Lang/Mathematica/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Munching-squares b/Lang/Mathematica/Munching-squares new file mode 120000 index 0000000000..25b3164de9 --- /dev/null +++ b/Lang/Mathematica/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Nth b/Lang/Mathematica/Nth new file mode 120000 index 0000000000..49eeb660e6 --- /dev/null +++ b/Lang/Mathematica/Nth @@ -0,0 +1 @@ +../../Task/Nth/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Paraffins b/Lang/Mathematica/Paraffins new file mode 120000 index 0000000000..90a280c56f --- /dev/null +++ b/Lang/Mathematica/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Permutations-Rank-of-a-permutation b/Lang/Mathematica/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..5fac2fd5e5 --- /dev/null +++ b/Lang/Mathematica/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Pernicious-numbers b/Lang/Mathematica/Pernicious-numbers new file mode 120000 index 0000000000..b31bfda78d --- /dev/null +++ b/Lang/Mathematica/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Phrase-reversals b/Lang/Mathematica/Phrase-reversals new file mode 120000 index 0000000000..32b590ccc8 --- /dev/null +++ b/Lang/Mathematica/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rep-string b/Lang/Mathematica/Rep-string new file mode 120000 index 0000000000..af35600729 --- /dev/null +++ b/Lang/Mathematica/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Reverse-words-in-a-string b/Lang/Mathematica/Reverse-words-in-a-string new file mode 120000 index 0000000000..fe66c5a215 --- /dev/null +++ b/Lang/Mathematica/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Runge-Kutta-method b/Lang/Mathematica/Runge-Kutta-method new file mode 120000 index 0000000000..7765a175bf --- /dev/null +++ b/Lang/Mathematica/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Semiprime b/Lang/Mathematica/Semiprime new file mode 120000 index 0000000000..bd7ffab660 --- /dev/null +++ b/Lang/Mathematica/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sparkline-in-unicode b/Lang/Mathematica/Sparkline-in-unicode new file mode 120000 index 0000000000..3f115a3f31 --- /dev/null +++ b/Lang/Mathematica/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/State-name-puzzle b/Lang/Mathematica/State-name-puzzle new file mode 120000 index 0000000000..98c3563f9a --- /dev/null +++ b/Lang/Mathematica/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Statistics-Basic b/Lang/Mathematica/Statistics-Basic new file mode 120000 index 0000000000..5f3970f041 --- /dev/null +++ b/Lang/Mathematica/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-append b/Lang/Mathematica/String-append new file mode 120000 index 0000000000..34496abf47 --- /dev/null +++ b/Lang/Mathematica/String-append @@ -0,0 +1 @@ +../../Task/String-append/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-matching b/Lang/Mathematica/String-matching new file mode 120000 index 0000000000..a59d47f610 --- /dev/null +++ b/Lang/Mathematica/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-prepend b/Lang/Mathematica/String-prepend new file mode 120000 index 0000000000..a17abfd3d6 --- /dev/null +++ b/Lang/Mathematica/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sum-multiples-of-3-and-5 b/Lang/Mathematica/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..c277018fa7 --- /dev/null +++ b/Lang/Mathematica/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/The-Twelve-Days-of-Christmas b/Lang/Mathematica/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..5c6cc2bbc2 --- /dev/null +++ b/Lang/Mathematica/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Total-circles-area b/Lang/Mathematica/Total-circles-area new file mode 120000 index 0000000000..d19f6f0351 --- /dev/null +++ b/Lang/Mathematica/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Unix-ls b/Lang/Mathematica/Unix-ls new file mode 120000 index 0000000000..9896f7c289 --- /dev/null +++ b/Lang/Mathematica/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Zero-to-the-zero-power b/Lang/Mathematica/Zero-to-the-zero-power new file mode 120000 index 0000000000..75d3a15443 --- /dev/null +++ b/Lang/Mathematica/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Zhang-Suen-thinning-algorithm b/Lang/Mathematica/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..b4e306b1bc --- /dev/null +++ b/Lang/Mathematica/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Catamorphism b/Lang/Maxima/Catamorphism new file mode 120000 index 0000000000..56c506399f --- /dev/null +++ b/Lang/Maxima/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Circles-of-given-radius-through-two-points b/Lang/Maxima/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..28efaa2188 --- /dev/null +++ b/Lang/Maxima/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Magic-squares-of-odd-order b/Lang/Maxima/Magic-squares-of-odd-order new file mode 120000 index 0000000000..29286345ce --- /dev/null +++ b/Lang/Maxima/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Runge-Kutta-method b/Lang/Maxima/Runge-Kutta-method new file mode 120000 index 0000000000..cf7692dba1 --- /dev/null +++ b/Lang/Maxima/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sum-multiples-of-3-and-5 b/Lang/Maxima/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..2f01c1a8f3 --- /dev/null +++ b/Lang/Maxima/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Maxima \ No newline at end of file diff --git a/Lang/Mercury/Amb b/Lang/Mercury/Amb new file mode 120000 index 0000000000..b675232a0b --- /dev/null +++ b/Lang/Mercury/Amb @@ -0,0 +1 @@ +../../Task/Amb/Mercury \ No newline at end of file diff --git a/Lang/Mercury/File-input-output b/Lang/Mercury/File-input-output new file mode 120000 index 0000000000..67f3ab76c6 --- /dev/null +++ b/Lang/Mercury/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Generate-lower-case-ASCII-alphabet b/Lang/Mercury/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..978ccdfa07 --- /dev/null +++ b/Lang/Mercury/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Mercury \ No newline at end of file diff --git a/Lang/Mercury/String-prepend b/Lang/Mercury/String-prepend new file mode 120000 index 0000000000..35f646fd44 --- /dev/null +++ b/Lang/Mercury/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Mercury \ No newline at end of file diff --git a/Lang/Modula-3/File-input-output b/Lang/Modula-3/File-input-output new file mode 120000 index 0000000000..99dd9c210f --- /dev/null +++ b/Lang/Modula-3/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Modula-3 \ No newline at end of file diff --git a/Lang/Nemerle/Catamorphism b/Lang/Nemerle/Catamorphism new file mode 120000 index 0000000000..149d2e11fc --- /dev/null +++ b/Lang/Nemerle/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Closures-Value-capture b/Lang/Nemerle/Closures-Value-capture new file mode 120000 index 0000000000..95ad73dbe4 --- /dev/null +++ b/Lang/Nemerle/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Currying b/Lang/Nemerle/Currying new file mode 120000 index 0000000000..446a1930b4 --- /dev/null +++ b/Lang/Nemerle/Currying @@ -0,0 +1 @@ +../../Task/Currying/Nemerle \ No newline at end of file diff --git a/Lang/NetRexx/Amb b/Lang/NetRexx/Amb new file mode 120000 index 0000000000..dfd3faea2e --- /dev/null +++ b/Lang/NetRexx/Amb @@ -0,0 +1 @@ +../../Task/Amb/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Benfords-law b/Lang/NetRexx/Benfords-law new file mode 120000 index 0000000000..a3a90fde31 --- /dev/null +++ b/Lang/NetRexx/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/CSV-data-manipulation b/Lang/NetRexx/CSV-data-manipulation new file mode 120000 index 0000000000..43dd03d7c6 --- /dev/null +++ b/Lang/NetRexx/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Comma-quibbling b/Lang/NetRexx/Comma-quibbling new file mode 120000 index 0000000000..0c65dfb3e5 --- /dev/null +++ b/Lang/NetRexx/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Convert-decimal-number-to-rational b/Lang/NetRexx/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..9dc22078a3 --- /dev/null +++ b/Lang/NetRexx/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Draw-a-clock b/Lang/NetRexx/Draw-a-clock new file mode 120000 index 0000000000..6e5d8a539d --- /dev/null +++ b/Lang/NetRexx/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/File-input-output b/Lang/NetRexx/File-input-output new file mode 120000 index 0000000000..30baa19804 --- /dev/null +++ b/Lang/NetRexx/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Quickselect-algorithm b/Lang/NetRexx/Quickselect-algorithm new file mode 120000 index 0000000000..0a5a997709 --- /dev/null +++ b/Lang/NetRexx/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Rep-string b/Lang/NetRexx/Rep-string new file mode 120000 index 0000000000..0b77b7c415 --- /dev/null +++ b/Lang/NetRexx/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sparkline-in-unicode b/Lang/NetRexx/Sparkline-in-unicode new file mode 120000 index 0000000000..b39724a28d --- /dev/null +++ b/Lang/NetRexx/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-append b/Lang/NetRexx/String-append new file mode 120000 index 0000000000..65ecd1d816 --- /dev/null +++ b/Lang/NetRexx/String-append @@ -0,0 +1 @@ +../../Task/String-append/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-matching b/Lang/NetRexx/String-matching new file mode 120000 index 0000000000..dc0f21e471 --- /dev/null +++ b/Lang/NetRexx/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-prepend b/Lang/NetRexx/String-prepend new file mode 120000 index 0000000000..bd3e42a239 --- /dev/null +++ b/Lang/NetRexx/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sum-multiples-of-3-and-5 b/Lang/NetRexx/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..b838b17361 --- /dev/null +++ b/Lang/NetRexx/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Zero-to-the-zero-power b/Lang/NetRexx/Zero-to-the-zero-power new file mode 120000 index 0000000000..2a58d5df8e --- /dev/null +++ b/Lang/NetRexx/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/String-append b/Lang/NewLISP/String-append new file mode 120000 index 0000000000..7b99a2fdfe --- /dev/null +++ b/Lang/NewLISP/String-append @@ -0,0 +1 @@ +../../Task/String-append/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/String-matching b/Lang/NewLISP/String-matching new file mode 120000 index 0000000000..d04e1f8519 --- /dev/null +++ b/Lang/NewLISP/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/String-prepend b/Lang/NewLISP/String-prepend new file mode 120000 index 0000000000..057b486adc --- /dev/null +++ b/Lang/NewLISP/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/NewLISP \ No newline at end of file diff --git a/Lang/OCaml/9-billion-names-of-God-the-integer b/Lang/OCaml/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..be25c5525c --- /dev/null +++ b/Lang/OCaml/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/OCaml \ No newline at end of file diff --git a/Lang/OCaml/ABC-Problem b/Lang/OCaml/ABC-Problem new file mode 120000 index 0000000000..4c10f2deed --- /dev/null +++ b/Lang/OCaml/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Amb b/Lang/OCaml/Amb new file mode 120000 index 0000000000..3592b8ebb7 --- /dev/null +++ b/Lang/OCaml/Amb @@ -0,0 +1 @@ +../../Task/Amb/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Catamorphism b/Lang/OCaml/Catamorphism new file mode 120000 index 0000000000..9f3725f63f --- /dev/null +++ b/Lang/OCaml/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Chinese-remainder-theorem b/Lang/OCaml/Chinese-remainder-theorem new file mode 120000 index 0000000000..62bc14ae6d --- /dev/null +++ b/Lang/OCaml/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Closures-Value-capture b/Lang/OCaml/Closures-Value-capture new file mode 120000 index 0000000000..7201a67a0b --- /dev/null +++ b/Lang/OCaml/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Currying b/Lang/OCaml/Currying new file mode 120000 index 0000000000..297f234743 --- /dev/null +++ b/Lang/OCaml/Currying @@ -0,0 +1 @@ +../../Task/Currying/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Draw-a-clock b/Lang/OCaml/Draw-a-clock new file mode 120000 index 0000000000..50b5f3954b --- /dev/null +++ b/Lang/OCaml/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/OCaml \ No newline at end of file diff --git a/Lang/OCaml/File-input-output b/Lang/OCaml/File-input-output new file mode 120000 index 0000000000..74253df9e9 --- /dev/null +++ b/Lang/OCaml/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Find-the-last-Sunday-of-each-month b/Lang/OCaml/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..104831ae57 --- /dev/null +++ b/Lang/OCaml/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Gaussian-elimination b/Lang/OCaml/Gaussian-elimination new file mode 120000 index 0000000000..3dd1c9ca2a --- /dev/null +++ b/Lang/OCaml/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Hash-join b/Lang/OCaml/Hash-join new file mode 120000 index 0000000000..230c0f0a67 --- /dev/null +++ b/Lang/OCaml/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Hello-world-Newbie b/Lang/OCaml/Hello-world-Newbie new file mode 120000 index 0000000000..2d49e72b49 --- /dev/null +++ b/Lang/OCaml/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Longest-increasing-subsequence b/Lang/OCaml/Longest-increasing-subsequence new file mode 120000 index 0000000000..949f45aebb --- /dev/null +++ b/Lang/OCaml/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Munching-squares b/Lang/OCaml/Munching-squares new file mode 120000 index 0000000000..1e083007e3 --- /dev/null +++ b/Lang/OCaml/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Odd-word-problem b/Lang/OCaml/Odd-word-problem new file mode 120000 index 0000000000..90b226c2fc --- /dev/null +++ b/Lang/OCaml/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Old-lady-swallowed-a-fly b/Lang/OCaml/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..5e6ce7181f --- /dev/null +++ b/Lang/OCaml/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Quickselect-algorithm b/Lang/OCaml/Quickselect-algorithm new file mode 120000 index 0000000000..551b9f88d5 --- /dev/null +++ b/Lang/OCaml/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Reverse-words-in-a-string b/Lang/OCaml/Reverse-words-in-a-string new file mode 120000 index 0000000000..3096fa4457 --- /dev/null +++ b/Lang/OCaml/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Runge-Kutta-method b/Lang/OCaml/Runge-Kutta-method new file mode 120000 index 0000000000..fd481581d9 --- /dev/null +++ b/Lang/OCaml/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-append b/Lang/OCaml/String-append new file mode 120000 index 0000000000..5af7f6308d --- /dev/null +++ b/Lang/OCaml/String-append @@ -0,0 +1 @@ +../../Task/String-append/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-matching b/Lang/OCaml/String-matching new file mode 120000 index 0000000000..dcc04f1157 --- /dev/null +++ b/Lang/OCaml/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Unix-ls b/Lang/OCaml/Unix-ls new file mode 120000 index 0000000000..60674b2e28 --- /dev/null +++ b/Lang/OCaml/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/ABC-Problem b/Lang/Oberon-2/ABC-Problem new file mode 120000 index 0000000000..487a963377 --- /dev/null +++ b/Lang/Oberon-2/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Catamorphism b/Lang/Oberon-2/Catamorphism new file mode 120000 index 0000000000..8935956c59 --- /dev/null +++ b/Lang/Oberon-2/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Hash-join b/Lang/Oberon-2/Hash-join new file mode 120000 index 0000000000..9ee64b77ad --- /dev/null +++ b/Lang/Oberon-2/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/IBAN b/Lang/Oberon-2/IBAN new file mode 120000 index 0000000000..19e3713959 --- /dev/null +++ b/Lang/Oberon-2/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Iterated-digits-squaring b/Lang/Oberon-2/Iterated-digits-squaring new file mode 120000 index 0000000000..898342e155 --- /dev/null +++ b/Lang/Oberon-2/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/Almost-prime b/Lang/Objeck/Almost-prime new file mode 120000 index 0000000000..ef83636576 --- /dev/null +++ b/Lang/Objeck/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Casting-out-nines b/Lang/Objeck/Casting-out-nines new file mode 120000 index 0000000000..5b986db8c1 --- /dev/null +++ b/Lang/Objeck/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Objeck \ No newline at end of file diff --git a/Lang/Objeck/File-input-output b/Lang/Objeck/File-input-output new file mode 120000 index 0000000000..e27e517a0c --- /dev/null +++ b/Lang/Objeck/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Generate-Chess960-starting-position b/Lang/Objeck/Generate-Chess960-starting-position new file mode 120000 index 0000000000..c41de87ee9 --- /dev/null +++ b/Lang/Objeck/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Reverse-words-in-a-string b/Lang/Objeck/Reverse-words-in-a-string new file mode 120000 index 0000000000..5ee8036699 --- /dev/null +++ b/Lang/Objeck/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Semiprime b/Lang/Objeck/Semiprime new file mode 120000 index 0000000000..54db18ece4 --- /dev/null +++ b/Lang/Objeck/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-append b/Lang/Objeck/String-append new file mode 120000 index 0000000000..dc7d7ba78f --- /dev/null +++ b/Lang/Objeck/String-append @@ -0,0 +1 @@ +../../Task/String-append/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-matching b/Lang/Objeck/String-matching new file mode 120000 index 0000000000..aa8c5f776b --- /dev/null +++ b/Lang/Objeck/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Objeck \ No newline at end of file diff --git a/Lang/Objeck/The-Twelve-Days-of-Christmas b/Lang/Objeck/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..ee425b2876 --- /dev/null +++ b/Lang/Objeck/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal/File-input-output b/Lang/Object-Pascal/File-input-output new file mode 120000 index 0000000000..ff749958c8 --- /dev/null +++ b/Lang/Object-Pascal/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Object-Pascal \ No newline at end of file diff --git a/Lang/Objective-C/Closures-Value-capture b/Lang/Objective-C/Closures-Value-capture new file mode 120000 index 0000000000..c0220afd39 --- /dev/null +++ b/Lang/Objective-C/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/File-input-output b/Lang/Objective-C/File-input-output new file mode 120000 index 0000000000..405200e393 --- /dev/null +++ b/Lang/Objective-C/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Longest-increasing-subsequence b/Lang/Objective-C/Longest-increasing-subsequence new file mode 120000 index 0000000000..e16b672177 --- /dev/null +++ b/Lang/Objective-C/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/String-matching b/Lang/Objective-C/String-matching new file mode 120000 index 0000000000..3d6270ec95 --- /dev/null +++ b/Lang/Objective-C/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Objective-C \ No newline at end of file diff --git a/Lang/Octave/File-input-output b/Lang/Octave/File-input-output new file mode 120000 index 0000000000..dbcb780b98 --- /dev/null +++ b/Lang/Octave/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Octave \ No newline at end of file diff --git a/Lang/Octave/Munching-squares b/Lang/Octave/Munching-squares new file mode 120000 index 0000000000..0b0c6a9c34 --- /dev/null +++ b/Lang/Octave/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Octave \ No newline at end of file diff --git a/Lang/Octave/Runge-Kutta-method b/Lang/Octave/Runge-Kutta-method new file mode 120000 index 0000000000..0825b7a6af --- /dev/null +++ b/Lang/Octave/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Octave \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Amb b/Lang/OpenEdge-Progress/Amb new file mode 120000 index 0000000000..9070c0d2bf --- /dev/null +++ b/Lang/OpenEdge-Progress/Amb @@ -0,0 +1 @@ +../../Task/Amb/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/File-input-output b/Lang/OpenEdge-Progress/File-input-output new file mode 120000 index 0000000000..ed8b34d81d --- /dev/null +++ b/Lang/OpenEdge-Progress/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OxygenBasic/String-matching b/Lang/OxygenBasic/String-matching new file mode 120000 index 0000000000..77a88ef8aa --- /dev/null +++ b/Lang/OxygenBasic/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/OxygenBasic \ No newline at end of file diff --git a/Lang/Oz/Amb b/Lang/Oz/Amb new file mode 120000 index 0000000000..ff7b0de3df --- /dev/null +++ b/Lang/Oz/Amb @@ -0,0 +1 @@ +../../Task/Amb/Oz \ No newline at end of file diff --git a/Lang/Oz/File-input-output b/Lang/Oz/File-input-output new file mode 120000 index 0000000000..deff7ab902 --- /dev/null +++ b/Lang/Oz/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/AKS-test-for-primes b/Lang/PARI-GP/AKS-test-for-primes new file mode 120000 index 0000000000..94689c8b08 --- /dev/null +++ b/Lang/PARI-GP/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Almost-prime b/Lang/PARI-GP/Almost-prime new file mode 120000 index 0000000000..e1ccbd19e1 --- /dev/null +++ b/Lang/PARI-GP/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Amb b/Lang/PARI-GP/Amb new file mode 120000 index 0000000000..e12273f564 --- /dev/null +++ b/Lang/PARI-GP/Amb @@ -0,0 +1 @@ +../../Task/Amb/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Amicable-pairs b/Lang/PARI-GP/Amicable-pairs new file mode 120000 index 0000000000..181fcf6220 --- /dev/null +++ b/Lang/PARI-GP/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Arithmetic-geometric-mean-Calculate-Pi b/Lang/PARI-GP/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..008fda87df --- /dev/null +++ b/Lang/PARI-GP/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Benfords-law b/Lang/PARI-GP/Benfords-law new file mode 120000 index 0000000000..7caec199eb --- /dev/null +++ b/Lang/PARI-GP/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Bernoulli-numbers b/Lang/PARI-GP/Bernoulli-numbers new file mode 120000 index 0000000000..025ea5e68d --- /dev/null +++ b/Lang/PARI-GP/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Casting-out-nines b/Lang/PARI-GP/Casting-out-nines new file mode 120000 index 0000000000..de8872c5f6 --- /dev/null +++ b/Lang/PARI-GP/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Catalan-numbers-Pascals-triangle b/Lang/PARI-GP/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..a2390c9d95 --- /dev/null +++ b/Lang/PARI-GP/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Catamorphism b/Lang/PARI-GP/Catamorphism new file mode 120000 index 0000000000..ae4bcde447 --- /dev/null +++ b/Lang/PARI-GP/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Chinese-remainder-theorem b/Lang/PARI-GP/Chinese-remainder-theorem new file mode 120000 index 0000000000..af0671c7ba --- /dev/null +++ b/Lang/PARI-GP/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Circles-of-given-radius-through-two-points b/Lang/PARI-GP/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..5ede4f3d83 --- /dev/null +++ b/Lang/PARI-GP/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Closures-Value-capture b/Lang/PARI-GP/Closures-Value-capture new file mode 120000 index 0000000000..bc89edd361 --- /dev/null +++ b/Lang/PARI-GP/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Comma-quibbling b/Lang/PARI-GP/Comma-quibbling new file mode 120000 index 0000000000..fbd06e9857 --- /dev/null +++ b/Lang/PARI-GP/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Conjugate-transpose b/Lang/PARI-GP/Conjugate-transpose new file mode 120000 index 0000000000..0f1181015f --- /dev/null +++ b/Lang/PARI-GP/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Convert-decimal-number-to-rational b/Lang/PARI-GP/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..613f3eec51 --- /dev/null +++ b/Lang/PARI-GP/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Currying b/Lang/PARI-GP/Currying new file mode 120000 index 0000000000..9c63ecb021 --- /dev/null +++ b/Lang/PARI-GP/Currying @@ -0,0 +1 @@ +../../Task/Currying/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Fibonacci-word b/Lang/PARI-GP/Fibonacci-word new file mode 120000 index 0000000000..56d08e3da6 --- /dev/null +++ b/Lang/PARI-GP/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/File-input-output b/Lang/PARI-GP/File-input-output new file mode 120000 index 0000000000..83fb80715f --- /dev/null +++ b/Lang/PARI-GP/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Gaussian-elimination b/Lang/PARI-GP/Gaussian-elimination new file mode 120000 index 0000000000..cf75b804d4 --- /dev/null +++ b/Lang/PARI-GP/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Hello-world-Newbie b/Lang/PARI-GP/Hello-world-Newbie new file mode 120000 index 0000000000..586689b802 --- /dev/null +++ b/Lang/PARI-GP/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Hickerson-series-of-almost-integers b/Lang/PARI-GP/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..62a07508d9 --- /dev/null +++ b/Lang/PARI-GP/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Left-factorials b/Lang/PARI-GP/Left-factorials new file mode 120000 index 0000000000..08f615a123 --- /dev/null +++ b/Lang/PARI-GP/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Machine-code b/Lang/PARI-GP/Machine-code new file mode 120000 index 0000000000..e1f19f1487 --- /dev/null +++ b/Lang/PARI-GP/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Maximum-triangle-path-sum b/Lang/PARI-GP/Maximum-triangle-path-sum new file mode 120000 index 0000000000..e474ab13e1 --- /dev/null +++ b/Lang/PARI-GP/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Nth b/Lang/PARI-GP/Nth new file mode 120000 index 0000000000..d90628e0fa --- /dev/null +++ b/Lang/PARI-GP/Nth @@ -0,0 +1 @@ +../../Task/Nth/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Permutations-Rank-of-a-permutation b/Lang/PARI-GP/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..b6e8428c34 --- /dev/null +++ b/Lang/PARI-GP/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Pernicious-numbers b/Lang/PARI-GP/Pernicious-numbers new file mode 120000 index 0000000000..fda86aaed1 --- /dev/null +++ b/Lang/PARI-GP/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Quickselect-algorithm b/Lang/PARI-GP/Quickselect-algorithm new file mode 120000 index 0000000000..aa6abb363d --- /dev/null +++ b/Lang/PARI-GP/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Rep-string b/Lang/PARI-GP/Rep-string new file mode 120000 index 0000000000..fa8cbc6a68 --- /dev/null +++ b/Lang/PARI-GP/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Runge-Kutta-method b/Lang/PARI-GP/Runge-Kutta-method new file mode 120000 index 0000000000..af60a0794a --- /dev/null +++ b/Lang/PARI-GP/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Semiprime b/Lang/PARI-GP/Semiprime new file mode 120000 index 0000000000..564a4f1d2e --- /dev/null +++ b/Lang/PARI-GP/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Statistics-Basic b/Lang/PARI-GP/Statistics-Basic new file mode 120000 index 0000000000..3f656ecd12 --- /dev/null +++ b/Lang/PARI-GP/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-append b/Lang/PARI-GP/String-append new file mode 120000 index 0000000000..d9199250f3 --- /dev/null +++ b/Lang/PARI-GP/String-append @@ -0,0 +1 @@ +../../Task/String-append/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-matching b/Lang/PARI-GP/String-matching new file mode 120000 index 0000000000..33057c3f14 --- /dev/null +++ b/Lang/PARI-GP/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-prepend b/Lang/PARI-GP/String-prepend new file mode 120000 index 0000000000..5b9f77a644 --- /dev/null +++ b/Lang/PARI-GP/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sum-multiples-of-3-and-5 b/Lang/PARI-GP/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..33ef70f247 --- /dev/null +++ b/Lang/PARI-GP/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Unix-ls b/Lang/PARI-GP/Unix-ls new file mode 120000 index 0000000000..d92d52cdb5 --- /dev/null +++ b/Lang/PARI-GP/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Zero-to-the-zero-power b/Lang/PARI-GP/Zero-to-the-zero-power new file mode 120000 index 0000000000..c9fb19adc5 --- /dev/null +++ b/Lang/PARI-GP/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/ABC-Problem b/Lang/PHP/ABC-Problem new file mode 120000 index 0000000000..df4af63a91 --- /dev/null +++ b/Lang/PHP/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PHP \ No newline at end of file diff --git a/Lang/PHP/CSV-data-manipulation b/Lang/PHP/CSV-data-manipulation new file mode 120000 index 0000000000..06ec3d0de2 --- /dev/null +++ b/Lang/PHP/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/PHP \ No newline at end of file diff --git a/Lang/PHP/Calendar---for-REAL-programmers b/Lang/PHP/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..b006582cb8 --- /dev/null +++ b/Lang/PHP/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/PHP \ No newline at end of file diff --git a/Lang/PHP/Closures-Value-capture b/Lang/PHP/Closures-Value-capture new file mode 120000 index 0000000000..3f713a283f --- /dev/null +++ b/Lang/PHP/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/PHP \ No newline at end of file diff --git a/Lang/PHP/Comma-quibbling b/Lang/PHP/Comma-quibbling new file mode 120000 index 0000000000..385c5fb32b --- /dev/null +++ b/Lang/PHP/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/PHP \ No newline at end of file diff --git a/Lang/PHP/File-input-output b/Lang/PHP/File-input-output new file mode 120000 index 0000000000..559e0ba563 --- /dev/null +++ b/Lang/PHP/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PHP \ No newline at end of file diff --git a/Lang/PHP/Gaussian-elimination b/Lang/PHP/Gaussian-elimination new file mode 120000 index 0000000000..2b077ed50e --- /dev/null +++ b/Lang/PHP/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/PHP \ No newline at end of file diff --git a/Lang/PHP/Generate-lower-case-ASCII-alphabet b/Lang/PHP/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..043a46b1ec --- /dev/null +++ b/Lang/PHP/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PHP \ No newline at end of file diff --git a/Lang/PHP/Hash-join b/Lang/PHP/Hash-join new file mode 120000 index 0000000000..11f37f8502 --- /dev/null +++ b/Lang/PHP/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/PHP \ No newline at end of file diff --git a/Lang/PHP/Longest-increasing-subsequence b/Lang/PHP/Longest-increasing-subsequence new file mode 120000 index 0000000000..8f9d56b88b --- /dev/null +++ b/Lang/PHP/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/PHP \ No newline at end of file diff --git a/Lang/PHP/Munching-squares b/Lang/PHP/Munching-squares new file mode 120000 index 0000000000..9dd55fe4b7 --- /dev/null +++ b/Lang/PHP/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/PHP \ No newline at end of file diff --git a/Lang/PHP/Nth b/Lang/PHP/Nth new file mode 120000 index 0000000000..c93e405229 --- /dev/null +++ b/Lang/PHP/Nth @@ -0,0 +1 @@ +../../Task/Nth/PHP \ No newline at end of file diff --git a/Lang/PHP/Odd-word-problem b/Lang/PHP/Odd-word-problem new file mode 120000 index 0000000000..a697571a41 --- /dev/null +++ b/Lang/PHP/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/PHP \ No newline at end of file diff --git a/Lang/PHP/Old-lady-swallowed-a-fly b/Lang/PHP/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..e2220ede7e --- /dev/null +++ b/Lang/PHP/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/PHP \ No newline at end of file diff --git a/Lang/PHP/Phrase-reversals b/Lang/PHP/Phrase-reversals new file mode 120000 index 0000000000..bc341c85d4 --- /dev/null +++ b/Lang/PHP/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/PHP \ No newline at end of file diff --git a/Lang/PHP/String-matching b/Lang/PHP/String-matching new file mode 120000 index 0000000000..c938ad1eef --- /dev/null +++ b/Lang/PHP/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PHP \ No newline at end of file diff --git a/Lang/PHP/The-Twelve-Days-of-Christmas b/Lang/PHP/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..9933325423 --- /dev/null +++ b/Lang/PHP/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/PHP \ No newline at end of file diff --git a/Lang/PHP/Zero-to-the-zero-power b/Lang/PHP/Zero-to-the-zero-power new file mode 120000 index 0000000000..97e2b172a9 --- /dev/null +++ b/Lang/PHP/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PHP \ No newline at end of file diff --git a/Lang/PL-I/ABC-Problem b/Lang/PL-I/ABC-Problem new file mode 120000 index 0000000000..b1ebeeae01 --- /dev/null +++ b/Lang/PL-I/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Abundant,-deficient-and-perfect-number-classifications b/Lang/PL-I/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..49e2e05cff --- /dev/null +++ b/Lang/PL-I/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Amb b/Lang/PL-I/Amb new file mode 120000 index 0000000000..6fcbcc2f05 --- /dev/null +++ b/Lang/PL-I/Amb @@ -0,0 +1 @@ +../../Task/Amb/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Amicable-pairs b/Lang/PL-I/Amicable-pairs new file mode 120000 index 0000000000..4878d58c66 --- /dev/null +++ b/Lang/PL-I/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Benfords-law b/Lang/PL-I/Benfords-law new file mode 120000 index 0000000000..488889958e --- /dev/null +++ b/Lang/PL-I/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Bernoulli-numbers b/Lang/PL-I/Bernoulli-numbers new file mode 120000 index 0000000000..c4b5985e29 --- /dev/null +++ b/Lang/PL-I/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/CSV-data-manipulation b/Lang/PL-I/CSV-data-manipulation new file mode 120000 index 0000000000..8a92f95b98 --- /dev/null +++ b/Lang/PL-I/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Calendar---for-REAL-programmers b/Lang/PL-I/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..b8e65a756b --- /dev/null +++ b/Lang/PL-I/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Circles-of-given-radius-through-two-points b/Lang/PL-I/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..469ca17064 --- /dev/null +++ b/Lang/PL-I/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Comma-quibbling b/Lang/PL-I/Comma-quibbling new file mode 120000 index 0000000000..527348de9a --- /dev/null +++ b/Lang/PL-I/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Conjugate-transpose b/Lang/PL-I/Conjugate-transpose new file mode 120000 index 0000000000..ea944b0cc2 --- /dev/null +++ b/Lang/PL-I/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Convert-decimal-number-to-rational b/Lang/PL-I/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..4b42450899 --- /dev/null +++ b/Lang/PL-I/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Digital-root-Multiplicative-digital-root b/Lang/PL-I/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..3476510c01 --- /dev/null +++ b/Lang/PL-I/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Fibonacci-word b/Lang/PL-I/Fibonacci-word new file mode 120000 index 0000000000..90655a4c89 --- /dev/null +++ b/Lang/PL-I/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/PL-I \ No newline at end of file diff --git a/Lang/PL-I/File-input-output b/Lang/PL-I/File-input-output new file mode 120000 index 0000000000..9d95cf2d54 --- /dev/null +++ b/Lang/PL-I/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Flipping-bits-game b/Lang/PL-I/Flipping-bits-game new file mode 120000 index 0000000000..fbeae2d2ca --- /dev/null +++ b/Lang/PL-I/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Gaussian-elimination b/Lang/PL-I/Gaussian-elimination new file mode 120000 index 0000000000..32e458e878 --- /dev/null +++ b/Lang/PL-I/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Generate-lower-case-ASCII-alphabet b/Lang/PL-I/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..6b10005a18 --- /dev/null +++ b/Lang/PL-I/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Hickerson-series-of-almost-integers b/Lang/PL-I/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..fd9299b8c0 --- /dev/null +++ b/Lang/PL-I/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Left-factorials b/Lang/PL-I/Left-factorials new file mode 120000 index 0000000000..408a8ddc9c --- /dev/null +++ b/Lang/PL-I/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Ludic-numbers b/Lang/PL-I/Ludic-numbers new file mode 120000 index 0000000000..2716f3233c --- /dev/null +++ b/Lang/PL-I/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Magic-squares-of-odd-order b/Lang/PL-I/Magic-squares-of-odd-order new file mode 120000 index 0000000000..ecc979f65b --- /dev/null +++ b/Lang/PL-I/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Move-to-front-algorithm b/Lang/PL-I/Move-to-front-algorithm new file mode 120000 index 0000000000..b1aa0d0ae4 --- /dev/null +++ b/Lang/PL-I/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Munching-squares b/Lang/PL-I/Munching-squares new file mode 120000 index 0000000000..ad12976dc3 --- /dev/null +++ b/Lang/PL-I/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Nth b/Lang/PL-I/Nth new file mode 120000 index 0000000000..c03d2050ee --- /dev/null +++ b/Lang/PL-I/Nth @@ -0,0 +1 @@ +../../Task/Nth/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Odd-word-problem b/Lang/PL-I/Odd-word-problem new file mode 120000 index 0000000000..9e8156a683 --- /dev/null +++ b/Lang/PL-I/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Quickselect-algorithm b/Lang/PL-I/Quickselect-algorithm new file mode 120000 index 0000000000..bce3231855 --- /dev/null +++ b/Lang/PL-I/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Rep-string b/Lang/PL-I/Rep-string new file mode 120000 index 0000000000..cecd481c91 --- /dev/null +++ b/Lang/PL-I/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Reverse-words-in-a-string b/Lang/PL-I/Reverse-words-in-a-string new file mode 120000 index 0000000000..911f72fb99 --- /dev/null +++ b/Lang/PL-I/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Runge-Kutta-method b/Lang/PL-I/Runge-Kutta-method new file mode 120000 index 0000000000..6a97095dab --- /dev/null +++ b/Lang/PL-I/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Semiprime b/Lang/PL-I/Semiprime new file mode 120000 index 0000000000..b9ce76e901 --- /dev/null +++ b/Lang/PL-I/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Statistics-Basic b/Lang/PL-I/Statistics-Basic new file mode 120000 index 0000000000..0dfde08474 --- /dev/null +++ b/Lang/PL-I/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-append b/Lang/PL-I/String-append new file mode 120000 index 0000000000..66440adbdd --- /dev/null +++ b/Lang/PL-I/String-append @@ -0,0 +1 @@ +../../Task/String-append/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-matching b/Lang/PL-I/String-matching new file mode 120000 index 0000000000..3e035c128e --- /dev/null +++ b/Lang/PL-I/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-prepend b/Lang/PL-I/String-prepend new file mode 120000 index 0000000000..68753f5def --- /dev/null +++ b/Lang/PL-I/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sum-multiples-of-3-and-5 b/Lang/PL-I/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..620becf916 --- /dev/null +++ b/Lang/PL-I/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Zero-to-the-zero-power b/Lang/PL-I/Zero-to-the-zero-power new file mode 120000 index 0000000000..edd5dcc285 --- /dev/null +++ b/Lang/PL-I/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Zhang-Suen-thinning-algorithm b/Lang/PL-I/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..453e819f9d --- /dev/null +++ b/Lang/PL-I/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/PL-I \ No newline at end of file diff --git a/Lang/PL-pgSQL/Benfords-law b/Lang/PL-pgSQL/Benfords-law new file mode 120000 index 0000000000..8b358dc012 --- /dev/null +++ b/Lang/PL-pgSQL/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/PL-pgSQL \ No newline at end of file diff --git a/Lang/Pascal/AKS-test-for-primes b/Lang/Pascal/AKS-test-for-primes new file mode 120000 index 0000000000..46dfd6f69f --- /dev/null +++ b/Lang/Pascal/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Abundant,-deficient-and-perfect-number-classifications b/Lang/Pascal/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..1c39623193 --- /dev/null +++ b/Lang/Pascal/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Almost-prime b/Lang/Pascal/Almost-prime new file mode 120000 index 0000000000..335df9213f --- /dev/null +++ b/Lang/Pascal/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Amicable-pairs b/Lang/Pascal/Amicable-pairs new file mode 120000 index 0000000000..2327835868 --- /dev/null +++ b/Lang/Pascal/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Catalan-numbers-Pascals-triangle b/Lang/Pascal/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..227c925309 --- /dev/null +++ b/Lang/Pascal/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Catamorphism b/Lang/Pascal/Catamorphism new file mode 120000 index 0000000000..9733b3bd23 --- /dev/null +++ b/Lang/Pascal/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Extensible-prime-generator b/Lang/Pascal/Extensible-prime-generator new file mode 120000 index 0000000000..ed11539b96 --- /dev/null +++ b/Lang/Pascal/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Fibonacci-word b/Lang/Pascal/Fibonacci-word new file mode 120000 index 0000000000..9b38efff15 --- /dev/null +++ b/Lang/Pascal/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Iterated-digits-squaring b/Lang/Pascal/Iterated-digits-squaring new file mode 120000 index 0000000000..d682587f7b --- /dev/null +++ b/Lang/Pascal/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Machine-code b/Lang/Pascal/Machine-code new file mode 120000 index 0000000000..cfa9f5777e --- /dev/null +++ b/Lang/Pascal/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Maximum-triangle-path-sum b/Lang/Pascal/Maximum-triangle-path-sum new file mode 120000 index 0000000000..046175babd --- /dev/null +++ b/Lang/Pascal/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Narcissistic-decimal-number b/Lang/Pascal/Narcissistic-decimal-number new file mode 120000 index 0000000000..328576767c --- /dev/null +++ b/Lang/Pascal/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Paraffins b/Lang/Pascal/Paraffins new file mode 120000 index 0000000000..5352a21fd0 --- /dev/null +++ b/Lang/Pascal/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Pernicious-numbers b/Lang/Pascal/Pernicious-numbers new file mode 120000 index 0000000000..ac531c89fe --- /dev/null +++ b/Lang/Pascal/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Runge-Kutta-method b/Lang/Pascal/Runge-Kutta-method new file mode 120000 index 0000000000..dde7302ce6 --- /dev/null +++ b/Lang/Pascal/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Semiprime b/Lang/Pascal/Semiprime new file mode 120000 index 0000000000..07386a3af1 --- /dev/null +++ b/Lang/Pascal/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Pascal \ No newline at end of file diff --git a/Lang/Pascal/String-append b/Lang/Pascal/String-append new file mode 120000 index 0000000000..31a65ab6bd --- /dev/null +++ b/Lang/Pascal/String-append @@ -0,0 +1 @@ +../../Task/String-append/Pascal \ No newline at end of file diff --git a/Lang/Pascal/String-prepend b/Lang/Pascal/String-prepend new file mode 120000 index 0000000000..6eee77decd --- /dev/null +++ b/Lang/Pascal/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sum-multiples-of-3-and-5 b/Lang/Pascal/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..e3ef27b1d3 --- /dev/null +++ b/Lang/Pascal/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Pascal \ No newline at end of file diff --git a/Lang/Pascal/The-ISAAC-Cipher b/Lang/Pascal/The-ISAAC-Cipher new file mode 120000 index 0000000000..0851f3f231 --- /dev/null +++ b/Lang/Pascal/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/9-billion-names-of-God-the-integer b/Lang/Perl-6/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..2bec27dcc3 --- /dev/null +++ b/Lang/Perl-6/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/ABC-Problem b/Lang/Perl-6/ABC-Problem new file mode 120000 index 0000000000..ae839c1142 --- /dev/null +++ b/Lang/Perl-6/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/AKS-test-for-primes b/Lang/Perl-6/AKS-test-for-primes new file mode 120000 index 0000000000..912ac1fc1b --- /dev/null +++ b/Lang/Perl-6/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Abundant,-deficient-and-perfect-number-classifications b/Lang/Perl-6/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..367edc4636 --- /dev/null +++ b/Lang/Perl-6/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Aliquot-sequence-classifications b/Lang/Perl-6/Aliquot-sequence-classifications new file mode 120000 index 0000000000..ca12c5f4bb --- /dev/null +++ b/Lang/Perl-6/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Almost-prime b/Lang/Perl-6/Almost-prime new file mode 120000 index 0000000000..56d2103db4 --- /dev/null +++ b/Lang/Perl-6/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Amb b/Lang/Perl-6/Amb new file mode 120000 index 0000000000..35952d67ef --- /dev/null +++ b/Lang/Perl-6/Amb @@ -0,0 +1 @@ +../../Task/Amb/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Amicable-pairs b/Lang/Perl-6/Amicable-pairs new file mode 120000 index 0000000000..a4ca4d0f7a --- /dev/null +++ b/Lang/Perl-6/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Perl-6/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..6bacdecfde --- /dev/null +++ b/Lang/Perl-6/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Benfords-law b/Lang/Perl-6/Benfords-law new file mode 120000 index 0000000000..b184228af5 --- /dev/null +++ b/Lang/Perl-6/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bernoulli-numbers b/Lang/Perl-6/Bernoulli-numbers new file mode 120000 index 0000000000..95f207256f --- /dev/null +++ b/Lang/Perl-6/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitcoin-public-point-to-address b/Lang/Perl-6/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..9b7799b4c2 --- /dev/null +++ b/Lang/Perl-6/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/CSV-data-manipulation b/Lang/Perl-6/CSV-data-manipulation new file mode 120000 index 0000000000..ac4febeb9a --- /dev/null +++ b/Lang/Perl-6/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Calendar---for-REAL-programmers b/Lang/Perl-6/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..d038320b31 --- /dev/null +++ b/Lang/Perl-6/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Casting-out-nines b/Lang/Perl-6/Casting-out-nines new file mode 120000 index 0000000000..4bb0677dab --- /dev/null +++ b/Lang/Perl-6/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Catalan-numbers-Pascals-triangle b/Lang/Perl-6/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..79e1e9624e --- /dev/null +++ b/Lang/Perl-6/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Catamorphism b/Lang/Perl-6/Catamorphism new file mode 120000 index 0000000000..2aefbacd94 --- /dev/null +++ b/Lang/Perl-6/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Chinese-remainder-theorem b/Lang/Perl-6/Chinese-remainder-theorem new file mode 120000 index 0000000000..e31cd3de9b --- /dev/null +++ b/Lang/Perl-6/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Circles-of-given-radius-through-two-points b/Lang/Perl-6/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..7d8e6439a0 --- /dev/null +++ b/Lang/Perl-6/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Closures-Value-capture b/Lang/Perl-6/Closures-Value-capture new file mode 120000 index 0000000000..e5a562b6fd --- /dev/null +++ b/Lang/Perl-6/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Combinations-and-permutations b/Lang/Perl-6/Combinations-and-permutations new file mode 120000 index 0000000000..56c0dcc7ea --- /dev/null +++ b/Lang/Perl-6/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Comma-quibbling b/Lang/Perl-6/Comma-quibbling new file mode 120000 index 0000000000..aca325f38d --- /dev/null +++ b/Lang/Perl-6/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Convert-decimal-number-to-rational b/Lang/Perl-6/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..2566783144 --- /dev/null +++ b/Lang/Perl-6/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Currying b/Lang/Perl-6/Currying new file mode 120000 index 0000000000..12708e4a1c --- /dev/null +++ b/Lang/Perl-6/Currying @@ -0,0 +1 @@ +../../Task/Currying/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Digital-root-Multiplicative-digital-root b/Lang/Perl-6/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..3c87926078 --- /dev/null +++ b/Lang/Perl-6/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Draw-a-clock b/Lang/Perl-6/Draw-a-clock new file mode 120000 index 0000000000..55703037d2 --- /dev/null +++ b/Lang/Perl-6/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Extensible-prime-generator b/Lang/Perl-6/Extensible-prime-generator new file mode 120000 index 0000000000..86b7796b1c --- /dev/null +++ b/Lang/Perl-6/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Fibonacci-word b/Lang/Perl-6/Fibonacci-word new file mode 120000 index 0000000000..324fb8c92a --- /dev/null +++ b/Lang/Perl-6/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Fibonacci-word-fractal b/Lang/Perl-6/Fibonacci-word-fractal new file mode 120000 index 0000000000..272e2c9f7e --- /dev/null +++ b/Lang/Perl-6/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/File-input-output b/Lang/Perl-6/File-input-output new file mode 120000 index 0000000000..7ef7e6447c --- /dev/null +++ b/Lang/Perl-6/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Find-the-last-Sunday-of-each-month b/Lang/Perl-6/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..80fae31a1e --- /dev/null +++ b/Lang/Perl-6/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Flipping-bits-game b/Lang/Perl-6/Flipping-bits-game new file mode 120000 index 0000000000..be62bc9d21 --- /dev/null +++ b/Lang/Perl-6/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Fractran b/Lang/Perl-6/Fractran new file mode 120000 index 0000000000..111f0d4bff --- /dev/null +++ b/Lang/Perl-6/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Gaussian-elimination b/Lang/Perl-6/Gaussian-elimination new file mode 120000 index 0000000000..b542c464ef --- /dev/null +++ b/Lang/Perl-6/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Generate-Chess960-starting-position b/Lang/Perl-6/Generate-Chess960-starting-position new file mode 120000 index 0000000000..a24e5fb752 --- /dev/null +++ b/Lang/Perl-6/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Generate-lower-case-ASCII-alphabet b/Lang/Perl-6/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d5b2d23d48 --- /dev/null +++ b/Lang/Perl-6/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Hash-join b/Lang/Perl-6/Hash-join new file mode 120000 index 0000000000..365ab75d18 --- /dev/null +++ b/Lang/Perl-6/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Heronian-triangles b/Lang/Perl-6/Heronian-triangles new file mode 120000 index 0000000000..646f3998c9 --- /dev/null +++ b/Lang/Perl-6/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Hickerson-series-of-almost-integers b/Lang/Perl-6/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..6f57276ae9 --- /dev/null +++ b/Lang/Perl-6/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/IBAN b/Lang/Perl-6/IBAN new file mode 120000 index 0000000000..0ab2e964eb --- /dev/null +++ b/Lang/Perl-6/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Iterated-digits-squaring b/Lang/Perl-6/Iterated-digits-squaring new file mode 120000 index 0000000000..bc6689cd05 --- /dev/null +++ b/Lang/Perl-6/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/K-d-tree b/Lang/Perl-6/K-d-tree new file mode 120000 index 0000000000..98bc27da97 --- /dev/null +++ b/Lang/Perl-6/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Left-factorials b/Lang/Perl-6/Left-factorials new file mode 120000 index 0000000000..fc43891fe8 --- /dev/null +++ b/Lang/Perl-6/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Longest-increasing-subsequence b/Lang/Perl-6/Longest-increasing-subsequence new file mode 120000 index 0000000000..e29dfe6427 --- /dev/null +++ b/Lang/Perl-6/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Ludic-numbers b/Lang/Perl-6/Ludic-numbers new file mode 120000 index 0000000000..778eefcd89 --- /dev/null +++ b/Lang/Perl-6/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Magic-squares-of-odd-order b/Lang/Perl-6/Magic-squares-of-odd-order new file mode 120000 index 0000000000..2bd7fc43b6 --- /dev/null +++ b/Lang/Perl-6/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Make-directory-path b/Lang/Perl-6/Make-directory-path new file mode 120000 index 0000000000..aa09c67633 --- /dev/null +++ b/Lang/Perl-6/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Maximum-triangle-path-sum b/Lang/Perl-6/Maximum-triangle-path-sum new file mode 120000 index 0000000000..2b055e7eaf --- /dev/null +++ b/Lang/Perl-6/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Move-to-front-algorithm b/Lang/Perl-6/Move-to-front-algorithm new file mode 120000 index 0000000000..1431137eac --- /dev/null +++ b/Lang/Perl-6/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Munching-squares b/Lang/Perl-6/Munching-squares new file mode 120000 index 0000000000..015b85297d --- /dev/null +++ b/Lang/Perl-6/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Narcissistic-decimal-number b/Lang/Perl-6/Narcissistic-decimal-number new file mode 120000 index 0000000000..a7e9886854 --- /dev/null +++ b/Lang/Perl-6/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Natural-sorting b/Lang/Perl-6/Natural-sorting new file mode 120000 index 0000000000..28b5af65f4 --- /dev/null +++ b/Lang/Perl-6/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Nth b/Lang/Perl-6/Nth new file mode 120000 index 0000000000..4be9c8c2bd --- /dev/null +++ b/Lang/Perl-6/Nth @@ -0,0 +1 @@ +../../Task/Nth/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Odd-word-problem b/Lang/Perl-6/Odd-word-problem new file mode 120000 index 0000000000..854642d46c --- /dev/null +++ b/Lang/Perl-6/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Old-lady-swallowed-a-fly b/Lang/Perl-6/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..f09e15227d --- /dev/null +++ b/Lang/Perl-6/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Order-disjoint-list-items b/Lang/Perl-6/Order-disjoint-list-items new file mode 120000 index 0000000000..3eb1c2adb4 --- /dev/null +++ b/Lang/Perl-6/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Paraffins b/Lang/Perl-6/Paraffins new file mode 120000 index 0000000000..838990120c --- /dev/null +++ b/Lang/Perl-6/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Parse-an-IP-Address b/Lang/Perl-6/Parse-an-IP-Address new file mode 120000 index 0000000000..1aba94fc5c --- /dev/null +++ b/Lang/Perl-6/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Penneys-game b/Lang/Perl-6/Penneys-game new file mode 120000 index 0000000000..ff6a11ef4d --- /dev/null +++ b/Lang/Perl-6/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Percolation-Mean-run-density b/Lang/Perl-6/Percolation-Mean-run-density new file mode 120000 index 0000000000..fe7718a11f --- /dev/null +++ b/Lang/Perl-6/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Pernicious-numbers b/Lang/Perl-6/Pernicious-numbers new file mode 120000 index 0000000000..bd11ec50e0 --- /dev/null +++ b/Lang/Perl-6/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Phrase-reversals b/Lang/Perl-6/Phrase-reversals new file mode 120000 index 0000000000..4cc1935f51 --- /dev/null +++ b/Lang/Perl-6/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Quickselect-algorithm b/Lang/Perl-6/Quickselect-algorithm new file mode 120000 index 0000000000..12d8e50624 --- /dev/null +++ b/Lang/Perl-6/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/RSA-code b/Lang/Perl-6/RSA-code new file mode 120000 index 0000000000..5b50450113 --- /dev/null +++ b/Lang/Perl-6/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Ranking-methods b/Lang/Perl-6/Ranking-methods new file mode 120000 index 0000000000..66c2e7bef9 --- /dev/null +++ b/Lang/Perl-6/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rep-string b/Lang/Perl-6/Rep-string new file mode 120000 index 0000000000..817ad287cf --- /dev/null +++ b/Lang/Perl-6/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Reverse-words-in-a-string b/Lang/Perl-6/Reverse-words-in-a-string new file mode 120000 index 0000000000..25f215d723 --- /dev/null +++ b/Lang/Perl-6/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Runge-Kutta-method b/Lang/Perl-6/Runge-Kutta-method new file mode 120000 index 0000000000..16ed2d2a89 --- /dev/null +++ b/Lang/Perl-6/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Semiprime b/Lang/Perl-6/Semiprime new file mode 120000 index 0000000000..3a5a2b9e64 --- /dev/null +++ b/Lang/Perl-6/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sequence-of-primes-by-Trial-Division b/Lang/Perl-6/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..f62deab1e0 --- /dev/null +++ b/Lang/Perl-6/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Solve-a-Holy-Knights-tour b/Lang/Perl-6/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..b0cc1c6333 --- /dev/null +++ b/Lang/Perl-6/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Solve-a-Hopido-puzzle b/Lang/Perl-6/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..53edfc2369 --- /dev/null +++ b/Lang/Perl-6/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Solve-a-Numbrix-puzzle b/Lang/Perl-6/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..667e1fc1cf --- /dev/null +++ b/Lang/Perl-6/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Solve-the-no-connection-puzzle b/Lang/Perl-6/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..e4c50482e0 --- /dev/null +++ b/Lang/Perl-6/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sparkline-in-unicode b/Lang/Perl-6/Sparkline-in-unicode new file mode 120000 index 0000000000..94502fdad9 --- /dev/null +++ b/Lang/Perl-6/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/State-name-puzzle b/Lang/Perl-6/State-name-puzzle new file mode 120000 index 0000000000..adc76eafa5 --- /dev/null +++ b/Lang/Perl-6/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Statistics-Basic b/Lang/Perl-6/Statistics-Basic new file mode 120000 index 0000000000..337345cdbf --- /dev/null +++ b/Lang/Perl-6/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stern-Brocot-sequence b/Lang/Perl-6/Stern-Brocot-sequence new file mode 120000 index 0000000000..a804d5fc2c --- /dev/null +++ b/Lang/Perl-6/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-append b/Lang/Perl-6/String-append new file mode 120000 index 0000000000..b71035fc37 --- /dev/null +++ b/Lang/Perl-6/String-append @@ -0,0 +1 @@ +../../Task/String-append/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-matching b/Lang/Perl-6/String-matching new file mode 120000 index 0000000000..96a4e33a3b --- /dev/null +++ b/Lang/Perl-6/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-prepend b/Lang/Perl-6/String-prepend new file mode 120000 index 0000000000..b8dc4aabf3 --- /dev/null +++ b/Lang/Perl-6/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sum-multiples-of-3-and-5 b/Lang/Perl-6/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..da92aa4914 --- /dev/null +++ b/Lang/Perl-6/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Textonyms b/Lang/Perl-6/Textonyms new file mode 120000 index 0000000000..85515b1e42 --- /dev/null +++ b/Lang/Perl-6/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/The-Twelve-Days-of-Christmas b/Lang/Perl-6/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..d9defa3d63 --- /dev/null +++ b/Lang/Perl-6/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Total-circles-area b/Lang/Perl-6/Total-circles-area new file mode 120000 index 0000000000..d73cadfd31 --- /dev/null +++ b/Lang/Perl-6/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Ulam-spiral--for-primes- b/Lang/Perl-6/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..756d3b82c8 --- /dev/null +++ b/Lang/Perl-6/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Unix-ls b/Lang/Perl-6/Unix-ls new file mode 120000 index 0000000000..c2ccc9b04c --- /dev/null +++ b/Lang/Perl-6/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/World-Cup-group-stage b/Lang/Perl-6/World-Cup-group-stage new file mode 120000 index 0000000000..594b24066c --- /dev/null +++ b/Lang/Perl-6/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Zero-to-the-zero-power b/Lang/Perl-6/Zero-to-the-zero-power new file mode 120000 index 0000000000..3f521e072a --- /dev/null +++ b/Lang/Perl-6/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Zhang-Suen-thinning-algorithm b/Lang/Perl-6/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..deeb2953e0 --- /dev/null +++ b/Lang/Perl-6/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/9-billion-names-of-God-the-integer b/Lang/Perl/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..5a22a0264b --- /dev/null +++ b/Lang/Perl/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Perl \ No newline at end of file diff --git a/Lang/Perl/ABC-Problem b/Lang/Perl/ABC-Problem new file mode 120000 index 0000000000..0fc28f9afe --- /dev/null +++ b/Lang/Perl/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Perl \ No newline at end of file diff --git a/Lang/Perl/AKS-test-for-primes b/Lang/Perl/AKS-test-for-primes new file mode 120000 index 0000000000..9022f2cbe8 --- /dev/null +++ b/Lang/Perl/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Perl \ No newline at end of file diff --git a/Lang/Perl/Abundant,-deficient-and-perfect-number-classifications b/Lang/Perl/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..887112ccb3 --- /dev/null +++ b/Lang/Perl/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Perl \ No newline at end of file diff --git a/Lang/Perl/Aliquot-sequence-classifications b/Lang/Perl/Aliquot-sequence-classifications new file mode 120000 index 0000000000..70b99a32f8 --- /dev/null +++ b/Lang/Perl/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Perl \ No newline at end of file diff --git a/Lang/Perl/Almost-prime b/Lang/Perl/Almost-prime new file mode 120000 index 0000000000..27aadf20c2 --- /dev/null +++ b/Lang/Perl/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Perl \ No newline at end of file diff --git a/Lang/Perl/Amb b/Lang/Perl/Amb new file mode 120000 index 0000000000..211550d044 --- /dev/null +++ b/Lang/Perl/Amb @@ -0,0 +1 @@ +../../Task/Amb/Perl \ No newline at end of file diff --git a/Lang/Perl/Amicable-pairs b/Lang/Perl/Amicable-pairs new file mode 120000 index 0000000000..5173e7ea2f --- /dev/null +++ b/Lang/Perl/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Perl \ No newline at end of file diff --git a/Lang/Perl/Append-a-record-to-the-end-of-a-text-file b/Lang/Perl/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..e9356d3b3b --- /dev/null +++ b/Lang/Perl/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Perl \ No newline at end of file diff --git a/Lang/Perl/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Perl/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..3b15baad41 --- /dev/null +++ b/Lang/Perl/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Perl \ No newline at end of file diff --git a/Lang/Perl/Benfords-law b/Lang/Perl/Benfords-law new file mode 120000 index 0000000000..7259ad43c0 --- /dev/null +++ b/Lang/Perl/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Perl \ No newline at end of file diff --git a/Lang/Perl/Bernoulli-numbers b/Lang/Perl/Bernoulli-numbers new file mode 120000 index 0000000000..c697700ec2 --- /dev/null +++ b/Lang/Perl/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Perl \ No newline at end of file diff --git a/Lang/Perl/Bitcoin-public-point-to-address b/Lang/Perl/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..d57a3a3eb9 --- /dev/null +++ b/Lang/Perl/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Perl \ No newline at end of file diff --git a/Lang/Perl/CSV-data-manipulation b/Lang/Perl/CSV-data-manipulation new file mode 120000 index 0000000000..78c98803f1 --- /dev/null +++ b/Lang/Perl/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Perl \ No newline at end of file diff --git a/Lang/Perl/Calendar---for-REAL-programmers b/Lang/Perl/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..24d21bfa20 --- /dev/null +++ b/Lang/Perl/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Perl \ No newline at end of file diff --git a/Lang/Perl/Casting-out-nines b/Lang/Perl/Casting-out-nines new file mode 120000 index 0000000000..d93aa0e239 --- /dev/null +++ b/Lang/Perl/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Perl \ No newline at end of file diff --git a/Lang/Perl/Catalan-numbers-Pascals-triangle b/Lang/Perl/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..bfd2c1f80a --- /dev/null +++ b/Lang/Perl/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Perl \ No newline at end of file diff --git a/Lang/Perl/Catamorphism b/Lang/Perl/Catamorphism new file mode 120000 index 0000000000..23a556ed9b --- /dev/null +++ b/Lang/Perl/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Perl \ No newline at end of file diff --git a/Lang/Perl/Chinese-remainder-theorem b/Lang/Perl/Chinese-remainder-theorem new file mode 120000 index 0000000000..2ebbfde38a --- /dev/null +++ b/Lang/Perl/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Perl \ No newline at end of file diff --git a/Lang/Perl/Closures-Value-capture b/Lang/Perl/Closures-Value-capture new file mode 120000 index 0000000000..bf26e1635e --- /dev/null +++ b/Lang/Perl/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Perl \ No newline at end of file diff --git a/Lang/Perl/Combinations-and-permutations b/Lang/Perl/Combinations-and-permutations new file mode 120000 index 0000000000..5f01b7dd89 --- /dev/null +++ b/Lang/Perl/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Perl \ No newline at end of file diff --git a/Lang/Perl/Comma-quibbling b/Lang/Perl/Comma-quibbling new file mode 120000 index 0000000000..ea344df4c8 --- /dev/null +++ b/Lang/Perl/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Perl \ No newline at end of file diff --git a/Lang/Perl/Convert-decimal-number-to-rational b/Lang/Perl/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..b02008c9ef --- /dev/null +++ b/Lang/Perl/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Perl \ No newline at end of file diff --git a/Lang/Perl/Currying b/Lang/Perl/Currying new file mode 120000 index 0000000000..53d7b4ea8a --- /dev/null +++ b/Lang/Perl/Currying @@ -0,0 +1 @@ +../../Task/Currying/Perl \ No newline at end of file diff --git a/Lang/Perl/Digital-root-Multiplicative-digital-root b/Lang/Perl/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..dd6f7c9d41 --- /dev/null +++ b/Lang/Perl/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Perl \ No newline at end of file diff --git a/Lang/Perl/Draw-a-clock b/Lang/Perl/Draw-a-clock new file mode 120000 index 0000000000..ecbfe6cd75 --- /dev/null +++ b/Lang/Perl/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Perl \ No newline at end of file diff --git a/Lang/Perl/Extensible-prime-generator b/Lang/Perl/Extensible-prime-generator new file mode 120000 index 0000000000..29d1ac5e00 --- /dev/null +++ b/Lang/Perl/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Perl \ No newline at end of file diff --git a/Lang/Perl/Fibonacci-word b/Lang/Perl/Fibonacci-word new file mode 120000 index 0000000000..d7dafe10e7 --- /dev/null +++ b/Lang/Perl/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Perl \ No newline at end of file diff --git a/Lang/Perl/Fibonacci-word-fractal b/Lang/Perl/Fibonacci-word-fractal new file mode 120000 index 0000000000..ddaba794db --- /dev/null +++ b/Lang/Perl/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Perl \ No newline at end of file diff --git a/Lang/Perl/File-input-output b/Lang/Perl/File-input-output new file mode 120000 index 0000000000..510b0a85cf --- /dev/null +++ b/Lang/Perl/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Perl \ No newline at end of file diff --git a/Lang/Perl/Find-the-last-Sunday-of-each-month b/Lang/Perl/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..46fc21a3fc --- /dev/null +++ b/Lang/Perl/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Perl \ No newline at end of file diff --git a/Lang/Perl/Flipping-bits-game b/Lang/Perl/Flipping-bits-game new file mode 120000 index 0000000000..0d0a18c5c6 --- /dev/null +++ b/Lang/Perl/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Perl \ No newline at end of file diff --git a/Lang/Perl/Fractran b/Lang/Perl/Fractran new file mode 120000 index 0000000000..c6abe76b3b --- /dev/null +++ b/Lang/Perl/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Perl \ No newline at end of file diff --git a/Lang/Perl/Gaussian-elimination b/Lang/Perl/Gaussian-elimination new file mode 120000 index 0000000000..a645794dbc --- /dev/null +++ b/Lang/Perl/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Perl \ No newline at end of file diff --git a/Lang/Perl/Generate-Chess960-starting-position b/Lang/Perl/Generate-Chess960-starting-position new file mode 120000 index 0000000000..2704bf8fc3 --- /dev/null +++ b/Lang/Perl/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Perl \ No newline at end of file diff --git a/Lang/Perl/Generate-lower-case-ASCII-alphabet b/Lang/Perl/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..358d29fe18 --- /dev/null +++ b/Lang/Perl/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Perl \ No newline at end of file diff --git a/Lang/Perl/Hash-join b/Lang/Perl/Hash-join new file mode 120000 index 0000000000..a07d27654e --- /dev/null +++ b/Lang/Perl/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Perl \ No newline at end of file diff --git a/Lang/Perl/Hello-world-Newbie b/Lang/Perl/Hello-world-Newbie new file mode 120000 index 0000000000..37ad6a86f0 --- /dev/null +++ b/Lang/Perl/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Perl \ No newline at end of file diff --git a/Lang/Perl/Heronian-triangles b/Lang/Perl/Heronian-triangles new file mode 120000 index 0000000000..f6f73af317 --- /dev/null +++ b/Lang/Perl/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Perl \ No newline at end of file diff --git a/Lang/Perl/Hickerson-series-of-almost-integers b/Lang/Perl/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..cb4a4e2cbe --- /dev/null +++ b/Lang/Perl/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Perl \ No newline at end of file diff --git a/Lang/Perl/IBAN b/Lang/Perl/IBAN new file mode 120000 index 0000000000..b4103cedc3 --- /dev/null +++ b/Lang/Perl/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Perl \ No newline at end of file diff --git a/Lang/Perl/Integer-overflow b/Lang/Perl/Integer-overflow new file mode 120000 index 0000000000..a7dcb42007 --- /dev/null +++ b/Lang/Perl/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Perl \ No newline at end of file diff --git a/Lang/Perl/Iterated-digits-squaring b/Lang/Perl/Iterated-digits-squaring new file mode 120000 index 0000000000..fe3c3a0dae --- /dev/null +++ b/Lang/Perl/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Perl \ No newline at end of file diff --git a/Lang/Perl/Left-factorials b/Lang/Perl/Left-factorials new file mode 120000 index 0000000000..d63b1eb5a8 --- /dev/null +++ b/Lang/Perl/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Perl \ No newline at end of file diff --git a/Lang/Perl/Longest-increasing-subsequence b/Lang/Perl/Longest-increasing-subsequence new file mode 120000 index 0000000000..fd4997e2a8 --- /dev/null +++ b/Lang/Perl/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Perl \ No newline at end of file diff --git a/Lang/Perl/Ludic-numbers b/Lang/Perl/Ludic-numbers new file mode 120000 index 0000000000..772b466ebd --- /dev/null +++ b/Lang/Perl/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Perl \ No newline at end of file diff --git a/Lang/Perl/Maximum-triangle-path-sum b/Lang/Perl/Maximum-triangle-path-sum new file mode 120000 index 0000000000..a25cb2ef13 --- /dev/null +++ b/Lang/Perl/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Perl \ No newline at end of file diff --git a/Lang/Perl/Move-to-front-algorithm b/Lang/Perl/Move-to-front-algorithm new file mode 120000 index 0000000000..f4e43eba43 --- /dev/null +++ b/Lang/Perl/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/Munching-squares b/Lang/Perl/Munching-squares new file mode 120000 index 0000000000..8593cfbd93 --- /dev/null +++ b/Lang/Perl/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Perl \ No newline at end of file diff --git a/Lang/Perl/Narcissistic-decimal-number b/Lang/Perl/Narcissistic-decimal-number new file mode 120000 index 0000000000..23f3226cc5 --- /dev/null +++ b/Lang/Perl/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Perl \ No newline at end of file diff --git a/Lang/Perl/Natural-sorting b/Lang/Perl/Natural-sorting new file mode 120000 index 0000000000..ff41e26a60 --- /dev/null +++ b/Lang/Perl/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Perl \ No newline at end of file diff --git a/Lang/Perl/Nth b/Lang/Perl/Nth new file mode 120000 index 0000000000..f1b414b77d --- /dev/null +++ b/Lang/Perl/Nth @@ -0,0 +1 @@ +../../Task/Nth/Perl \ No newline at end of file diff --git a/Lang/Perl/Odd-word-problem b/Lang/Perl/Odd-word-problem new file mode 120000 index 0000000000..df8d33ccef --- /dev/null +++ b/Lang/Perl/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Perl \ No newline at end of file diff --git a/Lang/Perl/Old-lady-swallowed-a-fly b/Lang/Perl/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..3fbefd1e62 --- /dev/null +++ b/Lang/Perl/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Perl \ No newline at end of file diff --git a/Lang/Perl/Order-disjoint-list-items b/Lang/Perl/Order-disjoint-list-items new file mode 120000 index 0000000000..bd6060c201 --- /dev/null +++ b/Lang/Perl/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Perl \ No newline at end of file diff --git a/Lang/Perl/Paraffins b/Lang/Perl/Paraffins new file mode 120000 index 0000000000..34110a582d --- /dev/null +++ b/Lang/Perl/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Perl \ No newline at end of file diff --git a/Lang/Perl/Parse-an-IP-Address b/Lang/Perl/Parse-an-IP-Address new file mode 120000 index 0000000000..034fb13a15 --- /dev/null +++ b/Lang/Perl/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Perl \ No newline at end of file diff --git a/Lang/Perl/Percolation-Mean-run-density b/Lang/Perl/Percolation-Mean-run-density new file mode 120000 index 0000000000..1117e242b5 --- /dev/null +++ b/Lang/Perl/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Perl \ No newline at end of file diff --git a/Lang/Perl/Pernicious-numbers b/Lang/Perl/Pernicious-numbers new file mode 120000 index 0000000000..c9fe0fa755 --- /dev/null +++ b/Lang/Perl/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Perl \ No newline at end of file diff --git a/Lang/Perl/Phrase-reversals b/Lang/Perl/Phrase-reversals new file mode 120000 index 0000000000..4caaaf0657 --- /dev/null +++ b/Lang/Perl/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Perl \ No newline at end of file diff --git a/Lang/Perl/Quickselect-algorithm b/Lang/Perl/Quickselect-algorithm new file mode 120000 index 0000000000..1a7fa1af1b --- /dev/null +++ b/Lang/Perl/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/Rep-string b/Lang/Perl/Rep-string new file mode 120000 index 0000000000..879ed5f8fd --- /dev/null +++ b/Lang/Perl/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Reverse-words-in-a-string b/Lang/Perl/Reverse-words-in-a-string new file mode 120000 index 0000000000..af8ee67ce6 --- /dev/null +++ b/Lang/Perl/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Find-bare-lang-tags b/Lang/Perl/Rosetta-Code-Find-bare-lang-tags new file mode 120000 index 0000000000..c5d8ab2076 --- /dev/null +++ b/Lang/Perl/Rosetta-Code-Find-bare-lang-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-bare-lang-tags/Perl \ No newline at end of file diff --git a/Lang/Perl/Runge-Kutta-method b/Lang/Perl/Runge-Kutta-method new file mode 120000 index 0000000000..a1ab1d58a8 --- /dev/null +++ b/Lang/Perl/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Perl \ No newline at end of file diff --git a/Lang/Perl/Semiprime b/Lang/Perl/Semiprime new file mode 120000 index 0000000000..2a0356260b --- /dev/null +++ b/Lang/Perl/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Perl \ No newline at end of file diff --git a/Lang/Perl/Sparkline-in-unicode b/Lang/Perl/Sparkline-in-unicode new file mode 120000 index 0000000000..866129b76c --- /dev/null +++ b/Lang/Perl/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Perl \ No newline at end of file diff --git a/Lang/Perl/State-name-puzzle b/Lang/Perl/State-name-puzzle new file mode 120000 index 0000000000..0072bfb718 --- /dev/null +++ b/Lang/Perl/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Statistics-Basic b/Lang/Perl/Statistics-Basic new file mode 120000 index 0000000000..09ed46cb98 --- /dev/null +++ b/Lang/Perl/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Perl \ No newline at end of file diff --git a/Lang/Perl/Stern-Brocot-sequence b/Lang/Perl/Stern-Brocot-sequence new file mode 120000 index 0000000000..e6a67136ac --- /dev/null +++ b/Lang/Perl/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Perl \ No newline at end of file diff --git a/Lang/Perl/String-append b/Lang/Perl/String-append new file mode 120000 index 0000000000..e7ee653128 --- /dev/null +++ b/Lang/Perl/String-append @@ -0,0 +1 @@ +../../Task/String-append/Perl \ No newline at end of file diff --git a/Lang/Perl/String-matching b/Lang/Perl/String-matching new file mode 120000 index 0000000000..6ca7755c53 --- /dev/null +++ b/Lang/Perl/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Perl \ No newline at end of file diff --git a/Lang/Perl/String-prepend b/Lang/Perl/String-prepend new file mode 120000 index 0000000000..d2844045f6 --- /dev/null +++ b/Lang/Perl/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Perl \ No newline at end of file diff --git a/Lang/Perl/Sum-multiples-of-3-and-5 b/Lang/Perl/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..5f802fe7e4 --- /dev/null +++ b/Lang/Perl/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Perl \ No newline at end of file diff --git a/Lang/Perl/Textonyms b/Lang/Perl/Textonyms new file mode 120000 index 0000000000..d8d38ef90f --- /dev/null +++ b/Lang/Perl/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Perl \ No newline at end of file diff --git a/Lang/Perl/The-ISAAC-Cipher b/Lang/Perl/The-ISAAC-Cipher new file mode 120000 index 0000000000..cbc41c5f28 --- /dev/null +++ b/Lang/Perl/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Perl \ No newline at end of file diff --git a/Lang/Perl/The-Twelve-Days-of-Christmas b/Lang/Perl/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..075cdc1b1e --- /dev/null +++ b/Lang/Perl/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Perl \ No newline at end of file diff --git a/Lang/Perl/Ulam-spiral--for-primes- b/Lang/Perl/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..08945d4e23 --- /dev/null +++ b/Lang/Perl/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Perl \ No newline at end of file diff --git a/Lang/Perl/Zero-to-the-zero-power b/Lang/Perl/Zero-to-the-zero-power new file mode 120000 index 0000000000..9b8d9acfbe --- /dev/null +++ b/Lang/Perl/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/9-billion-names-of-God-the-integer b/Lang/PicoLisp/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..9abdd99475 --- /dev/null +++ b/Lang/PicoLisp/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/ABC-Problem b/Lang/PicoLisp/ABC-Problem new file mode 120000 index 0000000000..84ad78b7b3 --- /dev/null +++ b/Lang/PicoLisp/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/AKS-test-for-primes b/Lang/PicoLisp/AKS-test-for-primes new file mode 120000 index 0000000000..30f4b7e291 --- /dev/null +++ b/Lang/PicoLisp/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Almost-prime b/Lang/PicoLisp/Almost-prime new file mode 120000 index 0000000000..c7a6ccba9b --- /dev/null +++ b/Lang/PicoLisp/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Amb b/Lang/PicoLisp/Amb new file mode 120000 index 0000000000..f082907af2 --- /dev/null +++ b/Lang/PicoLisp/Amb @@ -0,0 +1 @@ +../../Task/Amb/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Append-a-record-to-the-end-of-a-text-file b/Lang/PicoLisp/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..3a916c21e9 --- /dev/null +++ b/Lang/PicoLisp/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Arithmetic-geometric-mean-Calculate-Pi b/Lang/PicoLisp/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..0541c426f6 --- /dev/null +++ b/Lang/PicoLisp/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Bernoulli-numbers b/Lang/PicoLisp/Bernoulli-numbers new file mode 120000 index 0000000000..4cabd42cc7 --- /dev/null +++ b/Lang/PicoLisp/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/CSV-data-manipulation b/Lang/PicoLisp/CSV-data-manipulation new file mode 120000 index 0000000000..941bc7b084 --- /dev/null +++ b/Lang/PicoLisp/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Calendar---for-REAL-programmers b/Lang/PicoLisp/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..a9bbf1cec5 --- /dev/null +++ b/Lang/PicoLisp/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Casting-out-nines b/Lang/PicoLisp/Casting-out-nines new file mode 120000 index 0000000000..482f79193f --- /dev/null +++ b/Lang/PicoLisp/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Catalan-numbers-Pascals-triangle b/Lang/PicoLisp/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..76ee6d9e70 --- /dev/null +++ b/Lang/PicoLisp/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Catamorphism b/Lang/PicoLisp/Catamorphism new file mode 120000 index 0000000000..d41dea5ca0 --- /dev/null +++ b/Lang/PicoLisp/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Chinese-remainder-theorem b/Lang/PicoLisp/Chinese-remainder-theorem new file mode 120000 index 0000000000..1998630a5c --- /dev/null +++ b/Lang/PicoLisp/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Closures-Value-capture b/Lang/PicoLisp/Closures-Value-capture new file mode 120000 index 0000000000..f87c04b868 --- /dev/null +++ b/Lang/PicoLisp/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Comma-quibbling b/Lang/PicoLisp/Comma-quibbling new file mode 120000 index 0000000000..876fb81d4e --- /dev/null +++ b/Lang/PicoLisp/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Draw-a-clock b/Lang/PicoLisp/Draw-a-clock new file mode 120000 index 0000000000..5f9495e719 --- /dev/null +++ b/Lang/PicoLisp/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/File-input-output b/Lang/PicoLisp/File-input-output new file mode 120000 index 0000000000..f36a21126a --- /dev/null +++ b/Lang/PicoLisp/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Find-the-last-Sunday-of-each-month b/Lang/PicoLisp/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..5f271b142e --- /dev/null +++ b/Lang/PicoLisp/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Generate-Chess960-starting-position b/Lang/PicoLisp/Generate-Chess960-starting-position new file mode 120000 index 0000000000..8e836193a6 --- /dev/null +++ b/Lang/PicoLisp/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Generate-lower-case-ASCII-alphabet b/Lang/PicoLisp/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..c27915089a --- /dev/null +++ b/Lang/PicoLisp/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/IBAN b/Lang/PicoLisp/IBAN new file mode 120000 index 0000000000..62ea095230 --- /dev/null +++ b/Lang/PicoLisp/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Ludic-numbers b/Lang/PicoLisp/Ludic-numbers new file mode 120000 index 0000000000..c4d70afa1b --- /dev/null +++ b/Lang/PicoLisp/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Narcissistic-decimal-number b/Lang/PicoLisp/Narcissistic-decimal-number new file mode 120000 index 0000000000..c9f11f857f --- /dev/null +++ b/Lang/PicoLisp/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Natural-sorting b/Lang/PicoLisp/Natural-sorting new file mode 120000 index 0000000000..4476711e4c --- /dev/null +++ b/Lang/PicoLisp/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Nth b/Lang/PicoLisp/Nth new file mode 120000 index 0000000000..a38e438437 --- /dev/null +++ b/Lang/PicoLisp/Nth @@ -0,0 +1 @@ +../../Task/Nth/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Odd-word-problem b/Lang/PicoLisp/Odd-word-problem new file mode 120000 index 0000000000..640bed26aa --- /dev/null +++ b/Lang/PicoLisp/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Old-lady-swallowed-a-fly b/Lang/PicoLisp/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..ff9fea1441 --- /dev/null +++ b/Lang/PicoLisp/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Parse-an-IP-Address b/Lang/PicoLisp/Parse-an-IP-Address new file mode 120000 index 0000000000..571e6d7f64 --- /dev/null +++ b/Lang/PicoLisp/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/RSA-code b/Lang/PicoLisp/RSA-code new file mode 120000 index 0000000000..8edc8833b2 --- /dev/null +++ b/Lang/PicoLisp/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Semiprime b/Lang/PicoLisp/Semiprime new file mode 120000 index 0000000000..df680df06a --- /dev/null +++ b/Lang/PicoLisp/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/State-name-puzzle b/Lang/PicoLisp/State-name-puzzle new file mode 120000 index 0000000000..20c419c13b --- /dev/null +++ b/Lang/PicoLisp/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Statistics-Basic b/Lang/PicoLisp/Statistics-Basic new file mode 120000 index 0000000000..5d894bd982 --- /dev/null +++ b/Lang/PicoLisp/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-append b/Lang/PicoLisp/String-append new file mode 120000 index 0000000000..eff41c611b --- /dev/null +++ b/Lang/PicoLisp/String-append @@ -0,0 +1 @@ +../../Task/String-append/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-matching b/Lang/PicoLisp/String-matching new file mode 120000 index 0000000000..3a288170d9 --- /dev/null +++ b/Lang/PicoLisp/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-prepend b/Lang/PicoLisp/String-prepend new file mode 120000 index 0000000000..1504b0db1d --- /dev/null +++ b/Lang/PicoLisp/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sum-multiples-of-3-and-5 b/Lang/PicoLisp/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..47028461c2 --- /dev/null +++ b/Lang/PicoLisp/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/The-ISAAC-Cipher b/Lang/PicoLisp/The-ISAAC-Cipher new file mode 120000 index 0000000000..c3e28e4f3a --- /dev/null +++ b/Lang/PicoLisp/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/The-Twelve-Days-of-Christmas b/Lang/PicoLisp/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..54099d78a5 --- /dev/null +++ b/Lang/PicoLisp/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/PicoLisp \ No newline at end of file diff --git a/Lang/Pike/Closures-Value-capture b/Lang/Pike/Closures-Value-capture new file mode 120000 index 0000000000..2f378f320b --- /dev/null +++ b/Lang/Pike/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Pike \ No newline at end of file diff --git a/Lang/Pike/Paraffins b/Lang/Pike/Paraffins new file mode 120000 index 0000000000..fce3996ba5 --- /dev/null +++ b/Lang/Pike/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Pike \ No newline at end of file diff --git a/Lang/Pop11/File-input-output b/Lang/Pop11/File-input-output new file mode 120000 index 0000000000..c9eff43ec3 --- /dev/null +++ b/Lang/Pop11/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Pop11 \ No newline at end of file diff --git a/Lang/PowerBASIC/ABC-Problem b/Lang/PowerBASIC/ABC-Problem new file mode 120000 index 0000000000..039676e1a4 --- /dev/null +++ b/Lang/PowerBASIC/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerShell/File-input-output b/Lang/PowerShell/File-input-output new file mode 120000 index 0000000000..b54d3c5626 --- /dev/null +++ b/Lang/PowerShell/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Heronian-triangles b/Lang/PowerShell/Heronian-triangles new file mode 120000 index 0000000000..046bcc6dc1 --- /dev/null +++ b/Lang/PowerShell/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-matching b/Lang/PowerShell/String-matching new file mode 120000 index 0000000000..1eeec59a1a --- /dev/null +++ b/Lang/PowerShell/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sum-multiples-of-3-and-5 b/Lang/PowerShell/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..765735058b --- /dev/null +++ b/Lang/PowerShell/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/The-Twelve-Days-of-Christmas b/Lang/PowerShell/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..a54c5f9099 --- /dev/null +++ b/Lang/PowerShell/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Zero-to-the-zero-power b/Lang/PowerShell/Zero-to-the-zero-power new file mode 120000 index 0000000000..d664269f52 --- /dev/null +++ b/Lang/PowerShell/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/ABC-Problem b/Lang/Prolog/ABC-Problem new file mode 120000 index 0000000000..052279454b --- /dev/null +++ b/Lang/Prolog/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/AKS-test-for-primes b/Lang/Prolog/AKS-test-for-primes new file mode 120000 index 0000000000..6b696daf54 --- /dev/null +++ b/Lang/Prolog/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Almost-prime b/Lang/Prolog/Almost-prime new file mode 120000 index 0000000000..2057977df6 --- /dev/null +++ b/Lang/Prolog/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Amb b/Lang/Prolog/Amb new file mode 120000 index 0000000000..cf43b43a98 --- /dev/null +++ b/Lang/Prolog/Amb @@ -0,0 +1 @@ +../../Task/Amb/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Benfords-law b/Lang/Prolog/Benfords-law new file mode 120000 index 0000000000..e0b03c02d5 --- /dev/null +++ b/Lang/Prolog/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Prolog \ No newline at end of file diff --git a/Lang/Prolog/CSV-data-manipulation b/Lang/Prolog/CSV-data-manipulation new file mode 120000 index 0000000000..bd3e9d39a2 --- /dev/null +++ b/Lang/Prolog/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Catamorphism b/Lang/Prolog/Catamorphism new file mode 120000 index 0000000000..58376993a2 --- /dev/null +++ b/Lang/Prolog/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Closures-Value-capture b/Lang/Prolog/Closures-Value-capture new file mode 120000 index 0000000000..29148f6658 --- /dev/null +++ b/Lang/Prolog/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Comma-quibbling b/Lang/Prolog/Comma-quibbling new file mode 120000 index 0000000000..bf50f2e5d6 --- /dev/null +++ b/Lang/Prolog/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Generate-lower-case-ASCII-alphabet b/Lang/Prolog/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..9602523572 --- /dev/null +++ b/Lang/Prolog/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Longest-increasing-subsequence b/Lang/Prolog/Longest-increasing-subsequence new file mode 120000 index 0000000000..09428a724e --- /dev/null +++ b/Lang/Prolog/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Maximum-triangle-path-sum b/Lang/Prolog/Maximum-triangle-path-sum new file mode 120000 index 0000000000..f2d7e434af --- /dev/null +++ b/Lang/Prolog/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Munching-squares b/Lang/Prolog/Munching-squares new file mode 120000 index 0000000000..04b5c48b83 --- /dev/null +++ b/Lang/Prolog/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Nth b/Lang/Prolog/Nth new file mode 120000 index 0000000000..d2de6181aa --- /dev/null +++ b/Lang/Prolog/Nth @@ -0,0 +1 @@ +../../Task/Nth/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Odd-word-problem b/Lang/Prolog/Odd-word-problem new file mode 120000 index 0000000000..e1b3314d2a --- /dev/null +++ b/Lang/Prolog/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Rep-string b/Lang/Prolog/Rep-string new file mode 120000 index 0000000000..254f3f7752 --- /dev/null +++ b/Lang/Prolog/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Solve-the-no-connection-puzzle b/Lang/Prolog/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..037e1d52eb --- /dev/null +++ b/Lang/Prolog/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/State-name-puzzle b/Lang/Prolog/State-name-puzzle new file mode 120000 index 0000000000..d9a74a33c0 --- /dev/null +++ b/Lang/Prolog/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/String-prepend b/Lang/Prolog/String-prepend new file mode 120000 index 0000000000..18252d644e --- /dev/null +++ b/Lang/Prolog/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sum-multiples-of-3-and-5 b/Lang/Prolog/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..a68eb5fa82 --- /dev/null +++ b/Lang/Prolog/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Prolog \ No newline at end of file diff --git a/Lang/PureBasic/Amb b/Lang/PureBasic/Amb new file mode 120000 index 0000000000..f736fa81b9 --- /dev/null +++ b/Lang/PureBasic/Amb @@ -0,0 +1 @@ +../../Task/Amb/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Draw-a-clock b/Lang/PureBasic/Draw-a-clock new file mode 120000 index 0000000000..3d33f65e80 --- /dev/null +++ b/Lang/PureBasic/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/File-input-output b/Lang/PureBasic/File-input-output new file mode 120000 index 0000000000..1b43d013a7 --- /dev/null +++ b/Lang/PureBasic/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Generate-lower-case-ASCII-alphabet b/Lang/PureBasic/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..6e3c824ec8 --- /dev/null +++ b/Lang/PureBasic/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Machine-code b/Lang/PureBasic/Machine-code new file mode 120000 index 0000000000..99da1f9912 --- /dev/null +++ b/Lang/PureBasic/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Munching-squares b/Lang/PureBasic/Munching-squares new file mode 120000 index 0000000000..67101b762b --- /dev/null +++ b/Lang/PureBasic/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Odd-word-problem b/Lang/PureBasic/Odd-word-problem new file mode 120000 index 0000000000..c02a8504da --- /dev/null +++ b/Lang/PureBasic/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Statistics-Basic b/Lang/PureBasic/Statistics-Basic new file mode 120000 index 0000000000..a8f0cbb11e --- /dev/null +++ b/Lang/PureBasic/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-append b/Lang/PureBasic/String-append new file mode 120000 index 0000000000..d0cfc20120 --- /dev/null +++ b/Lang/PureBasic/String-append @@ -0,0 +1 @@ +../../Task/String-append/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-matching b/Lang/PureBasic/String-matching new file mode 120000 index 0000000000..1c75fe7011 --- /dev/null +++ b/Lang/PureBasic/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-prepend b/Lang/PureBasic/String-prepend new file mode 120000 index 0000000000..643e3b4965 --- /dev/null +++ b/Lang/PureBasic/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PureBasic \ No newline at end of file diff --git a/Lang/Python/9-billion-names-of-God-the-integer b/Lang/Python/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..4ece4ad346 --- /dev/null +++ b/Lang/Python/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Python \ No newline at end of file diff --git a/Lang/Python/ABC-Problem b/Lang/Python/ABC-Problem new file mode 120000 index 0000000000..17d0b635db --- /dev/null +++ b/Lang/Python/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Python \ No newline at end of file diff --git a/Lang/Python/AKS-test-for-primes b/Lang/Python/AKS-test-for-primes new file mode 120000 index 0000000000..06e053132a --- /dev/null +++ b/Lang/Python/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Python \ No newline at end of file diff --git a/Lang/Python/Abundant,-deficient-and-perfect-number-classifications b/Lang/Python/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..4497dc39b5 --- /dev/null +++ b/Lang/Python/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Python \ No newline at end of file diff --git a/Lang/Python/Aliquot-sequence-classifications b/Lang/Python/Aliquot-sequence-classifications new file mode 120000 index 0000000000..8406232695 --- /dev/null +++ b/Lang/Python/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Python \ No newline at end of file diff --git a/Lang/Python/Almost-prime b/Lang/Python/Almost-prime new file mode 120000 index 0000000000..ab4a70ac92 --- /dev/null +++ b/Lang/Python/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Python \ No newline at end of file diff --git a/Lang/Python/Amb b/Lang/Python/Amb new file mode 120000 index 0000000000..2443d947c8 --- /dev/null +++ b/Lang/Python/Amb @@ -0,0 +1 @@ +../../Task/Amb/Python \ No newline at end of file diff --git a/Lang/Python/Amicable-pairs b/Lang/Python/Amicable-pairs new file mode 120000 index 0000000000..e0c25c9f7e --- /dev/null +++ b/Lang/Python/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Python \ No newline at end of file diff --git a/Lang/Python/Append-a-record-to-the-end-of-a-text-file b/Lang/Python/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..4081c5171e --- /dev/null +++ b/Lang/Python/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Python \ No newline at end of file diff --git a/Lang/Python/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Python/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..f6c56d4fda --- /dev/null +++ b/Lang/Python/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Python \ No newline at end of file diff --git a/Lang/Python/Benfords-law b/Lang/Python/Benfords-law new file mode 120000 index 0000000000..a5b5393a1e --- /dev/null +++ b/Lang/Python/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Python \ No newline at end of file diff --git a/Lang/Python/Bernoulli-numbers b/Lang/Python/Bernoulli-numbers new file mode 120000 index 0000000000..ae40dffc1b --- /dev/null +++ b/Lang/Python/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Python \ No newline at end of file diff --git a/Lang/Python/CSV-data-manipulation b/Lang/Python/CSV-data-manipulation new file mode 120000 index 0000000000..f6dab386a3 --- /dev/null +++ b/Lang/Python/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Python \ No newline at end of file diff --git a/Lang/Python/Casting-out-nines b/Lang/Python/Casting-out-nines new file mode 120000 index 0000000000..680d27c64a --- /dev/null +++ b/Lang/Python/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Python \ No newline at end of file diff --git a/Lang/Python/Catalan-numbers-Pascals-triangle b/Lang/Python/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..631ee5cb33 --- /dev/null +++ b/Lang/Python/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Python \ No newline at end of file diff --git a/Lang/Python/Catamorphism b/Lang/Python/Catamorphism new file mode 120000 index 0000000000..d10817d3ca --- /dev/null +++ b/Lang/Python/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Python \ No newline at end of file diff --git a/Lang/Python/Chinese-remainder-theorem b/Lang/Python/Chinese-remainder-theorem new file mode 120000 index 0000000000..bed6d4de77 --- /dev/null +++ b/Lang/Python/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Python \ No newline at end of file diff --git a/Lang/Python/Circles-of-given-radius-through-two-points b/Lang/Python/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..6e7895c56a --- /dev/null +++ b/Lang/Python/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Python \ No newline at end of file diff --git a/Lang/Python/Closures-Value-capture b/Lang/Python/Closures-Value-capture new file mode 120000 index 0000000000..369e10a918 --- /dev/null +++ b/Lang/Python/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Python \ No newline at end of file diff --git a/Lang/Python/Combinations-and-permutations b/Lang/Python/Combinations-and-permutations new file mode 120000 index 0000000000..6a899daf2e --- /dev/null +++ b/Lang/Python/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Python \ No newline at end of file diff --git a/Lang/Python/Comma-quibbling b/Lang/Python/Comma-quibbling new file mode 120000 index 0000000000..de5933980f --- /dev/null +++ b/Lang/Python/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Python \ No newline at end of file diff --git a/Lang/Python/Conjugate-transpose b/Lang/Python/Conjugate-transpose new file mode 120000 index 0000000000..3331b4108a --- /dev/null +++ b/Lang/Python/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Python \ No newline at end of file diff --git a/Lang/Python/Convert-decimal-number-to-rational b/Lang/Python/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..8cba7b305b --- /dev/null +++ b/Lang/Python/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Python \ No newline at end of file diff --git a/Lang/Python/Currying b/Lang/Python/Currying new file mode 120000 index 0000000000..4357939807 --- /dev/null +++ b/Lang/Python/Currying @@ -0,0 +1 @@ +../../Task/Currying/Python \ No newline at end of file diff --git a/Lang/Python/Digital-root-Multiplicative-digital-root b/Lang/Python/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..fe8d0d9717 --- /dev/null +++ b/Lang/Python/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Python \ No newline at end of file diff --git a/Lang/Python/Draw-a-clock b/Lang/Python/Draw-a-clock new file mode 120000 index 0000000000..a00a890cfd --- /dev/null +++ b/Lang/Python/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Python \ No newline at end of file diff --git a/Lang/Python/Extensible-prime-generator b/Lang/Python/Extensible-prime-generator new file mode 120000 index 0000000000..a571e121f9 --- /dev/null +++ b/Lang/Python/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Python \ No newline at end of file diff --git a/Lang/Python/Fibonacci-word b/Lang/Python/Fibonacci-word new file mode 120000 index 0000000000..515b5f9059 --- /dev/null +++ b/Lang/Python/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Python \ No newline at end of file diff --git a/Lang/Python/Fibonacci-word-fractal b/Lang/Python/Fibonacci-word-fractal new file mode 120000 index 0000000000..9ff2e105fb --- /dev/null +++ b/Lang/Python/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Python \ No newline at end of file diff --git a/Lang/Python/File-input-output b/Lang/Python/File-input-output new file mode 120000 index 0000000000..debed858e4 --- /dev/null +++ b/Lang/Python/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Python \ No newline at end of file diff --git a/Lang/Python/Find-the-last-Sunday-of-each-month b/Lang/Python/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..5338837cf1 --- /dev/null +++ b/Lang/Python/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Python \ No newline at end of file diff --git a/Lang/Python/Flipping-bits-game b/Lang/Python/Flipping-bits-game new file mode 120000 index 0000000000..76b1971c64 --- /dev/null +++ b/Lang/Python/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Python \ No newline at end of file diff --git a/Lang/Python/Fractran b/Lang/Python/Fractran new file mode 120000 index 0000000000..8548641cd8 --- /dev/null +++ b/Lang/Python/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Python \ No newline at end of file diff --git a/Lang/Python/Gaussian-elimination b/Lang/Python/Gaussian-elimination new file mode 120000 index 0000000000..ba2abaa0ea --- /dev/null +++ b/Lang/Python/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Python \ No newline at end of file diff --git a/Lang/Python/Generate-Chess960-starting-position b/Lang/Python/Generate-Chess960-starting-position new file mode 120000 index 0000000000..bd0a22c2e1 --- /dev/null +++ b/Lang/Python/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Python \ No newline at end of file diff --git a/Lang/Python/Generate-lower-case-ASCII-alphabet b/Lang/Python/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d5f2ac907c --- /dev/null +++ b/Lang/Python/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Python \ No newline at end of file diff --git a/Lang/Python/Hash-join b/Lang/Python/Hash-join new file mode 120000 index 0000000000..67346843a1 --- /dev/null +++ b/Lang/Python/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Python \ No newline at end of file diff --git a/Lang/Python/Hello-world-Newbie b/Lang/Python/Hello-world-Newbie new file mode 120000 index 0000000000..e99724eff5 --- /dev/null +++ b/Lang/Python/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Python \ No newline at end of file diff --git a/Lang/Python/Heronian-triangles b/Lang/Python/Heronian-triangles new file mode 120000 index 0000000000..2174c519a2 --- /dev/null +++ b/Lang/Python/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Python \ No newline at end of file diff --git a/Lang/Python/Hickerson-series-of-almost-integers b/Lang/Python/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..f43873715d --- /dev/null +++ b/Lang/Python/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Python \ No newline at end of file diff --git a/Lang/Python/IBAN b/Lang/Python/IBAN new file mode 120000 index 0000000000..c024793555 --- /dev/null +++ b/Lang/Python/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Python \ No newline at end of file diff --git a/Lang/Python/Integer-overflow b/Lang/Python/Integer-overflow new file mode 120000 index 0000000000..c443c370b6 --- /dev/null +++ b/Lang/Python/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Python \ No newline at end of file diff --git a/Lang/Python/Iterated-digits-squaring b/Lang/Python/Iterated-digits-squaring new file mode 120000 index 0000000000..5667be9b16 --- /dev/null +++ b/Lang/Python/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Python \ No newline at end of file diff --git a/Lang/Python/K-d-tree b/Lang/Python/K-d-tree new file mode 120000 index 0000000000..a0f979c1a7 --- /dev/null +++ b/Lang/Python/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Python \ No newline at end of file diff --git a/Lang/Python/Left-factorials b/Lang/Python/Left-factorials new file mode 120000 index 0000000000..313611cf34 --- /dev/null +++ b/Lang/Python/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Python \ No newline at end of file diff --git a/Lang/Python/Longest-increasing-subsequence b/Lang/Python/Longest-increasing-subsequence new file mode 120000 index 0000000000..322337e22b --- /dev/null +++ b/Lang/Python/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Python \ No newline at end of file diff --git a/Lang/Python/Ludic-numbers b/Lang/Python/Ludic-numbers new file mode 120000 index 0000000000..6155a34cd7 --- /dev/null +++ b/Lang/Python/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Machine-code b/Lang/Python/Machine-code new file mode 120000 index 0000000000..0858f744be --- /dev/null +++ b/Lang/Python/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Python \ No newline at end of file diff --git a/Lang/Python/Magic-squares-of-odd-order b/Lang/Python/Magic-squares-of-odd-order new file mode 120000 index 0000000000..ecf54f2448 --- /dev/null +++ b/Lang/Python/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Python \ No newline at end of file diff --git a/Lang/Python/Make-directory-path b/Lang/Python/Make-directory-path new file mode 120000 index 0000000000..18106be38f --- /dev/null +++ b/Lang/Python/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Python \ No newline at end of file diff --git a/Lang/Python/Maximum-triangle-path-sum b/Lang/Python/Maximum-triangle-path-sum new file mode 120000 index 0000000000..7f512f888f --- /dev/null +++ b/Lang/Python/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Python \ No newline at end of file diff --git a/Lang/Python/Move-to-front-algorithm b/Lang/Python/Move-to-front-algorithm new file mode 120000 index 0000000000..ff81bd655f --- /dev/null +++ b/Lang/Python/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Python \ No newline at end of file diff --git a/Lang/Python/Munching-squares b/Lang/Python/Munching-squares new file mode 120000 index 0000000000..071dbc096b --- /dev/null +++ b/Lang/Python/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Python \ No newline at end of file diff --git a/Lang/Python/Narcissistic-decimal-number b/Lang/Python/Narcissistic-decimal-number new file mode 120000 index 0000000000..acefe34315 --- /dev/null +++ b/Lang/Python/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Python \ No newline at end of file diff --git a/Lang/Python/Natural-sorting b/Lang/Python/Natural-sorting new file mode 120000 index 0000000000..dd7a398ff3 --- /dev/null +++ b/Lang/Python/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Python \ No newline at end of file diff --git a/Lang/Python/Nth b/Lang/Python/Nth new file mode 120000 index 0000000000..d2922b3bea --- /dev/null +++ b/Lang/Python/Nth @@ -0,0 +1 @@ +../../Task/Nth/Python \ No newline at end of file diff --git a/Lang/Python/Odd-word-problem b/Lang/Python/Odd-word-problem new file mode 120000 index 0000000000..940753839c --- /dev/null +++ b/Lang/Python/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Python \ No newline at end of file diff --git a/Lang/Python/Old-lady-swallowed-a-fly b/Lang/Python/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..841d23d865 --- /dev/null +++ b/Lang/Python/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Python \ No newline at end of file diff --git a/Lang/Python/Order-disjoint-list-items b/Lang/Python/Order-disjoint-list-items new file mode 120000 index 0000000000..95703346ad --- /dev/null +++ b/Lang/Python/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Python \ No newline at end of file diff --git a/Lang/Python/Paraffins b/Lang/Python/Paraffins new file mode 120000 index 0000000000..7b3c429f85 --- /dev/null +++ b/Lang/Python/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Python \ No newline at end of file diff --git a/Lang/Python/Parse-an-IP-Address b/Lang/Python/Parse-an-IP-Address new file mode 120000 index 0000000000..f83e176dec --- /dev/null +++ b/Lang/Python/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Python \ No newline at end of file diff --git a/Lang/Python/Penneys-game b/Lang/Python/Penneys-game new file mode 120000 index 0000000000..4df53cbc23 --- /dev/null +++ b/Lang/Python/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Python \ No newline at end of file diff --git a/Lang/Python/Percolation-Bond-percolation b/Lang/Python/Percolation-Bond-percolation new file mode 120000 index 0000000000..5fefbf7ddf --- /dev/null +++ b/Lang/Python/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Python \ No newline at end of file diff --git a/Lang/Python/Percolation-Mean-cluster-density b/Lang/Python/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..8f43e2e6fc --- /dev/null +++ b/Lang/Python/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Python \ No newline at end of file diff --git a/Lang/Python/Percolation-Mean-run-density b/Lang/Python/Percolation-Mean-run-density new file mode 120000 index 0000000000..d5103e5821 --- /dev/null +++ b/Lang/Python/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Python \ No newline at end of file diff --git a/Lang/Python/Percolation-Site-percolation b/Lang/Python/Percolation-Site-percolation new file mode 120000 index 0000000000..23e8c1fa4a --- /dev/null +++ b/Lang/Python/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Python \ No newline at end of file diff --git a/Lang/Python/Permutations-Rank-of-a-permutation b/Lang/Python/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..39bcfa30b6 --- /dev/null +++ b/Lang/Python/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Python \ No newline at end of file diff --git a/Lang/Python/Pernicious-numbers b/Lang/Python/Pernicious-numbers new file mode 120000 index 0000000000..21114f043c --- /dev/null +++ b/Lang/Python/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Phrase-reversals b/Lang/Python/Phrase-reversals new file mode 120000 index 0000000000..c58b3dbc10 --- /dev/null +++ b/Lang/Python/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Python \ No newline at end of file diff --git a/Lang/Python/Quickselect-algorithm b/Lang/Python/Quickselect-algorithm new file mode 120000 index 0000000000..cc5bcd7f7f --- /dev/null +++ b/Lang/Python/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Python \ No newline at end of file diff --git a/Lang/Python/RSA-code b/Lang/Python/RSA-code new file mode 120000 index 0000000000..e1ee0e469d --- /dev/null +++ b/Lang/Python/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Python \ No newline at end of file diff --git a/Lang/Python/Ranking-methods b/Lang/Python/Ranking-methods new file mode 120000 index 0000000000..d1e06e13cc --- /dev/null +++ b/Lang/Python/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Python \ No newline at end of file diff --git a/Lang/Python/Rep-string b/Lang/Python/Rep-string new file mode 120000 index 0000000000..496c7e685d --- /dev/null +++ b/Lang/Python/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Python \ No newline at end of file diff --git a/Lang/Python/Reverse-words-in-a-string b/Lang/Python/Reverse-words-in-a-string new file mode 120000 index 0000000000..0b2cbde04b --- /dev/null +++ b/Lang/Python/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Python \ No newline at end of file diff --git a/Lang/Python/Runge-Kutta-method b/Lang/Python/Runge-Kutta-method new file mode 120000 index 0000000000..c02df96fff --- /dev/null +++ b/Lang/Python/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Python \ No newline at end of file diff --git a/Lang/Python/Semiprime b/Lang/Python/Semiprime new file mode 120000 index 0000000000..42e4ce42eb --- /dev/null +++ b/Lang/Python/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Python \ No newline at end of file diff --git a/Lang/Python/Solve-the-no-connection-puzzle b/Lang/Python/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..63ca0567eb --- /dev/null +++ b/Lang/Python/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Sparkline-in-unicode b/Lang/Python/Sparkline-in-unicode new file mode 120000 index 0000000000..5d389a1b43 --- /dev/null +++ b/Lang/Python/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Python \ No newline at end of file diff --git a/Lang/Python/State-name-puzzle b/Lang/Python/State-name-puzzle new file mode 120000 index 0000000000..feef118df1 --- /dev/null +++ b/Lang/Python/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Statistics-Basic b/Lang/Python/Statistics-Basic new file mode 120000 index 0000000000..5b37498522 --- /dev/null +++ b/Lang/Python/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Python \ No newline at end of file diff --git a/Lang/Python/Stern-Brocot-sequence b/Lang/Python/Stern-Brocot-sequence new file mode 120000 index 0000000000..e7bd0b0e22 --- /dev/null +++ b/Lang/Python/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Python \ No newline at end of file diff --git a/Lang/Python/String-append b/Lang/Python/String-append new file mode 120000 index 0000000000..415b5fa1af --- /dev/null +++ b/Lang/Python/String-append @@ -0,0 +1 @@ +../../Task/String-append/Python \ No newline at end of file diff --git a/Lang/Python/String-matching b/Lang/Python/String-matching new file mode 120000 index 0000000000..b8f46996af --- /dev/null +++ b/Lang/Python/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Python \ No newline at end of file diff --git a/Lang/Python/String-prepend b/Lang/Python/String-prepend new file mode 120000 index 0000000000..0ac084b26c --- /dev/null +++ b/Lang/Python/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Python \ No newline at end of file diff --git a/Lang/Python/Sum-multiples-of-3-and-5 b/Lang/Python/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..ba7d618bd5 --- /dev/null +++ b/Lang/Python/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Python \ No newline at end of file diff --git a/Lang/Python/Textonyms b/Lang/Python/Textonyms new file mode 120000 index 0000000000..cf55e80af8 --- /dev/null +++ b/Lang/Python/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Python \ No newline at end of file diff --git a/Lang/Python/The-ISAAC-Cipher b/Lang/Python/The-ISAAC-Cipher new file mode 120000 index 0000000000..929cb43ff7 --- /dev/null +++ b/Lang/Python/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Python \ No newline at end of file diff --git a/Lang/Python/The-Twelve-Days-of-Christmas b/Lang/Python/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..88dfa004d7 --- /dev/null +++ b/Lang/Python/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Python \ No newline at end of file diff --git a/Lang/Python/Total-circles-area b/Lang/Python/Total-circles-area new file mode 120000 index 0000000000..5618334f03 --- /dev/null +++ b/Lang/Python/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Python \ No newline at end of file diff --git a/Lang/Python/Ulam-spiral--for-primes- b/Lang/Python/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..ca13dbd4a9 --- /dev/null +++ b/Lang/Python/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Python \ No newline at end of file diff --git a/Lang/Python/Unix-ls b/Lang/Python/Unix-ls new file mode 120000 index 0000000000..ccb887ff0f --- /dev/null +++ b/Lang/Python/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Python \ No newline at end of file diff --git a/Lang/Python/Vogels-approximation-method b/Lang/Python/Vogels-approximation-method new file mode 120000 index 0000000000..dcfccc8d31 --- /dev/null +++ b/Lang/Python/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Python \ No newline at end of file diff --git a/Lang/Python/World-Cup-group-stage b/Lang/Python/World-Cup-group-stage new file mode 120000 index 0000000000..946517c66a --- /dev/null +++ b/Lang/Python/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Python \ No newline at end of file diff --git a/Lang/Python/Zero-to-the-zero-power b/Lang/Python/Zero-to-the-zero-power new file mode 120000 index 0000000000..495ccd08d3 --- /dev/null +++ b/Lang/Python/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Python \ No newline at end of file diff --git a/Lang/Python/Zhang-Suen-thinning-algorithm b/Lang/Python/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..d1cf149ed6 --- /dev/null +++ b/Lang/Python/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Python \ No newline at end of file diff --git a/Lang/R/ABC-Problem b/Lang/R/ABC-Problem new file mode 120000 index 0000000000..ea22bce862 --- /dev/null +++ b/Lang/R/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/R \ No newline at end of file diff --git a/Lang/R/Amb b/Lang/R/Amb new file mode 120000 index 0000000000..eeb6cf8667 --- /dev/null +++ b/Lang/R/Amb @@ -0,0 +1 @@ +../../Task/Amb/R \ No newline at end of file diff --git a/Lang/R/Benfords-law b/Lang/R/Benfords-law new file mode 120000 index 0000000000..fbcb9ff70b --- /dev/null +++ b/Lang/R/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/R \ No newline at end of file diff --git a/Lang/R/CSV-data-manipulation b/Lang/R/CSV-data-manipulation new file mode 120000 index 0000000000..2898e0b6a4 --- /dev/null +++ b/Lang/R/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/R \ No newline at end of file diff --git a/Lang/R/Chinese-remainder-theorem b/Lang/R/Chinese-remainder-theorem new file mode 120000 index 0000000000..3740cf9807 --- /dev/null +++ b/Lang/R/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/R \ No newline at end of file diff --git a/Lang/R/Closures-Value-capture b/Lang/R/Closures-Value-capture new file mode 120000 index 0000000000..3d37a7f4ac --- /dev/null +++ b/Lang/R/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/R \ No newline at end of file diff --git a/Lang/R/Fibonacci-word b/Lang/R/Fibonacci-word new file mode 120000 index 0000000000..364f80d99a --- /dev/null +++ b/Lang/R/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/R \ No newline at end of file diff --git a/Lang/R/File-input-output b/Lang/R/File-input-output new file mode 120000 index 0000000000..806f89acaa --- /dev/null +++ b/Lang/R/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/R \ No newline at end of file diff --git a/Lang/R/Nth b/Lang/R/Nth new file mode 120000 index 0000000000..06b36e6d40 --- /dev/null +++ b/Lang/R/Nth @@ -0,0 +1 @@ +../../Task/Nth/R \ No newline at end of file diff --git a/Lang/R/Sum-multiples-of-3-and-5 b/Lang/R/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..4dd3fd8b04 --- /dev/null +++ b/Lang/R/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/R \ No newline at end of file diff --git a/Lang/REALbasic/File-input-output b/Lang/REALbasic/File-input-output new file mode 120000 index 0000000000..569cf6b6d9 --- /dev/null +++ b/Lang/REALbasic/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/REALbasic \ No newline at end of file diff --git a/Lang/REBOL/Comma-quibbling b/Lang/REBOL/Comma-quibbling new file mode 120000 index 0000000000..b2f7530541 --- /dev/null +++ b/Lang/REBOL/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-input-output b/Lang/REBOL/File-input-output new file mode 120000 index 0000000000..30e510fb5d --- /dev/null +++ b/Lang/REBOL/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Find-the-last-Sunday-of-each-month b/Lang/REBOL/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..c54d330170 --- /dev/null +++ b/Lang/REBOL/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REXX/9-billion-names-of-God-the-integer b/Lang/REXX/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..5ad3d09d79 --- /dev/null +++ b/Lang/REXX/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/REXX \ No newline at end of file diff --git a/Lang/REXX/ABC-Problem b/Lang/REXX/ABC-Problem new file mode 120000 index 0000000000..b233d5ead7 --- /dev/null +++ b/Lang/REXX/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/REXX \ No newline at end of file diff --git a/Lang/REXX/AKS-test-for-primes b/Lang/REXX/AKS-test-for-primes new file mode 120000 index 0000000000..37361fab89 --- /dev/null +++ b/Lang/REXX/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Aliquot-sequence-classifications b/Lang/REXX/Aliquot-sequence-classifications new file mode 120000 index 0000000000..8307ba806a --- /dev/null +++ b/Lang/REXX/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/REXX \ No newline at end of file diff --git a/Lang/REXX/Almost-prime b/Lang/REXX/Almost-prime new file mode 120000 index 0000000000..9114a0636c --- /dev/null +++ b/Lang/REXX/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/REXX \ No newline at end of file diff --git a/Lang/REXX/Amb b/Lang/REXX/Amb new file mode 120000 index 0000000000..e7e8da0eb8 --- /dev/null +++ b/Lang/REXX/Amb @@ -0,0 +1 @@ +../../Task/Amb/REXX \ No newline at end of file diff --git a/Lang/REXX/Amicable-pairs b/Lang/REXX/Amicable-pairs new file mode 120000 index 0000000000..3143c7c53c --- /dev/null +++ b/Lang/REXX/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/REXX \ No newline at end of file diff --git a/Lang/REXX/Append-a-record-to-the-end-of-a-text-file b/Lang/REXX/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..d24387f339 --- /dev/null +++ b/Lang/REXX/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Arithmetic-geometric-mean-Calculate-Pi b/Lang/REXX/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..fa13ba9a84 --- /dev/null +++ b/Lang/REXX/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/REXX \ No newline at end of file diff --git a/Lang/REXX/Benfords-law b/Lang/REXX/Benfords-law new file mode 120000 index 0000000000..0d274e5c41 --- /dev/null +++ b/Lang/REXX/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/REXX \ No newline at end of file diff --git a/Lang/REXX/Bernoulli-numbers b/Lang/REXX/Bernoulli-numbers new file mode 120000 index 0000000000..fe50c8d1d3 --- /dev/null +++ b/Lang/REXX/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/CSV-data-manipulation b/Lang/REXX/CSV-data-manipulation new file mode 120000 index 0000000000..bf00322662 --- /dev/null +++ b/Lang/REXX/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/REXX \ No newline at end of file diff --git a/Lang/REXX/Calendar---for-REAL-programmers b/Lang/REXX/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..fbf41de075 --- /dev/null +++ b/Lang/REXX/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/REXX \ No newline at end of file diff --git a/Lang/REXX/Casting-out-nines b/Lang/REXX/Casting-out-nines new file mode 120000 index 0000000000..caed618ed0 --- /dev/null +++ b/Lang/REXX/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/REXX \ No newline at end of file diff --git a/Lang/REXX/Catalan-numbers-Pascals-triangle b/Lang/REXX/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..7fc3be76e6 --- /dev/null +++ b/Lang/REXX/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/REXX \ No newline at end of file diff --git a/Lang/REXX/Catamorphism b/Lang/REXX/Catamorphism new file mode 120000 index 0000000000..c9120bd890 --- /dev/null +++ b/Lang/REXX/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/REXX \ No newline at end of file diff --git a/Lang/REXX/Chinese-remainder-theorem b/Lang/REXX/Chinese-remainder-theorem new file mode 120000 index 0000000000..b5f01c0971 --- /dev/null +++ b/Lang/REXX/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/REXX \ No newline at end of file diff --git a/Lang/REXX/Circles-of-given-radius-through-two-points b/Lang/REXX/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..e398e611a5 --- /dev/null +++ b/Lang/REXX/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/REXX \ No newline at end of file diff --git a/Lang/REXX/Closures-Value-capture b/Lang/REXX/Closures-Value-capture new file mode 120000 index 0000000000..709f21d7b1 --- /dev/null +++ b/Lang/REXX/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/REXX \ No newline at end of file diff --git a/Lang/REXX/Combinations-and-permutations b/Lang/REXX/Combinations-and-permutations new file mode 120000 index 0000000000..ebf0a00bd3 --- /dev/null +++ b/Lang/REXX/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/REXX \ No newline at end of file diff --git a/Lang/REXX/Comma-quibbling b/Lang/REXX/Comma-quibbling new file mode 120000 index 0000000000..fe8b120114 --- /dev/null +++ b/Lang/REXX/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/REXX \ No newline at end of file diff --git a/Lang/REXX/Conjugate-transpose b/Lang/REXX/Conjugate-transpose new file mode 120000 index 0000000000..ad9621cc10 --- /dev/null +++ b/Lang/REXX/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/REXX \ No newline at end of file diff --git a/Lang/REXX/Convert-decimal-number-to-rational b/Lang/REXX/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..2afd3dd741 --- /dev/null +++ b/Lang/REXX/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/REXX \ No newline at end of file diff --git a/Lang/REXX/Currying b/Lang/REXX/Currying new file mode 120000 index 0000000000..3c68456c21 --- /dev/null +++ b/Lang/REXX/Currying @@ -0,0 +1 @@ +../../Task/Currying/REXX \ No newline at end of file diff --git a/Lang/REXX/Digital-root-Multiplicative-digital-root b/Lang/REXX/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..736e65429a --- /dev/null +++ b/Lang/REXX/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/REXX \ No newline at end of file diff --git a/Lang/REXX/Draw-a-clock b/Lang/REXX/Draw-a-clock new file mode 120000 index 0000000000..3f7a97c39d --- /dev/null +++ b/Lang/REXX/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/REXX \ No newline at end of file diff --git a/Lang/REXX/Extensible-prime-generator b/Lang/REXX/Extensible-prime-generator new file mode 120000 index 0000000000..be9243ae70 --- /dev/null +++ b/Lang/REXX/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/REXX \ No newline at end of file diff --git a/Lang/REXX/Fibonacci-word b/Lang/REXX/Fibonacci-word new file mode 120000 index 0000000000..9b90790b83 --- /dev/null +++ b/Lang/REXX/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/REXX \ No newline at end of file diff --git a/Lang/REXX/Fibonacci-word-fractal b/Lang/REXX/Fibonacci-word-fractal new file mode 120000 index 0000000000..99bb62cc6c --- /dev/null +++ b/Lang/REXX/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/REXX \ No newline at end of file diff --git a/Lang/REXX/File-input-output b/Lang/REXX/File-input-output new file mode 120000 index 0000000000..3a45b1ec58 --- /dev/null +++ b/Lang/REXX/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/REXX \ No newline at end of file diff --git a/Lang/REXX/Find-the-last-Sunday-of-each-month b/Lang/REXX/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..14887968cc --- /dev/null +++ b/Lang/REXX/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/REXX \ No newline at end of file diff --git a/Lang/REXX/Flipping-bits-game b/Lang/REXX/Flipping-bits-game new file mode 120000 index 0000000000..9310002c87 --- /dev/null +++ b/Lang/REXX/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/REXX \ No newline at end of file diff --git a/Lang/REXX/Fractran b/Lang/REXX/Fractran new file mode 120000 index 0000000000..202c9bcb75 --- /dev/null +++ b/Lang/REXX/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/REXX \ No newline at end of file diff --git a/Lang/REXX/Gaussian-elimination b/Lang/REXX/Gaussian-elimination new file mode 120000 index 0000000000..2c3e2c072b --- /dev/null +++ b/Lang/REXX/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/REXX \ No newline at end of file diff --git a/Lang/REXX/Generate-Chess960-starting-position b/Lang/REXX/Generate-Chess960-starting-position new file mode 120000 index 0000000000..a3625bc2a7 --- /dev/null +++ b/Lang/REXX/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/REXX \ No newline at end of file diff --git a/Lang/REXX/Generate-lower-case-ASCII-alphabet b/Lang/REXX/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..c9f274710b --- /dev/null +++ b/Lang/REXX/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/REXX \ No newline at end of file diff --git a/Lang/REXX/Hash-join b/Lang/REXX/Hash-join new file mode 120000 index 0000000000..b5b7e1a63e --- /dev/null +++ b/Lang/REXX/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/REXX \ No newline at end of file diff --git a/Lang/REXX/Hello-world-Newbie b/Lang/REXX/Hello-world-Newbie new file mode 120000 index 0000000000..219058c8cc --- /dev/null +++ b/Lang/REXX/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/REXX \ No newline at end of file diff --git a/Lang/REXX/Heronian-triangles b/Lang/REXX/Heronian-triangles new file mode 120000 index 0000000000..9c1244a173 --- /dev/null +++ b/Lang/REXX/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/REXX \ No newline at end of file diff --git a/Lang/REXX/Hickerson-series-of-almost-integers b/Lang/REXX/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..8fc1748b19 --- /dev/null +++ b/Lang/REXX/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/REXX \ No newline at end of file diff --git a/Lang/REXX/IBAN b/Lang/REXX/IBAN new file mode 120000 index 0000000000..d1f1669b76 --- /dev/null +++ b/Lang/REXX/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/REXX \ No newline at end of file diff --git a/Lang/REXX/Integer-overflow b/Lang/REXX/Integer-overflow new file mode 120000 index 0000000000..4d4fac4681 --- /dev/null +++ b/Lang/REXX/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/REXX \ No newline at end of file diff --git a/Lang/REXX/Iterated-digits-squaring b/Lang/REXX/Iterated-digits-squaring new file mode 120000 index 0000000000..86301b8ae9 --- /dev/null +++ b/Lang/REXX/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/REXX \ No newline at end of file diff --git a/Lang/REXX/Left-factorials b/Lang/REXX/Left-factorials new file mode 120000 index 0000000000..fda929295a --- /dev/null +++ b/Lang/REXX/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/REXX \ No newline at end of file diff --git a/Lang/REXX/Ludic-numbers b/Lang/REXX/Ludic-numbers new file mode 120000 index 0000000000..75d57cbf89 --- /dev/null +++ b/Lang/REXX/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Magic-squares-of-odd-order b/Lang/REXX/Magic-squares-of-odd-order new file mode 120000 index 0000000000..06f80670e5 --- /dev/null +++ b/Lang/REXX/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/REXX \ No newline at end of file diff --git a/Lang/REXX/Make-directory-path b/Lang/REXX/Make-directory-path new file mode 120000 index 0000000000..811fa4fe4b --- /dev/null +++ b/Lang/REXX/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/REXX \ No newline at end of file diff --git a/Lang/REXX/Maximum-triangle-path-sum b/Lang/REXX/Maximum-triangle-path-sum new file mode 120000 index 0000000000..259e55e547 --- /dev/null +++ b/Lang/REXX/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/REXX \ No newline at end of file diff --git a/Lang/REXX/Move-to-front-algorithm b/Lang/REXX/Move-to-front-algorithm new file mode 120000 index 0000000000..6cef35cf19 --- /dev/null +++ b/Lang/REXX/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/REXX \ No newline at end of file diff --git a/Lang/REXX/Narcissistic-decimal-number b/Lang/REXX/Narcissistic-decimal-number new file mode 120000 index 0000000000..11a4e22ae1 --- /dev/null +++ b/Lang/REXX/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/REXX \ No newline at end of file diff --git a/Lang/REXX/Nth b/Lang/REXX/Nth new file mode 120000 index 0000000000..15ba3e9755 --- /dev/null +++ b/Lang/REXX/Nth @@ -0,0 +1 @@ +../../Task/Nth/REXX \ No newline at end of file diff --git a/Lang/REXX/Odd-word-problem b/Lang/REXX/Odd-word-problem new file mode 120000 index 0000000000..303f577dd9 --- /dev/null +++ b/Lang/REXX/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/REXX \ No newline at end of file diff --git a/Lang/REXX/Old-lady-swallowed-a-fly b/Lang/REXX/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..9caab24816 --- /dev/null +++ b/Lang/REXX/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/REXX \ No newline at end of file diff --git a/Lang/REXX/Order-disjoint-list-items b/Lang/REXX/Order-disjoint-list-items new file mode 120000 index 0000000000..66372bede6 --- /dev/null +++ b/Lang/REXX/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/REXX \ No newline at end of file diff --git a/Lang/REXX/Paraffins b/Lang/REXX/Paraffins new file mode 120000 index 0000000000..98ccd950a2 --- /dev/null +++ b/Lang/REXX/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/REXX \ No newline at end of file diff --git a/Lang/REXX/Parse-an-IP-Address b/Lang/REXX/Parse-an-IP-Address new file mode 120000 index 0000000000..0c329dcd23 --- /dev/null +++ b/Lang/REXX/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/REXX \ No newline at end of file diff --git a/Lang/REXX/Penneys-game b/Lang/REXX/Penneys-game new file mode 120000 index 0000000000..d613c8f4d4 --- /dev/null +++ b/Lang/REXX/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/REXX \ No newline at end of file diff --git a/Lang/REXX/Permutations-Rank-of-a-permutation b/Lang/REXX/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..a006d58d6e --- /dev/null +++ b/Lang/REXX/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/REXX \ No newline at end of file diff --git a/Lang/REXX/Pernicious-numbers b/Lang/REXX/Pernicious-numbers new file mode 120000 index 0000000000..516773046f --- /dev/null +++ b/Lang/REXX/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Phrase-reversals b/Lang/REXX/Phrase-reversals new file mode 120000 index 0000000000..fb720d4d1c --- /dev/null +++ b/Lang/REXX/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/REXX \ No newline at end of file diff --git a/Lang/REXX/Quickselect-algorithm b/Lang/REXX/Quickselect-algorithm new file mode 120000 index 0000000000..ef4c8900cf --- /dev/null +++ b/Lang/REXX/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/REXX \ No newline at end of file diff --git a/Lang/REXX/Rep-string b/Lang/REXX/Rep-string new file mode 120000 index 0000000000..b155527c95 --- /dev/null +++ b/Lang/REXX/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Reverse-words-in-a-string b/Lang/REXX/Reverse-words-in-a-string new file mode 120000 index 0000000000..317a0cfbbd --- /dev/null +++ b/Lang/REXX/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Runge-Kutta-method b/Lang/REXX/Runge-Kutta-method new file mode 120000 index 0000000000..95816fd7ae --- /dev/null +++ b/Lang/REXX/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/REXX \ No newline at end of file diff --git a/Lang/REXX/Semiprime b/Lang/REXX/Semiprime new file mode 120000 index 0000000000..96972017e2 --- /dev/null +++ b/Lang/REXX/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/REXX \ No newline at end of file diff --git a/Lang/REXX/Sequence-of-primes-by-Trial-Division b/Lang/REXX/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..c334f9492f --- /dev/null +++ b/Lang/REXX/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/REXX \ No newline at end of file diff --git a/Lang/REXX/Solve-a-Holy-Knights-tour b/Lang/REXX/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..b45c116e70 --- /dev/null +++ b/Lang/REXX/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/REXX \ No newline at end of file diff --git a/Lang/REXX/Solve-a-Hopido-puzzle b/Lang/REXX/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..37591c1f37 --- /dev/null +++ b/Lang/REXX/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Solve-a-Numbrix-puzzle b/Lang/REXX/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..86a629cb3f --- /dev/null +++ b/Lang/REXX/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Solve-the-no-connection-puzzle b/Lang/REXX/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..1a41d78406 --- /dev/null +++ b/Lang/REXX/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Sparkline-in-unicode b/Lang/REXX/Sparkline-in-unicode new file mode 120000 index 0000000000..5366195abd --- /dev/null +++ b/Lang/REXX/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/REXX \ No newline at end of file diff --git a/Lang/REXX/State-name-puzzle b/Lang/REXX/State-name-puzzle new file mode 120000 index 0000000000..614adb2956 --- /dev/null +++ b/Lang/REXX/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Statistics-Basic b/Lang/REXX/Statistics-Basic new file mode 120000 index 0000000000..bfa9cf1908 --- /dev/null +++ b/Lang/REXX/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/REXX \ No newline at end of file diff --git a/Lang/REXX/Stern-Brocot-sequence b/Lang/REXX/Stern-Brocot-sequence new file mode 120000 index 0000000000..60449b30ec --- /dev/null +++ b/Lang/REXX/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/REXX \ No newline at end of file diff --git a/Lang/REXX/String-append b/Lang/REXX/String-append new file mode 120000 index 0000000000..cc30f0f14e --- /dev/null +++ b/Lang/REXX/String-append @@ -0,0 +1 @@ +../../Task/String-append/REXX \ No newline at end of file diff --git a/Lang/REXX/String-matching b/Lang/REXX/String-matching new file mode 120000 index 0000000000..d75f6c9ab6 --- /dev/null +++ b/Lang/REXX/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/REXX \ No newline at end of file diff --git a/Lang/REXX/String-prepend b/Lang/REXX/String-prepend new file mode 120000 index 0000000000..c038b6f13f --- /dev/null +++ b/Lang/REXX/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/REXX \ No newline at end of file diff --git a/Lang/REXX/Sum-multiples-of-3-and-5 b/Lang/REXX/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..f8d802544d --- /dev/null +++ b/Lang/REXX/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/REXX \ No newline at end of file diff --git a/Lang/REXX/Textonyms b/Lang/REXX/Textonyms new file mode 120000 index 0000000000..214ba5cb5b --- /dev/null +++ b/Lang/REXX/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/REXX \ No newline at end of file diff --git a/Lang/REXX/The-ISAAC-Cipher b/Lang/REXX/The-ISAAC-Cipher new file mode 120000 index 0000000000..9de63def31 --- /dev/null +++ b/Lang/REXX/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/REXX \ No newline at end of file diff --git a/Lang/REXX/The-Twelve-Days-of-Christmas b/Lang/REXX/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..3397abd1b4 --- /dev/null +++ b/Lang/REXX/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/REXX \ No newline at end of file diff --git a/Lang/REXX/Total-circles-area b/Lang/REXX/Total-circles-area new file mode 120000 index 0000000000..f2ddc8fc3f --- /dev/null +++ b/Lang/REXX/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/REXX \ No newline at end of file diff --git a/Lang/REXX/Ulam-spiral--for-primes- b/Lang/REXX/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..28ed891dcb --- /dev/null +++ b/Lang/REXX/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/REXX \ No newline at end of file diff --git a/Lang/REXX/Unix-ls b/Lang/REXX/Unix-ls new file mode 120000 index 0000000000..d8a9bf89b3 --- /dev/null +++ b/Lang/REXX/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/REXX \ No newline at end of file diff --git a/Lang/REXX/Zero-to-the-zero-power b/Lang/REXX/Zero-to-the-zero-power new file mode 120000 index 0000000000..58425b3d3a --- /dev/null +++ b/Lang/REXX/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/REXX \ No newline at end of file diff --git a/Lang/REXX/Zhang-Suen-thinning-algorithm b/Lang/REXX/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..3844941c3a --- /dev/null +++ b/Lang/REXX/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/REXX \ No newline at end of file diff --git a/Lang/Racket/9-billion-names-of-God-the-integer b/Lang/Racket/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..e666698e50 --- /dev/null +++ b/Lang/Racket/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Racket \ No newline at end of file diff --git a/Lang/Racket/ABC-Problem b/Lang/Racket/ABC-Problem new file mode 120000 index 0000000000..9faff3dd18 --- /dev/null +++ b/Lang/Racket/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Racket \ No newline at end of file diff --git a/Lang/Racket/AKS-test-for-primes b/Lang/Racket/AKS-test-for-primes new file mode 120000 index 0000000000..67ef700981 --- /dev/null +++ b/Lang/Racket/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Racket \ No newline at end of file diff --git a/Lang/Racket/Abundant,-deficient-and-perfect-number-classifications b/Lang/Racket/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..52ce51640d --- /dev/null +++ b/Lang/Racket/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Racket \ No newline at end of file diff --git a/Lang/Racket/Aliquot-sequence-classifications b/Lang/Racket/Aliquot-sequence-classifications new file mode 120000 index 0000000000..5c9be191f6 --- /dev/null +++ b/Lang/Racket/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Racket \ No newline at end of file diff --git a/Lang/Racket/Almost-prime b/Lang/Racket/Almost-prime new file mode 120000 index 0000000000..92f4a03e5a --- /dev/null +++ b/Lang/Racket/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Racket \ No newline at end of file diff --git a/Lang/Racket/Amb b/Lang/Racket/Amb new file mode 120000 index 0000000000..53bad6c7d4 --- /dev/null +++ b/Lang/Racket/Amb @@ -0,0 +1 @@ +../../Task/Amb/Racket \ No newline at end of file diff --git a/Lang/Racket/Amicable-pairs b/Lang/Racket/Amicable-pairs new file mode 120000 index 0000000000..65666502c7 --- /dev/null +++ b/Lang/Racket/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Racket \ No newline at end of file diff --git a/Lang/Racket/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Racket/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..86eff23e2a --- /dev/null +++ b/Lang/Racket/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Racket \ No newline at end of file diff --git a/Lang/Racket/Benfords-law b/Lang/Racket/Benfords-law new file mode 120000 index 0000000000..0845953be5 --- /dev/null +++ b/Lang/Racket/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Racket \ No newline at end of file diff --git a/Lang/Racket/Bernoulli-numbers b/Lang/Racket/Bernoulli-numbers new file mode 120000 index 0000000000..cb5d046fef --- /dev/null +++ b/Lang/Racket/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitcoin-public-point-to-address b/Lang/Racket/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..17b9333302 --- /dev/null +++ b/Lang/Racket/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Racket \ No newline at end of file diff --git a/Lang/Racket/CSV-data-manipulation b/Lang/Racket/CSV-data-manipulation new file mode 120000 index 0000000000..c8bba1b310 --- /dev/null +++ b/Lang/Racket/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Racket \ No newline at end of file diff --git a/Lang/Racket/Calendar---for-REAL-programmers b/Lang/Racket/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..6f3763eda5 --- /dev/null +++ b/Lang/Racket/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Racket \ No newline at end of file diff --git a/Lang/Racket/Casting-out-nines b/Lang/Racket/Casting-out-nines new file mode 120000 index 0000000000..0c0b0e054a --- /dev/null +++ b/Lang/Racket/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Racket \ No newline at end of file diff --git a/Lang/Racket/Catalan-numbers-Pascals-triangle b/Lang/Racket/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..1fad781c9a --- /dev/null +++ b/Lang/Racket/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Racket \ No newline at end of file diff --git a/Lang/Racket/Catamorphism b/Lang/Racket/Catamorphism new file mode 120000 index 0000000000..1f0dd23907 --- /dev/null +++ b/Lang/Racket/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Racket \ No newline at end of file diff --git a/Lang/Racket/Chinese-remainder-theorem b/Lang/Racket/Chinese-remainder-theorem new file mode 120000 index 0000000000..8613105629 --- /dev/null +++ b/Lang/Racket/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Racket \ No newline at end of file diff --git a/Lang/Racket/Circles-of-given-radius-through-two-points b/Lang/Racket/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..aa7208c58e --- /dev/null +++ b/Lang/Racket/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Racket \ No newline at end of file diff --git a/Lang/Racket/Closures-Value-capture b/Lang/Racket/Closures-Value-capture new file mode 120000 index 0000000000..9a08756c4b --- /dev/null +++ b/Lang/Racket/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Racket \ No newline at end of file diff --git a/Lang/Racket/Combinations-and-permutations b/Lang/Racket/Combinations-and-permutations new file mode 120000 index 0000000000..93dc531d90 --- /dev/null +++ b/Lang/Racket/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Racket \ No newline at end of file diff --git a/Lang/Racket/Comma-quibbling b/Lang/Racket/Comma-quibbling new file mode 120000 index 0000000000..753d3149f0 --- /dev/null +++ b/Lang/Racket/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Racket \ No newline at end of file diff --git a/Lang/Racket/Conjugate-transpose b/Lang/Racket/Conjugate-transpose new file mode 120000 index 0000000000..047d6a64d1 --- /dev/null +++ b/Lang/Racket/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Racket \ No newline at end of file diff --git a/Lang/Racket/Convert-decimal-number-to-rational b/Lang/Racket/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..843f541965 --- /dev/null +++ b/Lang/Racket/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Racket \ No newline at end of file diff --git a/Lang/Racket/Currying b/Lang/Racket/Currying new file mode 120000 index 0000000000..2471b2df94 --- /dev/null +++ b/Lang/Racket/Currying @@ -0,0 +1 @@ +../../Task/Currying/Racket \ No newline at end of file diff --git a/Lang/Racket/Digital-root-Multiplicative-digital-root b/Lang/Racket/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..2231aa59b6 --- /dev/null +++ b/Lang/Racket/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Racket \ No newline at end of file diff --git a/Lang/Racket/Draw-a-clock b/Lang/Racket/Draw-a-clock new file mode 120000 index 0000000000..30abb5e5bc --- /dev/null +++ b/Lang/Racket/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Racket \ No newline at end of file diff --git a/Lang/Racket/Extensible-prime-generator b/Lang/Racket/Extensible-prime-generator new file mode 120000 index 0000000000..59633811e7 --- /dev/null +++ b/Lang/Racket/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Racket \ No newline at end of file diff --git a/Lang/Racket/Fibonacci-word b/Lang/Racket/Fibonacci-word new file mode 120000 index 0000000000..92deb0d1e0 --- /dev/null +++ b/Lang/Racket/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Racket \ No newline at end of file diff --git a/Lang/Racket/Fibonacci-word-fractal b/Lang/Racket/Fibonacci-word-fractal new file mode 120000 index 0000000000..9ebb6ff255 --- /dev/null +++ b/Lang/Racket/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Racket \ No newline at end of file diff --git a/Lang/Racket/File-input-output b/Lang/Racket/File-input-output new file mode 120000 index 0000000000..a26f3298a7 --- /dev/null +++ b/Lang/Racket/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Racket \ No newline at end of file diff --git a/Lang/Racket/Find-the-last-Sunday-of-each-month b/Lang/Racket/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..215a3ff8e1 --- /dev/null +++ b/Lang/Racket/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Racket \ No newline at end of file diff --git a/Lang/Racket/Flipping-bits-game b/Lang/Racket/Flipping-bits-game new file mode 120000 index 0000000000..31e5c2818d --- /dev/null +++ b/Lang/Racket/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Racket \ No newline at end of file diff --git a/Lang/Racket/Fractran b/Lang/Racket/Fractran new file mode 120000 index 0000000000..0623bb5a37 --- /dev/null +++ b/Lang/Racket/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Racket \ No newline at end of file diff --git a/Lang/Racket/Gaussian-elimination b/Lang/Racket/Gaussian-elimination new file mode 120000 index 0000000000..c2df9daecf --- /dev/null +++ b/Lang/Racket/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Racket \ No newline at end of file diff --git a/Lang/Racket/Generate-Chess960-starting-position b/Lang/Racket/Generate-Chess960-starting-position new file mode 120000 index 0000000000..dcda5b108b --- /dev/null +++ b/Lang/Racket/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Racket \ No newline at end of file diff --git a/Lang/Racket/Generate-lower-case-ASCII-alphabet b/Lang/Racket/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..8bb5b82a12 --- /dev/null +++ b/Lang/Racket/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Racket \ No newline at end of file diff --git a/Lang/Racket/Hash-join b/Lang/Racket/Hash-join new file mode 120000 index 0000000000..da5addb6ff --- /dev/null +++ b/Lang/Racket/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Racket \ No newline at end of file diff --git a/Lang/Racket/Heronian-triangles b/Lang/Racket/Heronian-triangles new file mode 120000 index 0000000000..84baf65171 --- /dev/null +++ b/Lang/Racket/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Racket \ No newline at end of file diff --git a/Lang/Racket/Hickerson-series-of-almost-integers b/Lang/Racket/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..1ce5de62b0 --- /dev/null +++ b/Lang/Racket/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Racket \ No newline at end of file diff --git a/Lang/Racket/IBAN b/Lang/Racket/IBAN new file mode 120000 index 0000000000..1627a1aa05 --- /dev/null +++ b/Lang/Racket/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Racket \ No newline at end of file diff --git a/Lang/Racket/Iterated-digits-squaring b/Lang/Racket/Iterated-digits-squaring new file mode 120000 index 0000000000..b40bcfd2f8 --- /dev/null +++ b/Lang/Racket/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Racket \ No newline at end of file diff --git a/Lang/Racket/K-d-tree b/Lang/Racket/K-d-tree new file mode 120000 index 0000000000..2f3ccdcfa7 --- /dev/null +++ b/Lang/Racket/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Racket \ No newline at end of file diff --git a/Lang/Racket/Left-factorials b/Lang/Racket/Left-factorials new file mode 120000 index 0000000000..8dcefcf1f1 --- /dev/null +++ b/Lang/Racket/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Racket \ No newline at end of file diff --git a/Lang/Racket/Longest-increasing-subsequence b/Lang/Racket/Longest-increasing-subsequence new file mode 120000 index 0000000000..8a591aad40 --- /dev/null +++ b/Lang/Racket/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Racket \ No newline at end of file diff --git a/Lang/Racket/Ludic-numbers b/Lang/Racket/Ludic-numbers new file mode 120000 index 0000000000..970f6f5d01 --- /dev/null +++ b/Lang/Racket/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Magic-squares-of-odd-order b/Lang/Racket/Magic-squares-of-odd-order new file mode 120000 index 0000000000..ee598452c7 --- /dev/null +++ b/Lang/Racket/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Racket \ No newline at end of file diff --git a/Lang/Racket/Make-directory-path b/Lang/Racket/Make-directory-path new file mode 120000 index 0000000000..6e4a58095f --- /dev/null +++ b/Lang/Racket/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Racket \ No newline at end of file diff --git a/Lang/Racket/Maximum-triangle-path-sum b/Lang/Racket/Maximum-triangle-path-sum new file mode 120000 index 0000000000..15f47fcf05 --- /dev/null +++ b/Lang/Racket/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Racket \ No newline at end of file diff --git a/Lang/Racket/Move-to-front-algorithm b/Lang/Racket/Move-to-front-algorithm new file mode 120000 index 0000000000..bddec8ef59 --- /dev/null +++ b/Lang/Racket/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Munching-squares b/Lang/Racket/Munching-squares new file mode 120000 index 0000000000..b2a43a98b1 --- /dev/null +++ b/Lang/Racket/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Racket \ No newline at end of file diff --git a/Lang/Racket/Narcissistic-decimal-number b/Lang/Racket/Narcissistic-decimal-number new file mode 120000 index 0000000000..e91b2d1d9e --- /dev/null +++ b/Lang/Racket/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Racket \ No newline at end of file diff --git a/Lang/Racket/Natural-sorting b/Lang/Racket/Natural-sorting new file mode 120000 index 0000000000..36cd01c6bc --- /dev/null +++ b/Lang/Racket/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Racket \ No newline at end of file diff --git a/Lang/Racket/Nth b/Lang/Racket/Nth new file mode 120000 index 0000000000..aaa81ab992 --- /dev/null +++ b/Lang/Racket/Nth @@ -0,0 +1 @@ +../../Task/Nth/Racket \ No newline at end of file diff --git a/Lang/Racket/Odd-word-problem b/Lang/Racket/Odd-word-problem new file mode 120000 index 0000000000..35b5a6d75b --- /dev/null +++ b/Lang/Racket/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Old-lady-swallowed-a-fly b/Lang/Racket/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..6be1826634 --- /dev/null +++ b/Lang/Racket/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Racket \ No newline at end of file diff --git a/Lang/Racket/Order-disjoint-list-items b/Lang/Racket/Order-disjoint-list-items new file mode 120000 index 0000000000..e13f75bcec --- /dev/null +++ b/Lang/Racket/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Racket \ No newline at end of file diff --git a/Lang/Racket/Paraffins b/Lang/Racket/Paraffins new file mode 120000 index 0000000000..3ed5965f50 --- /dev/null +++ b/Lang/Racket/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Racket \ No newline at end of file diff --git a/Lang/Racket/Parse-an-IP-Address b/Lang/Racket/Parse-an-IP-Address new file mode 120000 index 0000000000..94ff71b8e9 --- /dev/null +++ b/Lang/Racket/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Racket \ No newline at end of file diff --git a/Lang/Racket/Penneys-game b/Lang/Racket/Penneys-game new file mode 120000 index 0000000000..8c273969c7 --- /dev/null +++ b/Lang/Racket/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Racket \ No newline at end of file diff --git a/Lang/Racket/Percolation-Bond-percolation b/Lang/Racket/Percolation-Bond-percolation new file mode 120000 index 0000000000..608a0ff0cc --- /dev/null +++ b/Lang/Racket/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Racket \ No newline at end of file diff --git a/Lang/Racket/Percolation-Mean-cluster-density b/Lang/Racket/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..6feac8c5b3 --- /dev/null +++ b/Lang/Racket/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Racket \ No newline at end of file diff --git a/Lang/Racket/Percolation-Mean-run-density b/Lang/Racket/Percolation-Mean-run-density new file mode 120000 index 0000000000..5af3800df9 --- /dev/null +++ b/Lang/Racket/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Racket \ No newline at end of file diff --git a/Lang/Racket/Percolation-Site-percolation b/Lang/Racket/Percolation-Site-percolation new file mode 120000 index 0000000000..78dc927dcb --- /dev/null +++ b/Lang/Racket/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Racket \ No newline at end of file diff --git a/Lang/Racket/Permutations-Rank-of-a-permutation b/Lang/Racket/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..61362d11b9 --- /dev/null +++ b/Lang/Racket/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Racket \ No newline at end of file diff --git a/Lang/Racket/Pernicious-numbers b/Lang/Racket/Pernicious-numbers new file mode 120000 index 0000000000..414f1f0c6b --- /dev/null +++ b/Lang/Racket/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Phrase-reversals b/Lang/Racket/Phrase-reversals new file mode 120000 index 0000000000..247c1aa664 --- /dev/null +++ b/Lang/Racket/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Racket \ No newline at end of file diff --git a/Lang/Racket/Quickselect-algorithm b/Lang/Racket/Quickselect-algorithm new file mode 120000 index 0000000000..8727eca9fb --- /dev/null +++ b/Lang/Racket/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/RSA-code b/Lang/Racket/RSA-code new file mode 120000 index 0000000000..e7c21020f9 --- /dev/null +++ b/Lang/Racket/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Racket \ No newline at end of file diff --git a/Lang/Racket/Ranking-methods b/Lang/Racket/Ranking-methods new file mode 120000 index 0000000000..ccaede98ad --- /dev/null +++ b/Lang/Racket/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Racket \ No newline at end of file diff --git a/Lang/Racket/Rep-string b/Lang/Racket/Rep-string new file mode 120000 index 0000000000..5282bd7927 --- /dev/null +++ b/Lang/Racket/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Reverse-words-in-a-string b/Lang/Racket/Reverse-words-in-a-string new file mode 120000 index 0000000000..1c059fc10a --- /dev/null +++ b/Lang/Racket/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Runge-Kutta-method b/Lang/Racket/Runge-Kutta-method new file mode 120000 index 0000000000..5bb75d7f9e --- /dev/null +++ b/Lang/Racket/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Racket \ No newline at end of file diff --git a/Lang/Racket/Semiprime b/Lang/Racket/Semiprime new file mode 120000 index 0000000000..830adbf126 --- /dev/null +++ b/Lang/Racket/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Racket \ No newline at end of file diff --git a/Lang/Racket/Sequence-of-primes-by-Trial-Division b/Lang/Racket/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..b2d94526a6 --- /dev/null +++ b/Lang/Racket/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Racket \ No newline at end of file diff --git a/Lang/Racket/Solve-a-Holy-Knights-tour b/Lang/Racket/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..2fe2866ab8 --- /dev/null +++ b/Lang/Racket/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Racket \ No newline at end of file diff --git a/Lang/Racket/Solve-a-Hopido-puzzle b/Lang/Racket/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..ad9a0f927c --- /dev/null +++ b/Lang/Racket/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Solve-a-Numbrix-puzzle b/Lang/Racket/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..b79bf471a0 --- /dev/null +++ b/Lang/Racket/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Solve-the-no-connection-puzzle b/Lang/Racket/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d2946edc21 --- /dev/null +++ b/Lang/Racket/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Sparkline-in-unicode b/Lang/Racket/Sparkline-in-unicode new file mode 120000 index 0000000000..930c409823 --- /dev/null +++ b/Lang/Racket/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Racket \ No newline at end of file diff --git a/Lang/Racket/State-name-puzzle b/Lang/Racket/State-name-puzzle new file mode 120000 index 0000000000..0557af9560 --- /dev/null +++ b/Lang/Racket/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Statistics-Basic b/Lang/Racket/Statistics-Basic new file mode 120000 index 0000000000..22ddb52363 --- /dev/null +++ b/Lang/Racket/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Racket \ No newline at end of file diff --git a/Lang/Racket/Stern-Brocot-sequence b/Lang/Racket/Stern-Brocot-sequence new file mode 120000 index 0000000000..b6dfb67ba9 --- /dev/null +++ b/Lang/Racket/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Racket \ No newline at end of file diff --git a/Lang/Racket/String-append b/Lang/Racket/String-append new file mode 120000 index 0000000000..b315e12139 --- /dev/null +++ b/Lang/Racket/String-append @@ -0,0 +1 @@ +../../Task/String-append/Racket \ No newline at end of file diff --git a/Lang/Racket/String-matching b/Lang/Racket/String-matching new file mode 120000 index 0000000000..66d0dd618b --- /dev/null +++ b/Lang/Racket/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Racket \ No newline at end of file diff --git a/Lang/Racket/String-prepend b/Lang/Racket/String-prepend new file mode 120000 index 0000000000..1fde47569f --- /dev/null +++ b/Lang/Racket/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Racket \ No newline at end of file diff --git a/Lang/Racket/Sum-multiples-of-3-and-5 b/Lang/Racket/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..8bd432992e --- /dev/null +++ b/Lang/Racket/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Racket \ No newline at end of file diff --git a/Lang/Racket/The-ISAAC-Cipher b/Lang/Racket/The-ISAAC-Cipher new file mode 120000 index 0000000000..45900675ca --- /dev/null +++ b/Lang/Racket/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Racket \ No newline at end of file diff --git a/Lang/Racket/The-Twelve-Days-of-Christmas b/Lang/Racket/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..a2b0f3808f --- /dev/null +++ b/Lang/Racket/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Racket \ No newline at end of file diff --git a/Lang/Racket/Ulam-spiral--for-primes- b/Lang/Racket/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..73d5442bdd --- /dev/null +++ b/Lang/Racket/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Racket \ No newline at end of file diff --git a/Lang/Racket/Unix-ls b/Lang/Racket/Unix-ls new file mode 120000 index 0000000000..74b53a0df4 --- /dev/null +++ b/Lang/Racket/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Racket \ No newline at end of file diff --git a/Lang/Racket/Vogels-approximation-method b/Lang/Racket/Vogels-approximation-method new file mode 120000 index 0000000000..b814c2f78b --- /dev/null +++ b/Lang/Racket/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Racket \ No newline at end of file diff --git a/Lang/Racket/World-Cup-group-stage b/Lang/Racket/World-Cup-group-stage new file mode 120000 index 0000000000..79d2500605 --- /dev/null +++ b/Lang/Racket/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Racket \ No newline at end of file diff --git a/Lang/Racket/Zero-to-the-zero-power b/Lang/Racket/Zero-to-the-zero-power new file mode 120000 index 0000000000..09395e2d45 --- /dev/null +++ b/Lang/Racket/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Racket \ No newline at end of file diff --git a/Lang/Racket/Zhang-Suen-thinning-algorithm b/Lang/Racket/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..ca95158a60 --- /dev/null +++ b/Lang/Racket/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Racket \ No newline at end of file diff --git a/Lang/RapidQ/ABC-Problem b/Lang/RapidQ/ABC-Problem new file mode 120000 index 0000000000..ecaa7ec541 --- /dev/null +++ b/Lang/RapidQ/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Append-a-record-to-the-end-of-a-text-file b/Lang/RapidQ/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..fa4210c809 --- /dev/null +++ b/Lang/RapidQ/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/File-input-output b/Lang/RapidQ/File-input-output new file mode 120000 index 0000000000..9cfeba5793 --- /dev/null +++ b/Lang/RapidQ/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/RapidQ \ No newline at end of file diff --git a/Lang/Raven/File-input-output b/Lang/Raven/File-input-output new file mode 120000 index 0000000000..8dc9d9863f --- /dev/null +++ b/Lang/Raven/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Raven \ No newline at end of file diff --git a/Lang/Retro/File-input-output b/Lang/Retro/File-input-output new file mode 120000 index 0000000000..3cf3bc3ecf --- /dev/null +++ b/Lang/Retro/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Retro \ No newline at end of file diff --git a/Lang/Retro/String-matching b/Lang/Retro/String-matching new file mode 120000 index 0000000000..cdba728951 --- /dev/null +++ b/Lang/Retro/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Retro \ No newline at end of file diff --git a/Lang/Ruby/9-billion-names-of-God-the-integer b/Lang/Ruby/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..ca7a307dc6 --- /dev/null +++ b/Lang/Ruby/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Ruby \ No newline at end of file diff --git a/Lang/Ruby/ABC-Problem b/Lang/Ruby/ABC-Problem new file mode 120000 index 0000000000..0217b1c304 --- /dev/null +++ b/Lang/Ruby/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Ruby \ No newline at end of file diff --git a/Lang/Ruby/AKS-test-for-primes b/Lang/Ruby/AKS-test-for-primes new file mode 120000 index 0000000000..6d55898060 --- /dev/null +++ b/Lang/Ruby/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Abundant,-deficient-and-perfect-number-classifications b/Lang/Ruby/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..9316c73f90 --- /dev/null +++ b/Lang/Ruby/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Aliquot-sequence-classifications b/Lang/Ruby/Aliquot-sequence-classifications new file mode 120000 index 0000000000..92175be2fb --- /dev/null +++ b/Lang/Ruby/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Almost-prime b/Lang/Ruby/Almost-prime new file mode 120000 index 0000000000..2aa9c48356 --- /dev/null +++ b/Lang/Ruby/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Amb b/Lang/Ruby/Amb new file mode 120000 index 0000000000..83bf4777b0 --- /dev/null +++ b/Lang/Ruby/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Amicable-pairs b/Lang/Ruby/Amicable-pairs new file mode 120000 index 0000000000..cf6b6ec244 --- /dev/null +++ b/Lang/Ruby/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Append-a-record-to-the-end-of-a-text-file b/Lang/Ruby/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..34eccd35bb --- /dev/null +++ b/Lang/Ruby/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Ruby/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..21bcdc9789 --- /dev/null +++ b/Lang/Ruby/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Benfords-law b/Lang/Ruby/Benfords-law new file mode 120000 index 0000000000..9720747b5d --- /dev/null +++ b/Lang/Ruby/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Bernoulli-numbers b/Lang/Ruby/Bernoulli-numbers new file mode 120000 index 0000000000..a0989fb0cc --- /dev/null +++ b/Lang/Ruby/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Bitcoin-public-point-to-address b/Lang/Ruby/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..72aa4ec62f --- /dev/null +++ b/Lang/Ruby/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Ruby \ No newline at end of file diff --git a/Lang/Ruby/CSV-data-manipulation b/Lang/Ruby/CSV-data-manipulation new file mode 120000 index 0000000000..04d49ca994 --- /dev/null +++ b/Lang/Ruby/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Calendar---for-REAL-programmers b/Lang/Ruby/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..ad90632b2f --- /dev/null +++ b/Lang/Ruby/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Catalan-numbers-Pascals-triangle b/Lang/Ruby/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..0b9adaa70e --- /dev/null +++ b/Lang/Ruby/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Catamorphism b/Lang/Ruby/Catamorphism new file mode 120000 index 0000000000..26c23f1462 --- /dev/null +++ b/Lang/Ruby/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Chinese-remainder-theorem b/Lang/Ruby/Chinese-remainder-theorem new file mode 120000 index 0000000000..df3076e2cf --- /dev/null +++ b/Lang/Ruby/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Circles-of-given-radius-through-two-points b/Lang/Ruby/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..48b4293336 --- /dev/null +++ b/Lang/Ruby/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Closures-Value-capture b/Lang/Ruby/Closures-Value-capture new file mode 120000 index 0000000000..15c9e9fe41 --- /dev/null +++ b/Lang/Ruby/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Combinations-and-permutations b/Lang/Ruby/Combinations-and-permutations new file mode 120000 index 0000000000..1ea5cfa0d2 --- /dev/null +++ b/Lang/Ruby/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Comma-quibbling b/Lang/Ruby/Comma-quibbling new file mode 120000 index 0000000000..62458ba04f --- /dev/null +++ b/Lang/Ruby/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Conjugate-transpose b/Lang/Ruby/Conjugate-transpose new file mode 120000 index 0000000000..2802331eec --- /dev/null +++ b/Lang/Ruby/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Convert-decimal-number-to-rational b/Lang/Ruby/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..dc6dc5b76c --- /dev/null +++ b/Lang/Ruby/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Currying b/Lang/Ruby/Currying new file mode 120000 index 0000000000..86bf783ee1 --- /dev/null +++ b/Lang/Ruby/Currying @@ -0,0 +1 @@ +../../Task/Currying/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Digital-root-Multiplicative-digital-root b/Lang/Ruby/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..7b57191e24 --- /dev/null +++ b/Lang/Ruby/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Draw-a-clock b/Lang/Ruby/Draw-a-clock new file mode 120000 index 0000000000..c8422c028f --- /dev/null +++ b/Lang/Ruby/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Extensible-prime-generator b/Lang/Ruby/Extensible-prime-generator new file mode 120000 index 0000000000..db9062fc8a --- /dev/null +++ b/Lang/Ruby/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Fibonacci-word b/Lang/Ruby/Fibonacci-word new file mode 120000 index 0000000000..ae2e484994 --- /dev/null +++ b/Lang/Ruby/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Fibonacci-word-fractal b/Lang/Ruby/Fibonacci-word-fractal new file mode 120000 index 0000000000..7013b8fd5e --- /dev/null +++ b/Lang/Ruby/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Ruby \ No newline at end of file diff --git a/Lang/Ruby/File-input-output b/Lang/Ruby/File-input-output new file mode 120000 index 0000000000..4f09b7ce1c --- /dev/null +++ b/Lang/Ruby/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Find-the-last-Sunday-of-each-month b/Lang/Ruby/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..d92935f3f2 --- /dev/null +++ b/Lang/Ruby/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Flipping-bits-game b/Lang/Ruby/Flipping-bits-game new file mode 120000 index 0000000000..b148400a05 --- /dev/null +++ b/Lang/Ruby/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Fractran b/Lang/Ruby/Fractran new file mode 120000 index 0000000000..ab43e33c21 --- /dev/null +++ b/Lang/Ruby/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Gaussian-elimination b/Lang/Ruby/Gaussian-elimination new file mode 120000 index 0000000000..3aadfc6896 --- /dev/null +++ b/Lang/Ruby/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Generate-Chess960-starting-position b/Lang/Ruby/Generate-Chess960-starting-position new file mode 120000 index 0000000000..e4fe9df62d --- /dev/null +++ b/Lang/Ruby/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Generate-lower-case-ASCII-alphabet b/Lang/Ruby/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..992d3a5c30 --- /dev/null +++ b/Lang/Ruby/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Hash-join b/Lang/Ruby/Hash-join new file mode 120000 index 0000000000..fe2f2889c8 --- /dev/null +++ b/Lang/Ruby/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Heronian-triangles b/Lang/Ruby/Heronian-triangles new file mode 120000 index 0000000000..cf38ce98a2 --- /dev/null +++ b/Lang/Ruby/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Hickerson-series-of-almost-integers b/Lang/Ruby/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..fc706a038c --- /dev/null +++ b/Lang/Ruby/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/IBAN b/Lang/Ruby/IBAN new file mode 120000 index 0000000000..d5b4d3337f --- /dev/null +++ b/Lang/Ruby/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Integer-overflow b/Lang/Ruby/Integer-overflow new file mode 120000 index 0000000000..d4c164e4fa --- /dev/null +++ b/Lang/Ruby/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Iterated-digits-squaring b/Lang/Ruby/Iterated-digits-squaring new file mode 120000 index 0000000000..d6724a7174 --- /dev/null +++ b/Lang/Ruby/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Left-factorials b/Lang/Ruby/Left-factorials new file mode 120000 index 0000000000..d3381e8a5c --- /dev/null +++ b/Lang/Ruby/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Longest-increasing-subsequence b/Lang/Ruby/Longest-increasing-subsequence new file mode 120000 index 0000000000..02a4b3f7e0 --- /dev/null +++ b/Lang/Ruby/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Ludic-numbers b/Lang/Ruby/Ludic-numbers new file mode 120000 index 0000000000..89feba939a --- /dev/null +++ b/Lang/Ruby/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Magic-squares-of-odd-order b/Lang/Ruby/Magic-squares-of-odd-order new file mode 120000 index 0000000000..8901a86701 --- /dev/null +++ b/Lang/Ruby/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Make-directory-path b/Lang/Ruby/Make-directory-path new file mode 120000 index 0000000000..5da8e2a2af --- /dev/null +++ b/Lang/Ruby/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Maximum-triangle-path-sum b/Lang/Ruby/Maximum-triangle-path-sum new file mode 120000 index 0000000000..a3dca90005 --- /dev/null +++ b/Lang/Ruby/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Move-to-front-algorithm b/Lang/Ruby/Move-to-front-algorithm new file mode 120000 index 0000000000..df056397bd --- /dev/null +++ b/Lang/Ruby/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Munching-squares b/Lang/Ruby/Munching-squares new file mode 120000 index 0000000000..61e3a46e5d --- /dev/null +++ b/Lang/Ruby/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Narcissistic-decimal-number b/Lang/Ruby/Narcissistic-decimal-number new file mode 120000 index 0000000000..3809385138 --- /dev/null +++ b/Lang/Ruby/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Natural-sorting b/Lang/Ruby/Natural-sorting new file mode 120000 index 0000000000..f05dab1851 --- /dev/null +++ b/Lang/Ruby/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Nth b/Lang/Ruby/Nth new file mode 120000 index 0000000000..b569e125d6 --- /dev/null +++ b/Lang/Ruby/Nth @@ -0,0 +1 @@ +../../Task/Nth/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Odd-word-problem b/Lang/Ruby/Odd-word-problem new file mode 120000 index 0000000000..b69c31506a --- /dev/null +++ b/Lang/Ruby/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Old-lady-swallowed-a-fly b/Lang/Ruby/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..58aedf7530 --- /dev/null +++ b/Lang/Ruby/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Order-disjoint-list-items b/Lang/Ruby/Order-disjoint-list-items new file mode 120000 index 0000000000..4c5e32aa09 --- /dev/null +++ b/Lang/Ruby/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Paraffins b/Lang/Ruby/Paraffins new file mode 120000 index 0000000000..ad6ac5052b --- /dev/null +++ b/Lang/Ruby/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Parse-an-IP-Address b/Lang/Ruby/Parse-an-IP-Address new file mode 120000 index 0000000000..1f128cada9 --- /dev/null +++ b/Lang/Ruby/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Penneys-game b/Lang/Ruby/Penneys-game new file mode 120000 index 0000000000..a2dff9fd55 --- /dev/null +++ b/Lang/Ruby/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Permutations-Rank-of-a-permutation b/Lang/Ruby/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..9cc348f4ca --- /dev/null +++ b/Lang/Ruby/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Pernicious-numbers b/Lang/Ruby/Pernicious-numbers new file mode 120000 index 0000000000..d732dbcff4 --- /dev/null +++ b/Lang/Ruby/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Phrase-reversals b/Lang/Ruby/Phrase-reversals new file mode 120000 index 0000000000..b56457e6a9 --- /dev/null +++ b/Lang/Ruby/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Quickselect-algorithm b/Lang/Ruby/Quickselect-algorithm new file mode 120000 index 0000000000..e28d46193a --- /dev/null +++ b/Lang/Ruby/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Ranking-methods b/Lang/Ruby/Ranking-methods new file mode 120000 index 0000000000..2469d80559 --- /dev/null +++ b/Lang/Ruby/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rep-string b/Lang/Ruby/Rep-string new file mode 120000 index 0000000000..9ca5c86851 --- /dev/null +++ b/Lang/Ruby/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Reverse-words-in-a-string b/Lang/Ruby/Reverse-words-in-a-string new file mode 120000 index 0000000000..632b9a045f --- /dev/null +++ b/Lang/Ruby/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Runge-Kutta-method b/Lang/Ruby/Runge-Kutta-method new file mode 120000 index 0000000000..9ce7cfc861 --- /dev/null +++ b/Lang/Ruby/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Semiprime b/Lang/Ruby/Semiprime new file mode 120000 index 0000000000..86755fdf11 --- /dev/null +++ b/Lang/Ruby/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sequence-of-primes-by-Trial-Division b/Lang/Ruby/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..ae0ea1583c --- /dev/null +++ b/Lang/Ruby/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Solve-a-Holy-Knights-tour b/Lang/Ruby/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..c57e191b3e --- /dev/null +++ b/Lang/Ruby/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Solve-a-Hopido-puzzle b/Lang/Ruby/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..6d481e254b --- /dev/null +++ b/Lang/Ruby/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Solve-a-Numbrix-puzzle b/Lang/Ruby/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..e4184e9dbf --- /dev/null +++ b/Lang/Ruby/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Solve-the-no-connection-puzzle b/Lang/Ruby/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d1509b30b0 --- /dev/null +++ b/Lang/Ruby/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sparkline-in-unicode b/Lang/Ruby/Sparkline-in-unicode new file mode 120000 index 0000000000..35d38bac30 --- /dev/null +++ b/Lang/Ruby/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Ruby \ No newline at end of file diff --git a/Lang/Ruby/State-name-puzzle b/Lang/Ruby/State-name-puzzle new file mode 120000 index 0000000000..fcac846e14 --- /dev/null +++ b/Lang/Ruby/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Statistics-Basic b/Lang/Ruby/Statistics-Basic new file mode 120000 index 0000000000..d5a9733d0c --- /dev/null +++ b/Lang/Ruby/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stern-Brocot-sequence b/Lang/Ruby/Stern-Brocot-sequence new file mode 120000 index 0000000000..2f2146ba59 --- /dev/null +++ b/Lang/Ruby/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-append b/Lang/Ruby/String-append new file mode 120000 index 0000000000..78d60eb7e6 --- /dev/null +++ b/Lang/Ruby/String-append @@ -0,0 +1 @@ +../../Task/String-append/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-matching b/Lang/Ruby/String-matching new file mode 120000 index 0000000000..81e71fb7ec --- /dev/null +++ b/Lang/Ruby/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-prepend b/Lang/Ruby/String-prepend new file mode 120000 index 0000000000..85206a6eb5 --- /dev/null +++ b/Lang/Ruby/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sum-multiples-of-3-and-5 b/Lang/Ruby/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..442f40f983 --- /dev/null +++ b/Lang/Ruby/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Textonyms b/Lang/Ruby/Textonyms new file mode 120000 index 0000000000..0a2e371a39 --- /dev/null +++ b/Lang/Ruby/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Ruby \ No newline at end of file diff --git a/Lang/Ruby/The-Twelve-Days-of-Christmas b/Lang/Ruby/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..8f4f171493 --- /dev/null +++ b/Lang/Ruby/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Total-circles-area b/Lang/Ruby/Total-circles-area new file mode 120000 index 0000000000..6b4bee10e7 --- /dev/null +++ b/Lang/Ruby/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Unix-ls b/Lang/Ruby/Unix-ls new file mode 120000 index 0000000000..d14bb4ef49 --- /dev/null +++ b/Lang/Ruby/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Vogels-approximation-method b/Lang/Ruby/Vogels-approximation-method new file mode 120000 index 0000000000..c17c7b0ca5 --- /dev/null +++ b/Lang/Ruby/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Ruby \ No newline at end of file diff --git a/Lang/Ruby/World-Cup-group-stage b/Lang/Ruby/World-Cup-group-stage new file mode 120000 index 0000000000..8d9b9f6ea3 --- /dev/null +++ b/Lang/Ruby/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Zero-to-the-zero-power b/Lang/Ruby/Zero-to-the-zero-power new file mode 120000 index 0000000000..b5baaf1e76 --- /dev/null +++ b/Lang/Ruby/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Zhang-Suen-thinning-algorithm b/Lang/Ruby/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..bb92ed72a1 --- /dev/null +++ b/Lang/Ruby/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Benfords-law b/Lang/Run-BASIC/Benfords-law new file mode 120000 index 0000000000..6b2894d9f3 --- /dev/null +++ b/Lang/Run-BASIC/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/CSV-data-manipulation b/Lang/Run-BASIC/CSV-data-manipulation new file mode 120000 index 0000000000..50faa036aa --- /dev/null +++ b/Lang/Run-BASIC/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Catalan-numbers-Pascals-triangle b/Lang/Run-BASIC/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..d5059496b7 --- /dev/null +++ b/Lang/Run-BASIC/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Catamorphism b/Lang/Run-BASIC/Catamorphism new file mode 120000 index 0000000000..2f1af93c4a --- /dev/null +++ b/Lang/Run-BASIC/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Comma-quibbling b/Lang/Run-BASIC/Comma-quibbling new file mode 120000 index 0000000000..26058a6856 --- /dev/null +++ b/Lang/Run-BASIC/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Draw-a-clock b/Lang/Run-BASIC/Draw-a-clock new file mode 120000 index 0000000000..c4b581f997 --- /dev/null +++ b/Lang/Run-BASIC/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/File-input-output b/Lang/Run-BASIC/File-input-output new file mode 120000 index 0000000000..8dd0e247aa --- /dev/null +++ b/Lang/Run-BASIC/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Munching-squares b/Lang/Run-BASIC/Munching-squares new file mode 120000 index 0000000000..4d66a550f0 --- /dev/null +++ b/Lang/Run-BASIC/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Odd-word-problem b/Lang/Run-BASIC/Odd-word-problem new file mode 120000 index 0000000000..9b49db6767 --- /dev/null +++ b/Lang/Run-BASIC/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Runge-Kutta-method b/Lang/Run-BASIC/Runge-Kutta-method new file mode 120000 index 0000000000..54f2a2134e --- /dev/null +++ b/Lang/Run-BASIC/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-matching b/Lang/Run-BASIC/String-matching new file mode 120000 index 0000000000..2eb8b3e9d9 --- /dev/null +++ b/Lang/Run-BASIC/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-multiples-of-3-and-5 b/Lang/Run-BASIC/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..a7f8e16a1b --- /dev/null +++ b/Lang/Run-BASIC/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/ABC-Problem b/Lang/Rust/ABC-Problem new file mode 120000 index 0000000000..eb1b7aba8c --- /dev/null +++ b/Lang/Rust/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Rust \ No newline at end of file diff --git a/Lang/Rust/AKS-test-for-primes b/Lang/Rust/AKS-test-for-primes new file mode 120000 index 0000000000..2448d99a58 --- /dev/null +++ b/Lang/Rust/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Rust \ No newline at end of file diff --git a/Lang/Rust/Almost-prime b/Lang/Rust/Almost-prime new file mode 120000 index 0000000000..9b5595bff7 --- /dev/null +++ b/Lang/Rust/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Rust \ No newline at end of file diff --git a/Lang/Rust/Circles-of-given-radius-through-two-points b/Lang/Rust/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..fad7aab792 --- /dev/null +++ b/Lang/Rust/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Rust \ No newline at end of file diff --git a/Lang/Rust/Closures-Value-capture b/Lang/Rust/Closures-Value-capture new file mode 120000 index 0000000000..5acfbb1c8b --- /dev/null +++ b/Lang/Rust/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Rust \ No newline at end of file diff --git a/Lang/Rust/Comma-quibbling b/Lang/Rust/Comma-quibbling new file mode 120000 index 0000000000..d637d95961 --- /dev/null +++ b/Lang/Rust/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Rust \ No newline at end of file diff --git a/Lang/Rust/Currying b/Lang/Rust/Currying new file mode 120000 index 0000000000..ef729ba17d --- /dev/null +++ b/Lang/Rust/Currying @@ -0,0 +1 @@ +../../Task/Currying/Rust \ No newline at end of file diff --git a/Lang/Rust/File-input-output b/Lang/Rust/File-input-output new file mode 120000 index 0000000000..30a39c1078 --- /dev/null +++ b/Lang/Rust/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Rust \ No newline at end of file diff --git a/Lang/Rust/Hello-world-Newbie b/Lang/Rust/Hello-world-Newbie new file mode 120000 index 0000000000..bac467c970 --- /dev/null +++ b/Lang/Rust/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Rust \ No newline at end of file diff --git a/Lang/Rust/Magic-squares-of-odd-order b/Lang/Rust/Magic-squares-of-odd-order new file mode 120000 index 0000000000..512ff0d924 --- /dev/null +++ b/Lang/Rust/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Rust \ No newline at end of file diff --git a/Lang/Rust/Nth b/Lang/Rust/Nth new file mode 120000 index 0000000000..4f55a7b8cc --- /dev/null +++ b/Lang/Rust/Nth @@ -0,0 +1 @@ +../../Task/Nth/Rust \ No newline at end of file diff --git a/Lang/Rust/The-Twelve-Days-of-Christmas b/Lang/Rust/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..f3a205e5b9 --- /dev/null +++ b/Lang/Rust/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Rust \ No newline at end of file diff --git a/Lang/Rust/Unix-ls b/Lang/Rust/Unix-ls new file mode 120000 index 0000000000..021fcdaa37 --- /dev/null +++ b/Lang/Rust/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Rust \ No newline at end of file diff --git a/Lang/Rust/Zero-to-the-zero-power b/Lang/Rust/Zero-to-the-zero-power new file mode 120000 index 0000000000..d7fae5a183 --- /dev/null +++ b/Lang/Rust/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Rust \ No newline at end of file diff --git a/Lang/SETL/Amb b/Lang/SETL/Amb new file mode 120000 index 0000000000..f7ce3848c0 --- /dev/null +++ b/Lang/SETL/Amb @@ -0,0 +1 @@ +../../Task/Amb/SETL \ No newline at end of file diff --git a/Lang/SNOBOL4/File-input-output b/Lang/SNOBOL4/File-input-output new file mode 120000 index 0000000000..ce1966050a --- /dev/null +++ b/Lang/SNOBOL4/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/SNOBOL4 \ No newline at end of file diff --git a/Lang/SQL/Benfords-law b/Lang/SQL/Benfords-law new file mode 120000 index 0000000000..24400424af --- /dev/null +++ b/Lang/SQL/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/SQL \ No newline at end of file diff --git a/Lang/SQL/Hash-join b/Lang/SQL/Hash-join new file mode 120000 index 0000000000..252a8ff0f4 --- /dev/null +++ b/Lang/SQL/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/SQL \ No newline at end of file diff --git a/Lang/Scala/9-billion-names-of-God-the-integer b/Lang/Scala/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..16766ecc8a --- /dev/null +++ b/Lang/Scala/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Scala \ No newline at end of file diff --git a/Lang/Scala/ABC-Problem b/Lang/Scala/ABC-Problem new file mode 120000 index 0000000000..6370e9a32f --- /dev/null +++ b/Lang/Scala/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Scala \ No newline at end of file diff --git a/Lang/Scala/AKS-test-for-primes b/Lang/Scala/AKS-test-for-primes new file mode 120000 index 0000000000..7a743c01a6 --- /dev/null +++ b/Lang/Scala/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Scala \ No newline at end of file diff --git a/Lang/Scala/Abundant,-deficient-and-perfect-number-classifications b/Lang/Scala/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..4927d70276 --- /dev/null +++ b/Lang/Scala/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Scala \ No newline at end of file diff --git a/Lang/Scala/Aliquot-sequence-classifications b/Lang/Scala/Aliquot-sequence-classifications new file mode 120000 index 0000000000..e22e479a55 --- /dev/null +++ b/Lang/Scala/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Scala \ No newline at end of file diff --git a/Lang/Scala/Almost-prime b/Lang/Scala/Almost-prime new file mode 120000 index 0000000000..1b1639f534 --- /dev/null +++ b/Lang/Scala/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Scala \ No newline at end of file diff --git a/Lang/Scala/Amb b/Lang/Scala/Amb new file mode 120000 index 0000000000..2ea2b2ffcd --- /dev/null +++ b/Lang/Scala/Amb @@ -0,0 +1 @@ +../../Task/Amb/Scala \ No newline at end of file diff --git a/Lang/Scala/Amicable-pairs b/Lang/Scala/Amicable-pairs new file mode 120000 index 0000000000..b379da8dc2 --- /dev/null +++ b/Lang/Scala/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Scala \ No newline at end of file diff --git a/Lang/Scala/Append-a-record-to-the-end-of-a-text-file b/Lang/Scala/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..28bd743a39 --- /dev/null +++ b/Lang/Scala/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Benfords-law b/Lang/Scala/Benfords-law new file mode 120000 index 0000000000..451f9301ed --- /dev/null +++ b/Lang/Scala/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Scala \ No newline at end of file diff --git a/Lang/Scala/CSV-data-manipulation b/Lang/Scala/CSV-data-manipulation new file mode 120000 index 0000000000..0cbb2b4704 --- /dev/null +++ b/Lang/Scala/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Scala \ No newline at end of file diff --git a/Lang/Scala/Closures-Value-capture b/Lang/Scala/Closures-Value-capture new file mode 120000 index 0000000000..7a70c33803 --- /dev/null +++ b/Lang/Scala/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Scala \ No newline at end of file diff --git a/Lang/Scala/Comma-quibbling b/Lang/Scala/Comma-quibbling new file mode 120000 index 0000000000..c63dc4f131 --- /dev/null +++ b/Lang/Scala/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Scala \ No newline at end of file diff --git a/Lang/Scala/Digital-root-Multiplicative-digital-root b/Lang/Scala/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..ab4001f2d4 --- /dev/null +++ b/Lang/Scala/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Scala \ No newline at end of file diff --git a/Lang/Scala/Draw-a-clock b/Lang/Scala/Draw-a-clock new file mode 120000 index 0000000000..45c2707ec0 --- /dev/null +++ b/Lang/Scala/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Scala \ No newline at end of file diff --git a/Lang/Scala/Fibonacci-word b/Lang/Scala/Fibonacci-word new file mode 120000 index 0000000000..0f2fb06ca0 --- /dev/null +++ b/Lang/Scala/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Scala \ No newline at end of file diff --git a/Lang/Scala/Fibonacci-word-fractal b/Lang/Scala/Fibonacci-word-fractal new file mode 120000 index 0000000000..604dd2e3d0 --- /dev/null +++ b/Lang/Scala/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Scala \ No newline at end of file diff --git a/Lang/Scala/File-input-output b/Lang/Scala/File-input-output new file mode 120000 index 0000000000..753f509f81 --- /dev/null +++ b/Lang/Scala/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Scala \ No newline at end of file diff --git a/Lang/Scala/Find-the-last-Sunday-of-each-month b/Lang/Scala/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..405c2aa3b0 --- /dev/null +++ b/Lang/Scala/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Scala \ No newline at end of file diff --git a/Lang/Scala/Generate-lower-case-ASCII-alphabet b/Lang/Scala/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..14b3518c91 --- /dev/null +++ b/Lang/Scala/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Scala \ No newline at end of file diff --git a/Lang/Scala/Hash-join b/Lang/Scala/Hash-join new file mode 120000 index 0000000000..c6e54349a7 --- /dev/null +++ b/Lang/Scala/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Scala \ No newline at end of file diff --git a/Lang/Scala/Hello-world-Newbie b/Lang/Scala/Hello-world-Newbie new file mode 120000 index 0000000000..8c851b4cb4 --- /dev/null +++ b/Lang/Scala/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Scala \ No newline at end of file diff --git a/Lang/Scala/IBAN b/Lang/Scala/IBAN new file mode 120000 index 0000000000..d2ced19728 --- /dev/null +++ b/Lang/Scala/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Scala \ No newline at end of file diff --git a/Lang/Scala/Integer-overflow b/Lang/Scala/Integer-overflow new file mode 120000 index 0000000000..6bb550a169 --- /dev/null +++ b/Lang/Scala/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Scala \ No newline at end of file diff --git a/Lang/Scala/K-d-tree b/Lang/Scala/K-d-tree new file mode 120000 index 0000000000..91d4c47905 --- /dev/null +++ b/Lang/Scala/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Scala \ No newline at end of file diff --git a/Lang/Scala/Longest-increasing-subsequence b/Lang/Scala/Longest-increasing-subsequence new file mode 120000 index 0000000000..e87f8947f5 --- /dev/null +++ b/Lang/Scala/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Scala \ No newline at end of file diff --git a/Lang/Scala/Make-directory-path b/Lang/Scala/Make-directory-path new file mode 120000 index 0000000000..1480649c04 --- /dev/null +++ b/Lang/Scala/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Scala \ No newline at end of file diff --git a/Lang/Scala/Maximum-triangle-path-sum b/Lang/Scala/Maximum-triangle-path-sum new file mode 120000 index 0000000000..e361e6be43 --- /dev/null +++ b/Lang/Scala/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Scala \ No newline at end of file diff --git a/Lang/Scala/Munching-squares b/Lang/Scala/Munching-squares new file mode 120000 index 0000000000..16bcdb12ba --- /dev/null +++ b/Lang/Scala/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Scala \ No newline at end of file diff --git a/Lang/Scala/Narcissistic-decimal-number b/Lang/Scala/Narcissistic-decimal-number new file mode 120000 index 0000000000..ede813fd40 --- /dev/null +++ b/Lang/Scala/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Scala \ No newline at end of file diff --git a/Lang/Scala/Natural-sorting b/Lang/Scala/Natural-sorting new file mode 120000 index 0000000000..2534007909 --- /dev/null +++ b/Lang/Scala/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Scala \ No newline at end of file diff --git a/Lang/Scala/Nth b/Lang/Scala/Nth new file mode 120000 index 0000000000..09353864b4 --- /dev/null +++ b/Lang/Scala/Nth @@ -0,0 +1 @@ +../../Task/Nth/Scala \ No newline at end of file diff --git a/Lang/Scala/Odd-word-problem b/Lang/Scala/Odd-word-problem new file mode 120000 index 0000000000..38091002af --- /dev/null +++ b/Lang/Scala/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Scala \ No newline at end of file diff --git a/Lang/Scala/Old-lady-swallowed-a-fly b/Lang/Scala/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..9213f31ea0 --- /dev/null +++ b/Lang/Scala/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Scala \ No newline at end of file diff --git a/Lang/Scala/Order-disjoint-list-items b/Lang/Scala/Order-disjoint-list-items new file mode 120000 index 0000000000..045fe59dbf --- /dev/null +++ b/Lang/Scala/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Scala \ No newline at end of file diff --git a/Lang/Scala/Pernicious-numbers b/Lang/Scala/Pernicious-numbers new file mode 120000 index 0000000000..2a690811ac --- /dev/null +++ b/Lang/Scala/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Scala \ No newline at end of file diff --git a/Lang/Scala/Quickselect-algorithm b/Lang/Scala/Quickselect-algorithm new file mode 120000 index 0000000000..31a6e23062 --- /dev/null +++ b/Lang/Scala/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/Ranking-methods b/Lang/Scala/Ranking-methods new file mode 120000 index 0000000000..5223c7d187 --- /dev/null +++ b/Lang/Scala/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Scala \ No newline at end of file diff --git a/Lang/Scala/Rep-string b/Lang/Scala/Rep-string new file mode 120000 index 0000000000..77c27fb32a --- /dev/null +++ b/Lang/Scala/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Reverse-words-in-a-string b/Lang/Scala/Reverse-words-in-a-string new file mode 120000 index 0000000000..34ae7be490 --- /dev/null +++ b/Lang/Scala/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Semiprime b/Lang/Scala/Semiprime new file mode 120000 index 0000000000..37c6ad2913 --- /dev/null +++ b/Lang/Scala/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Scala \ No newline at end of file diff --git a/Lang/Scala/Sequence-of-primes-by-Trial-Division b/Lang/Scala/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..0b6be33779 --- /dev/null +++ b/Lang/Scala/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Scala \ No newline at end of file diff --git a/Lang/Scala/Sparkline-in-unicode b/Lang/Scala/Sparkline-in-unicode new file mode 120000 index 0000000000..af97332665 --- /dev/null +++ b/Lang/Scala/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Scala \ No newline at end of file diff --git a/Lang/Scala/State-name-puzzle b/Lang/Scala/State-name-puzzle new file mode 120000 index 0000000000..c5cdb112cb --- /dev/null +++ b/Lang/Scala/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Scala \ No newline at end of file diff --git a/Lang/Scala/Statistics-Basic b/Lang/Scala/Statistics-Basic new file mode 120000 index 0000000000..349226ee27 --- /dev/null +++ b/Lang/Scala/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Scala \ No newline at end of file diff --git a/Lang/Scala/String-append b/Lang/Scala/String-append new file mode 120000 index 0000000000..235c96f40f --- /dev/null +++ b/Lang/Scala/String-append @@ -0,0 +1 @@ +../../Task/String-append/Scala \ No newline at end of file diff --git a/Lang/Scala/String-matching b/Lang/Scala/String-matching new file mode 120000 index 0000000000..854699fdde --- /dev/null +++ b/Lang/Scala/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Scala \ No newline at end of file diff --git a/Lang/Scala/String-prepend b/Lang/Scala/String-prepend new file mode 120000 index 0000000000..6fc4f5c241 --- /dev/null +++ b/Lang/Scala/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Scala \ No newline at end of file diff --git a/Lang/Scala/Sum-multiples-of-3-and-5 b/Lang/Scala/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..86de32501c --- /dev/null +++ b/Lang/Scala/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Scala \ No newline at end of file diff --git a/Lang/Scala/Zero-to-the-zero-power b/Lang/Scala/Zero-to-the-zero-power new file mode 120000 index 0000000000..6abf0eb72f --- /dev/null +++ b/Lang/Scala/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Scala \ No newline at end of file diff --git a/Lang/Scheme/Amb b/Lang/Scheme/Amb new file mode 120000 index 0000000000..c19edc9c49 --- /dev/null +++ b/Lang/Scheme/Amb @@ -0,0 +1 @@ +../../Task/Amb/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Closures-Value-capture b/Lang/Scheme/Closures-Value-capture new file mode 120000 index 0000000000..eaf048e4cd --- /dev/null +++ b/Lang/Scheme/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Scheme \ No newline at end of file diff --git a/Lang/Scheme/File-input-output b/Lang/Scheme/File-input-output new file mode 120000 index 0000000000..3939a0889f --- /dev/null +++ b/Lang/Scheme/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Generate-lower-case-ASCII-alphabet b/Lang/Scheme/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..f61687b57a --- /dev/null +++ b/Lang/Scheme/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Hash-join b/Lang/Scheme/Hash-join new file mode 120000 index 0000000000..9367355510 --- /dev/null +++ b/Lang/Scheme/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Longest-increasing-subsequence b/Lang/Scheme/Longest-increasing-subsequence new file mode 120000 index 0000000000..cf97f99831 --- /dev/null +++ b/Lang/Scheme/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Odd-word-problem b/Lang/Scheme/Odd-word-problem new file mode 120000 index 0000000000..740e737e77 --- /dev/null +++ b/Lang/Scheme/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Reverse-words-in-a-string b/Lang/Scheme/Reverse-words-in-a-string new file mode 120000 index 0000000000..cbbff379b8 --- /dev/null +++ b/Lang/Scheme/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sum-multiples-of-3-and-5 b/Lang/Scheme/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..ab14edf91e --- /dev/null +++ b/Lang/Scheme/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Zero-to-the-zero-power b/Lang/Scheme/Zero-to-the-zero-power new file mode 120000 index 0000000000..fd38e34b62 --- /dev/null +++ b/Lang/Scheme/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Scheme \ No newline at end of file diff --git a/Lang/Scilab/AKS-test-for-primes b/Lang/Scilab/AKS-test-for-primes new file mode 120000 index 0000000000..3238da9d09 --- /dev/null +++ b/Lang/Scilab/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Catalan-numbers-Pascals-triangle b/Lang/Scilab/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..8025f0d00b --- /dev/null +++ b/Lang/Scilab/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Scilab \ No newline at end of file diff --git a/Lang/Seed7/ABC-Problem b/Lang/Seed7/ABC-Problem new file mode 120000 index 0000000000..27e8df8f9b --- /dev/null +++ b/Lang/Seed7/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/AKS-test-for-primes b/Lang/Seed7/AKS-test-for-primes new file mode 120000 index 0000000000..8666d143d1 --- /dev/null +++ b/Lang/Seed7/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Amb b/Lang/Seed7/Amb new file mode 120000 index 0000000000..f31fd16d58 --- /dev/null +++ b/Lang/Seed7/Amb @@ -0,0 +1 @@ +../../Task/Amb/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/CSV-data-manipulation b/Lang/Seed7/CSV-data-manipulation new file mode 120000 index 0000000000..78bccbc067 --- /dev/null +++ b/Lang/Seed7/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Calendar---for-REAL-programmers b/Lang/Seed7/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..dc3a01f0d0 --- /dev/null +++ b/Lang/Seed7/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Casting-out-nines b/Lang/Seed7/Casting-out-nines new file mode 120000 index 0000000000..6aeb840eed --- /dev/null +++ b/Lang/Seed7/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Catalan-numbers-Pascals-triangle b/Lang/Seed7/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..add88ff3e1 --- /dev/null +++ b/Lang/Seed7/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Chinese-remainder-theorem b/Lang/Seed7/Chinese-remainder-theorem new file mode 120000 index 0000000000..84d40e6c95 --- /dev/null +++ b/Lang/Seed7/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Circles-of-given-radius-through-two-points b/Lang/Seed7/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..e1b959b423 --- /dev/null +++ b/Lang/Seed7/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Comma-quibbling b/Lang/Seed7/Comma-quibbling new file mode 120000 index 0000000000..9ed4a9675e --- /dev/null +++ b/Lang/Seed7/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Convert-decimal-number-to-rational b/Lang/Seed7/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..33811a98b1 --- /dev/null +++ b/Lang/Seed7/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Draw-a-clock b/Lang/Seed7/Draw-a-clock new file mode 120000 index 0000000000..22bf2c103d --- /dev/null +++ b/Lang/Seed7/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Extensible-prime-generator b/Lang/Seed7/Extensible-prime-generator new file mode 120000 index 0000000000..59db97e922 --- /dev/null +++ b/Lang/Seed7/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Fibonacci-word b/Lang/Seed7/Fibonacci-word new file mode 120000 index 0000000000..024ed4c387 --- /dev/null +++ b/Lang/Seed7/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/File-input-output b/Lang/Seed7/File-input-output new file mode 120000 index 0000000000..6bfe9bd434 --- /dev/null +++ b/Lang/Seed7/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Find-the-last-Sunday-of-each-month b/Lang/Seed7/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..34e6237eab --- /dev/null +++ b/Lang/Seed7/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Fractran b/Lang/Seed7/Fractran new file mode 120000 index 0000000000..f1be1fc7d9 --- /dev/null +++ b/Lang/Seed7/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Generate-Chess960-starting-position b/Lang/Seed7/Generate-Chess960-starting-position new file mode 120000 index 0000000000..f68fbc75af --- /dev/null +++ b/Lang/Seed7/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Hickerson-series-of-almost-integers b/Lang/Seed7/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..5e3c3187e3 --- /dev/null +++ b/Lang/Seed7/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/IBAN b/Lang/Seed7/IBAN new file mode 120000 index 0000000000..e599ad4d86 --- /dev/null +++ b/Lang/Seed7/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Integer-overflow b/Lang/Seed7/Integer-overflow new file mode 120000 index 0000000000..16ad67ac75 --- /dev/null +++ b/Lang/Seed7/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Left-factorials b/Lang/Seed7/Left-factorials new file mode 120000 index 0000000000..0655134508 --- /dev/null +++ b/Lang/Seed7/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Ludic-numbers b/Lang/Seed7/Ludic-numbers new file mode 120000 index 0000000000..db3d655b70 --- /dev/null +++ b/Lang/Seed7/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Magic-squares-of-odd-order b/Lang/Seed7/Magic-squares-of-odd-order new file mode 120000 index 0000000000..caa938290e --- /dev/null +++ b/Lang/Seed7/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Nth b/Lang/Seed7/Nth new file mode 120000 index 0000000000..673f8f5aba --- /dev/null +++ b/Lang/Seed7/Nth @@ -0,0 +1 @@ +../../Task/Nth/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Odd-word-problem b/Lang/Seed7/Odd-word-problem new file mode 120000 index 0000000000..4e39e28f66 --- /dev/null +++ b/Lang/Seed7/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Old-lady-swallowed-a-fly b/Lang/Seed7/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..16333cae68 --- /dev/null +++ b/Lang/Seed7/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Paraffins b/Lang/Seed7/Paraffins new file mode 120000 index 0000000000..9c5779a527 --- /dev/null +++ b/Lang/Seed7/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/RSA-code b/Lang/Seed7/RSA-code new file mode 120000 index 0000000000..adab14caef --- /dev/null +++ b/Lang/Seed7/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Rep-string b/Lang/Seed7/Rep-string new file mode 120000 index 0000000000..546e1e4826 --- /dev/null +++ b/Lang/Seed7/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Reverse-words-in-a-string b/Lang/Seed7/Reverse-words-in-a-string new file mode 120000 index 0000000000..30031bcaaa --- /dev/null +++ b/Lang/Seed7/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Semiprime b/Lang/Seed7/Semiprime new file mode 120000 index 0000000000..6cc35464c6 --- /dev/null +++ b/Lang/Seed7/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sparkline-in-unicode b/Lang/Seed7/Sparkline-in-unicode new file mode 120000 index 0000000000..156c1b3fd6 --- /dev/null +++ b/Lang/Seed7/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-append b/Lang/Seed7/String-append new file mode 120000 index 0000000000..17d103c0fb --- /dev/null +++ b/Lang/Seed7/String-append @@ -0,0 +1 @@ +../../Task/String-append/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-matching b/Lang/Seed7/String-matching new file mode 120000 index 0000000000..8de1ad143d --- /dev/null +++ b/Lang/Seed7/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-prepend b/Lang/Seed7/String-prepend new file mode 120000 index 0000000000..7958d3e7d3 --- /dev/null +++ b/Lang/Seed7/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sum-multiples-of-3-and-5 b/Lang/Seed7/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..e2d0b8ff8a --- /dev/null +++ b/Lang/Seed7/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/The-Twelve-Days-of-Christmas b/Lang/Seed7/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..801cac7955 --- /dev/null +++ b/Lang/Seed7/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Zero-to-the-zero-power b/Lang/Seed7/Zero-to-the-zero-power new file mode 120000 index 0000000000..36d74f5ab1 --- /dev/null +++ b/Lang/Seed7/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Seed7 \ No newline at end of file diff --git a/Lang/Slate/File-input-output b/Lang/Slate/File-input-output new file mode 120000 index 0000000000..eabc55b6ec --- /dev/null +++ b/Lang/Slate/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Slate \ No newline at end of file diff --git a/Lang/Smalltalk/ABC-Problem b/Lang/Smalltalk/ABC-Problem new file mode 120000 index 0000000000..8257a19ca1 --- /dev/null +++ b/Lang/Smalltalk/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Closures-Value-capture b/Lang/Smalltalk/Closures-Value-capture new file mode 120000 index 0000000000..5611997eea --- /dev/null +++ b/Lang/Smalltalk/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/File-input-output b/Lang/Smalltalk/File-input-output new file mode 120000 index 0000000000..4b3a9d54a9 --- /dev/null +++ b/Lang/Smalltalk/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Reverse-words-in-a-string b/Lang/Smalltalk/Reverse-words-in-a-string new file mode 120000 index 0000000000..bd6f96dcc3 --- /dev/null +++ b/Lang/Smalltalk/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/String-matching b/Lang/Smalltalk/String-matching new file mode 120000 index 0000000000..ca047ecf3c --- /dev/null +++ b/Lang/Smalltalk/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Zero-to-the-zero-power b/Lang/Smalltalk/Zero-to-the-zero-power new file mode 120000 index 0000000000..6561c4a7e8 --- /dev/null +++ b/Lang/Smalltalk/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Smalltalk \ No newline at end of file diff --git a/Lang/Standard-ML/Catamorphism b/Lang/Standard-ML/Catamorphism new file mode 120000 index 0000000000..f4501f3e3f --- /dev/null +++ b/Lang/Standard-ML/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Comma-quibbling b/Lang/Standard-ML/Comma-quibbling new file mode 120000 index 0000000000..c0ec18422b --- /dev/null +++ b/Lang/Standard-ML/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Currying b/Lang/Standard-ML/Currying new file mode 120000 index 0000000000..afe208505f --- /dev/null +++ b/Lang/Standard-ML/Currying @@ -0,0 +1 @@ +../../Task/Currying/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/File-input-output b/Lang/Standard-ML/File-input-output new file mode 120000 index 0000000000..59e89929a6 --- /dev/null +++ b/Lang/Standard-ML/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Generate-lower-case-ASCII-alphabet b/Lang/Standard-ML/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..a2a734d909 --- /dev/null +++ b/Lang/Standard-ML/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Longest-increasing-subsequence b/Lang/Standard-ML/Longest-increasing-subsequence new file mode 120000 index 0000000000..dfa6ec4e42 --- /dev/null +++ b/Lang/Standard-ML/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Quickselect-algorithm b/Lang/Standard-ML/Quickselect-algorithm new file mode 120000 index 0000000000..8d2c3676e4 --- /dev/null +++ b/Lang/Standard-ML/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Runge-Kutta-method b/Lang/Standard-ML/Runge-Kutta-method new file mode 120000 index 0000000000..b2e77beb2c --- /dev/null +++ b/Lang/Standard-ML/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/String-matching b/Lang/Standard-ML/String-matching new file mode 120000 index 0000000000..8ce74b2e97 --- /dev/null +++ b/Lang/Standard-ML/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Standard-ML \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Catalan-numbers-Pascals-triangle b/Lang/TI-83-BASIC/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..bb07e3d491 --- /dev/null +++ b/Lang/TI-83-BASIC/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Hello-world-Newbie b/Lang/TI-83-BASIC/Hello-world-Newbie new file mode 120000 index 0000000000..73ce752311 --- /dev/null +++ b/Lang/TI-83-BASIC/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Munching-squares b/Lang/TI-83-BASIC/Munching-squares new file mode 120000 index 0000000000..6c404f160b --- /dev/null +++ b/Lang/TI-83-BASIC/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TUSCRIPT/ABC-Problem b/Lang/TUSCRIPT/ABC-Problem new file mode 120000 index 0000000000..ca9150a2cf --- /dev/null +++ b/Lang/TUSCRIPT/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Amb b/Lang/TUSCRIPT/Amb new file mode 120000 index 0000000000..c8aaa106e7 --- /dev/null +++ b/Lang/TUSCRIPT/Amb @@ -0,0 +1 @@ +../../Task/Amb/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/CSV-data-manipulation b/Lang/TUSCRIPT/CSV-data-manipulation new file mode 120000 index 0000000000..fa63752579 --- /dev/null +++ b/Lang/TUSCRIPT/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Odd-word-problem b/Lang/TUSCRIPT/Odd-word-problem new file mode 120000 index 0000000000..5ece6ae29a --- /dev/null +++ b/Lang/TUSCRIPT/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/String-matching b/Lang/TUSCRIPT/String-matching new file mode 120000 index 0000000000..eaa5dd73e3 --- /dev/null +++ b/Lang/TUSCRIPT/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/TUSCRIPT \ No newline at end of file diff --git a/Lang/TXR/ABC-Problem b/Lang/TXR/ABC-Problem new file mode 120000 index 0000000000..82f1ac3de3 --- /dev/null +++ b/Lang/TXR/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/TXR \ No newline at end of file diff --git a/Lang/TXR/Amb b/Lang/TXR/Amb new file mode 120000 index 0000000000..4ef0437a9c --- /dev/null +++ b/Lang/TXR/Amb @@ -0,0 +1 @@ +../../Task/Amb/TXR \ No newline at end of file diff --git a/Lang/TXR/Hash-join b/Lang/TXR/Hash-join new file mode 120000 index 0000000000..11245150b5 --- /dev/null +++ b/Lang/TXR/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/TXR \ No newline at end of file diff --git a/Lang/TXR/Old-lady-swallowed-a-fly b/Lang/TXR/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..a5d438a012 --- /dev/null +++ b/Lang/TXR/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/TXR \ No newline at end of file diff --git a/Lang/TXR/String-matching b/Lang/TXR/String-matching new file mode 120000 index 0000000000..449db2a7df --- /dev/null +++ b/Lang/TXR/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/TXR \ No newline at end of file diff --git a/Lang/Tcl/9-billion-names-of-God-the-integer b/Lang/Tcl/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..9763f08758 --- /dev/null +++ b/Lang/Tcl/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Tcl \ No newline at end of file diff --git a/Lang/Tcl/ABC-Problem b/Lang/Tcl/ABC-Problem new file mode 120000 index 0000000000..5c085135cb --- /dev/null +++ b/Lang/Tcl/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Tcl \ No newline at end of file diff --git a/Lang/Tcl/AKS-test-for-primes b/Lang/Tcl/AKS-test-for-primes new file mode 120000 index 0000000000..50d966f945 --- /dev/null +++ b/Lang/Tcl/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Almost-prime b/Lang/Tcl/Almost-prime new file mode 120000 index 0000000000..77a487f9a5 --- /dev/null +++ b/Lang/Tcl/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Amb b/Lang/Tcl/Amb new file mode 120000 index 0000000000..38a675cbd9 --- /dev/null +++ b/Lang/Tcl/Amb @@ -0,0 +1 @@ +../../Task/Amb/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Amicable-pairs b/Lang/Tcl/Amicable-pairs new file mode 120000 index 0000000000..ec3ea86d78 --- /dev/null +++ b/Lang/Tcl/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Append-a-record-to-the-end-of-a-text-file b/Lang/Tcl/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..cb9aa31075 --- /dev/null +++ b/Lang/Tcl/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Tcl/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..cb2a56552f --- /dev/null +++ b/Lang/Tcl/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Benfords-law b/Lang/Tcl/Benfords-law new file mode 120000 index 0000000000..5295191165 --- /dev/null +++ b/Lang/Tcl/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Bernoulli-numbers b/Lang/Tcl/Bernoulli-numbers new file mode 120000 index 0000000000..b6146a098c --- /dev/null +++ b/Lang/Tcl/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Bitcoin-public-point-to-address b/Lang/Tcl/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..8d30bd7c16 --- /dev/null +++ b/Lang/Tcl/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Tcl \ No newline at end of file diff --git a/Lang/Tcl/CSV-data-manipulation b/Lang/Tcl/CSV-data-manipulation new file mode 120000 index 0000000000..30e5d98351 --- /dev/null +++ b/Lang/Tcl/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Calendar---for-REAL-programmers b/Lang/Tcl/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..0cb9aaa9cf --- /dev/null +++ b/Lang/Tcl/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Casting-out-nines b/Lang/Tcl/Casting-out-nines new file mode 120000 index 0000000000..22c34a8bd7 --- /dev/null +++ b/Lang/Tcl/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Catalan-numbers-Pascals-triangle b/Lang/Tcl/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..e3206859b5 --- /dev/null +++ b/Lang/Tcl/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Catamorphism b/Lang/Tcl/Catamorphism new file mode 120000 index 0000000000..9ca508cd94 --- /dev/null +++ b/Lang/Tcl/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Chinese-remainder-theorem b/Lang/Tcl/Chinese-remainder-theorem new file mode 120000 index 0000000000..e002fff774 --- /dev/null +++ b/Lang/Tcl/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Circles-of-given-radius-through-two-points b/Lang/Tcl/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..c8849c1ca2 --- /dev/null +++ b/Lang/Tcl/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Closures-Value-capture b/Lang/Tcl/Closures-Value-capture new file mode 120000 index 0000000000..3a35f06ec4 --- /dev/null +++ b/Lang/Tcl/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Combinations-and-permutations b/Lang/Tcl/Combinations-and-permutations new file mode 120000 index 0000000000..6500a6a0e6 --- /dev/null +++ b/Lang/Tcl/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Comma-quibbling b/Lang/Tcl/Comma-quibbling new file mode 120000 index 0000000000..2bdb8851a1 --- /dev/null +++ b/Lang/Tcl/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Conjugate-transpose b/Lang/Tcl/Conjugate-transpose new file mode 120000 index 0000000000..1f28e09d9d --- /dev/null +++ b/Lang/Tcl/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Convert-decimal-number-to-rational b/Lang/Tcl/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..3380963163 --- /dev/null +++ b/Lang/Tcl/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Currying b/Lang/Tcl/Currying new file mode 120000 index 0000000000..15eba2ee48 --- /dev/null +++ b/Lang/Tcl/Currying @@ -0,0 +1 @@ +../../Task/Currying/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Digital-root-Multiplicative-digital-root b/Lang/Tcl/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..83f0f304a4 --- /dev/null +++ b/Lang/Tcl/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Draw-a-clock b/Lang/Tcl/Draw-a-clock new file mode 120000 index 0000000000..f3d019520b --- /dev/null +++ b/Lang/Tcl/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Extensible-prime-generator b/Lang/Tcl/Extensible-prime-generator new file mode 120000 index 0000000000..4b1ac10ab1 --- /dev/null +++ b/Lang/Tcl/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Fibonacci-word b/Lang/Tcl/Fibonacci-word new file mode 120000 index 0000000000..7f1df9fc24 --- /dev/null +++ b/Lang/Tcl/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Fibonacci-word-fractal b/Lang/Tcl/Fibonacci-word-fractal new file mode 120000 index 0000000000..bbbd26a36e --- /dev/null +++ b/Lang/Tcl/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Tcl \ No newline at end of file diff --git a/Lang/Tcl/File-input-output b/Lang/Tcl/File-input-output new file mode 120000 index 0000000000..52d0537f51 --- /dev/null +++ b/Lang/Tcl/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Find-the-last-Sunday-of-each-month b/Lang/Tcl/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..801604a38a --- /dev/null +++ b/Lang/Tcl/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Flipping-bits-game b/Lang/Tcl/Flipping-bits-game new file mode 120000 index 0000000000..696269555f --- /dev/null +++ b/Lang/Tcl/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Fractran b/Lang/Tcl/Fractran new file mode 120000 index 0000000000..26ad9b7585 --- /dev/null +++ b/Lang/Tcl/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Gaussian-elimination b/Lang/Tcl/Gaussian-elimination new file mode 120000 index 0000000000..2db50b3c19 --- /dev/null +++ b/Lang/Tcl/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Generate-Chess960-starting-position b/Lang/Tcl/Generate-Chess960-starting-position new file mode 120000 index 0000000000..7a3f4e54f9 --- /dev/null +++ b/Lang/Tcl/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Generate-lower-case-ASCII-alphabet b/Lang/Tcl/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..0155c4eb2c --- /dev/null +++ b/Lang/Tcl/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Hash-join b/Lang/Tcl/Hash-join new file mode 120000 index 0000000000..38beb38010 --- /dev/null +++ b/Lang/Tcl/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Hello-world-Newbie b/Lang/Tcl/Hello-world-Newbie new file mode 120000 index 0000000000..d350b7ce77 --- /dev/null +++ b/Lang/Tcl/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Hickerson-series-of-almost-integers b/Lang/Tcl/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..5ea76bada2 --- /dev/null +++ b/Lang/Tcl/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/IBAN b/Lang/Tcl/IBAN new file mode 120000 index 0000000000..bd4c650bc8 --- /dev/null +++ b/Lang/Tcl/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Integer-overflow b/Lang/Tcl/Integer-overflow new file mode 120000 index 0000000000..170b36c39e --- /dev/null +++ b/Lang/Tcl/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Iterated-digits-squaring b/Lang/Tcl/Iterated-digits-squaring new file mode 120000 index 0000000000..4e76f5aae1 --- /dev/null +++ b/Lang/Tcl/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Tcl \ No newline at end of file diff --git a/Lang/Tcl/K-d-tree b/Lang/Tcl/K-d-tree new file mode 120000 index 0000000000..d1f78afb42 --- /dev/null +++ b/Lang/Tcl/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Left-factorials b/Lang/Tcl/Left-factorials new file mode 120000 index 0000000000..bd7833a9a3 --- /dev/null +++ b/Lang/Tcl/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Longest-increasing-subsequence b/Lang/Tcl/Longest-increasing-subsequence new file mode 120000 index 0000000000..f7674f7b83 --- /dev/null +++ b/Lang/Tcl/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Ludic-numbers b/Lang/Tcl/Ludic-numbers new file mode 120000 index 0000000000..7fb20bb746 --- /dev/null +++ b/Lang/Tcl/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Machine-code b/Lang/Tcl/Machine-code new file mode 120000 index 0000000000..249526efc4 --- /dev/null +++ b/Lang/Tcl/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Magic-squares-of-odd-order b/Lang/Tcl/Magic-squares-of-odd-order new file mode 120000 index 0000000000..7bc81ce004 --- /dev/null +++ b/Lang/Tcl/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Make-directory-path b/Lang/Tcl/Make-directory-path new file mode 120000 index 0000000000..c917c56de7 --- /dev/null +++ b/Lang/Tcl/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Maximum-triangle-path-sum b/Lang/Tcl/Maximum-triangle-path-sum new file mode 120000 index 0000000000..f257e103c1 --- /dev/null +++ b/Lang/Tcl/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Move-to-front-algorithm b/Lang/Tcl/Move-to-front-algorithm new file mode 120000 index 0000000000..716ee4bb44 --- /dev/null +++ b/Lang/Tcl/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Munching-squares b/Lang/Tcl/Munching-squares new file mode 120000 index 0000000000..7a2b01526b --- /dev/null +++ b/Lang/Tcl/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Narcissistic-decimal-number b/Lang/Tcl/Narcissistic-decimal-number new file mode 120000 index 0000000000..40acfbb781 --- /dev/null +++ b/Lang/Tcl/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Natural-sorting b/Lang/Tcl/Natural-sorting new file mode 120000 index 0000000000..1329a12399 --- /dev/null +++ b/Lang/Tcl/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Nth b/Lang/Tcl/Nth new file mode 120000 index 0000000000..31ceda276a --- /dev/null +++ b/Lang/Tcl/Nth @@ -0,0 +1 @@ +../../Task/Nth/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Odd-word-problem b/Lang/Tcl/Odd-word-problem new file mode 120000 index 0000000000..bc10995c97 --- /dev/null +++ b/Lang/Tcl/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Old-lady-swallowed-a-fly b/Lang/Tcl/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..7bf77261b9 --- /dev/null +++ b/Lang/Tcl/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Order-disjoint-list-items b/Lang/Tcl/Order-disjoint-list-items new file mode 120000 index 0000000000..a6851b8844 --- /dev/null +++ b/Lang/Tcl/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Paraffins b/Lang/Tcl/Paraffins new file mode 120000 index 0000000000..6ec0ca232e --- /dev/null +++ b/Lang/Tcl/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Parse-an-IP-Address b/Lang/Tcl/Parse-an-IP-Address new file mode 120000 index 0000000000..208700cc83 --- /dev/null +++ b/Lang/Tcl/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Penneys-game b/Lang/Tcl/Penneys-game new file mode 120000 index 0000000000..148a11aa06 --- /dev/null +++ b/Lang/Tcl/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Percolation-Bond-percolation b/Lang/Tcl/Percolation-Bond-percolation new file mode 120000 index 0000000000..2e3a994b4c --- /dev/null +++ b/Lang/Tcl/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Percolation-Mean-cluster-density b/Lang/Tcl/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..62a72f472a --- /dev/null +++ b/Lang/Tcl/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Percolation-Mean-run-density b/Lang/Tcl/Percolation-Mean-run-density new file mode 120000 index 0000000000..bf17ee677a --- /dev/null +++ b/Lang/Tcl/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Percolation-Site-percolation b/Lang/Tcl/Percolation-Site-percolation new file mode 120000 index 0000000000..0029613a17 --- /dev/null +++ b/Lang/Tcl/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Permutations-Rank-of-a-permutation b/Lang/Tcl/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..402e4bf6ca --- /dev/null +++ b/Lang/Tcl/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Pernicious-numbers b/Lang/Tcl/Pernicious-numbers new file mode 120000 index 0000000000..8bb41f3333 --- /dev/null +++ b/Lang/Tcl/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Phrase-reversals b/Lang/Tcl/Phrase-reversals new file mode 120000 index 0000000000..59fbddf09e --- /dev/null +++ b/Lang/Tcl/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Quickselect-algorithm b/Lang/Tcl/Quickselect-algorithm new file mode 120000 index 0000000000..b26a81d41c --- /dev/null +++ b/Lang/Tcl/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Tcl/RSA-code b/Lang/Tcl/RSA-code new file mode 120000 index 0000000000..70b5ded386 --- /dev/null +++ b/Lang/Tcl/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Ranking-methods b/Lang/Tcl/Ranking-methods new file mode 120000 index 0000000000..689f13d77b --- /dev/null +++ b/Lang/Tcl/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Rep-string b/Lang/Tcl/Rep-string new file mode 120000 index 0000000000..937ac8e9ed --- /dev/null +++ b/Lang/Tcl/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Reverse-words-in-a-string b/Lang/Tcl/Reverse-words-in-a-string new file mode 120000 index 0000000000..3feb3b5948 --- /dev/null +++ b/Lang/Tcl/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Runge-Kutta-method b/Lang/Tcl/Runge-Kutta-method new file mode 120000 index 0000000000..982602cfa1 --- /dev/null +++ b/Lang/Tcl/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Semiprime b/Lang/Tcl/Semiprime new file mode 120000 index 0000000000..1737aa0e2d --- /dev/null +++ b/Lang/Tcl/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sequence-of-primes-by-Trial-Division b/Lang/Tcl/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..f647af3e79 --- /dev/null +++ b/Lang/Tcl/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Solve-a-Holy-Knights-tour b/Lang/Tcl/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..0e9c377e8e --- /dev/null +++ b/Lang/Tcl/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Solve-a-Hopido-puzzle b/Lang/Tcl/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..d17afadb66 --- /dev/null +++ b/Lang/Tcl/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Solve-the-no-connection-puzzle b/Lang/Tcl/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..df35bb9b04 --- /dev/null +++ b/Lang/Tcl/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sparkline-in-unicode b/Lang/Tcl/Sparkline-in-unicode new file mode 120000 index 0000000000..82667dbc46 --- /dev/null +++ b/Lang/Tcl/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Tcl \ No newline at end of file diff --git a/Lang/Tcl/State-name-puzzle b/Lang/Tcl/State-name-puzzle new file mode 120000 index 0000000000..1e3e7b56a9 --- /dev/null +++ b/Lang/Tcl/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Statistics-Basic b/Lang/Tcl/Statistics-Basic new file mode 120000 index 0000000000..3381774045 --- /dev/null +++ b/Lang/Tcl/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-append b/Lang/Tcl/String-append new file mode 120000 index 0000000000..bd0d9dedc6 --- /dev/null +++ b/Lang/Tcl/String-append @@ -0,0 +1 @@ +../../Task/String-append/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-matching b/Lang/Tcl/String-matching new file mode 120000 index 0000000000..a6b3580da6 --- /dev/null +++ b/Lang/Tcl/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-prepend b/Lang/Tcl/String-prepend new file mode 120000 index 0000000000..4212b62a4f --- /dev/null +++ b/Lang/Tcl/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sum-multiples-of-3-and-5 b/Lang/Tcl/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..6758fae102 --- /dev/null +++ b/Lang/Tcl/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Tcl \ No newline at end of file diff --git a/Lang/Tcl/The-ISAAC-Cipher b/Lang/Tcl/The-ISAAC-Cipher new file mode 120000 index 0000000000..23ad9da80b --- /dev/null +++ b/Lang/Tcl/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Tcl \ No newline at end of file diff --git a/Lang/Tcl/The-Twelve-Days-of-Christmas b/Lang/Tcl/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..99ab2e721c --- /dev/null +++ b/Lang/Tcl/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Total-circles-area b/Lang/Tcl/Total-circles-area new file mode 120000 index 0000000000..b175482104 --- /dev/null +++ b/Lang/Tcl/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Unix-ls b/Lang/Tcl/Unix-ls new file mode 120000 index 0000000000..ab0a67ce77 --- /dev/null +++ b/Lang/Tcl/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Vogels-approximation-method b/Lang/Tcl/Vogels-approximation-method new file mode 120000 index 0000000000..2af1a99fae --- /dev/null +++ b/Lang/Tcl/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Tcl \ No newline at end of file diff --git a/Lang/Tcl/World-Cup-group-stage b/Lang/Tcl/World-Cup-group-stage new file mode 120000 index 0000000000..8e1fe320f3 --- /dev/null +++ b/Lang/Tcl/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Zero-to-the-zero-power b/Lang/Tcl/Zero-to-the-zero-power new file mode 120000 index 0000000000..c95b993386 --- /dev/null +++ b/Lang/Tcl/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Zhang-Suen-thinning-algorithm b/Lang/Tcl/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..719c3d4b78 --- /dev/null +++ b/Lang/Tcl/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Toka/File-input-output b/Lang/Toka/File-input-output new file mode 120000 index 0000000000..efd0ff09b3 --- /dev/null +++ b/Lang/Toka/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Toka \ No newline at end of file diff --git a/Lang/UNIX-Shell/ABC-Problem b/Lang/UNIX-Shell/ABC-Problem new file mode 120000 index 0000000000..4d815939f3 --- /dev/null +++ b/Lang/UNIX-Shell/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Append-a-record-to-the-end-of-a-text-file b/Lang/UNIX-Shell/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..3d68a76ef7 --- /dev/null +++ b/Lang/UNIX-Shell/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/CSV-data-manipulation b/Lang/UNIX-Shell/CSV-data-manipulation new file mode 120000 index 0000000000..06c933a557 --- /dev/null +++ b/Lang/UNIX-Shell/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Comma-quibbling b/Lang/UNIX-Shell/Comma-quibbling new file mode 120000 index 0000000000..c9ca895f7f --- /dev/null +++ b/Lang/UNIX-Shell/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/File-input-output b/Lang/UNIX-Shell/File-input-output new file mode 120000 index 0000000000..4ebb616c06 --- /dev/null +++ b/Lang/UNIX-Shell/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Generate-lower-case-ASCII-alphabet b/Lang/UNIX-Shell/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..56ceaa7ab4 --- /dev/null +++ b/Lang/UNIX-Shell/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/IBAN b/Lang/UNIX-Shell/IBAN new file mode 120000 index 0000000000..ce60d628fc --- /dev/null +++ b/Lang/UNIX-Shell/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Make-directory-path b/Lang/UNIX-Shell/Make-directory-path new file mode 120000 index 0000000000..8a5a9757ec --- /dev/null +++ b/Lang/UNIX-Shell/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Narcissistic-decimal-number b/Lang/UNIX-Shell/Narcissistic-decimal-number new file mode 120000 index 0000000000..76ab481a92 --- /dev/null +++ b/Lang/UNIX-Shell/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Penneys-game b/Lang/UNIX-Shell/Penneys-game new file mode 120000 index 0000000000..d87c7e450c --- /dev/null +++ b/Lang/UNIX-Shell/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Phrase-reversals b/Lang/UNIX-Shell/Phrase-reversals new file mode 120000 index 0000000000..766815a66f --- /dev/null +++ b/Lang/UNIX-Shell/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Rep-string b/Lang/UNIX-Shell/Rep-string new file mode 120000 index 0000000000..2a73c95be1 --- /dev/null +++ b/Lang/UNIX-Shell/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Reverse-words-in-a-string b/Lang/UNIX-Shell/Reverse-words-in-a-string new file mode 120000 index 0000000000..5dc2e86406 --- /dev/null +++ b/Lang/UNIX-Shell/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/Ursala/File-input-output b/Lang/Ursala/File-input-output new file mode 120000 index 0000000000..99af38a0a8 --- /dev/null +++ b/Lang/Ursala/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Ursala \ No newline at end of file diff --git a/Lang/VBA/String-append b/Lang/VBA/String-append new file mode 120000 index 0000000000..81c5055f2b --- /dev/null +++ b/Lang/VBA/String-append @@ -0,0 +1 @@ +../../Task/String-append/VBA \ No newline at end of file diff --git a/Lang/VBA/String-prepend b/Lang/VBA/String-prepend new file mode 120000 index 0000000000..c60906d033 --- /dev/null +++ b/Lang/VBA/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/VBA \ No newline at end of file diff --git a/Lang/VBScript/Abundant,-deficient-and-perfect-number-classifications b/Lang/VBScript/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..4b77871794 --- /dev/null +++ b/Lang/VBScript/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Amb b/Lang/VBScript/Amb new file mode 120000 index 0000000000..4ec268c5eb --- /dev/null +++ b/Lang/VBScript/Amb @@ -0,0 +1 @@ +../../Task/Amb/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Amicable-pairs b/Lang/VBScript/Amicable-pairs new file mode 120000 index 0000000000..a5331ded01 --- /dev/null +++ b/Lang/VBScript/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Catalan-numbers-Pascals-triangle b/Lang/VBScript/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..50b29e050d --- /dev/null +++ b/Lang/VBScript/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/VBScript \ No newline at end of file diff --git a/Lang/VBScript/File-input-output b/Lang/VBScript/File-input-output new file mode 120000 index 0000000000..71cfabdbe3 --- /dev/null +++ b/Lang/VBScript/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Find-the-last-Sunday-of-each-month b/Lang/VBScript/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..0839f6b883 --- /dev/null +++ b/Lang/VBScript/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Stern-Brocot-sequence b/Lang/VBScript/Stern-Brocot-sequence new file mode 120000 index 0000000000..ce83bb2e31 --- /dev/null +++ b/Lang/VBScript/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Textonyms b/Lang/VBScript/Textonyms new file mode 120000 index 0000000000..2818fa96aa --- /dev/null +++ b/Lang/VBScript/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/VBScript \ No newline at end of file diff --git a/Lang/Vedit-macro-language/CSV-data-manipulation b/Lang/Vedit-macro-language/CSV-data-manipulation new file mode 120000 index 0000000000..7b0db32630 --- /dev/null +++ b/Lang/Vedit-macro-language/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Calendar---for-REAL-programmers b/Lang/Vedit-macro-language/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..1a37d41a84 --- /dev/null +++ b/Lang/Vedit-macro-language/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/File-input-output b/Lang/Vedit-macro-language/File-input-output new file mode 120000 index 0000000000..e41f0dfb55 --- /dev/null +++ b/Lang/Vedit-macro-language/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vim-Script/Generate-lower-case-ASCII-alphabet b/Lang/Vim-Script/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d8ed64aa60 --- /dev/null +++ b/Lang/Vim-Script/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Vim-Script \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/File-input-output b/Lang/Visual-Basic-.NET/File-input-output new file mode 120000 index 0000000000..5276a6ad86 --- /dev/null +++ b/Lang/Visual-Basic-.NET/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic/Catalan-numbers-Pascals-triangle b/Lang/Visual-Basic/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..ff725a42a0 --- /dev/null +++ b/Lang/Visual-Basic/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Visual-Basic \ No newline at end of file diff --git a/Lang/X86-Assembly/Calendar---for-REAL-programmers b/Lang/X86-Assembly/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..0a714c855a --- /dev/null +++ b/Lang/X86-Assembly/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/X86-Assembly \ No newline at end of file diff --git a/Lang/XPL0/Circles-of-given-radius-through-two-points b/Lang/XPL0/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..c8bab7c254 --- /dev/null +++ b/Lang/XPL0/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Comma-quibbling b/Lang/XPL0/Comma-quibbling new file mode 120000 index 0000000000..62ab4bec51 --- /dev/null +++ b/Lang/XPL0/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/File-input-output b/Lang/XPL0/File-input-output new file mode 120000 index 0000000000..e8d64b7b48 --- /dev/null +++ b/Lang/XPL0/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Munching-squares b/Lang/XPL0/Munching-squares new file mode 120000 index 0000000000..51d114e27c --- /dev/null +++ b/Lang/XPL0/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Solve-the-no-connection-puzzle b/Lang/XPL0/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..5d02f55775 --- /dev/null +++ b/Lang/XPL0/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/String-matching b/Lang/XPL0/String-matching new file mode 120000 index 0000000000..b223a9d3af --- /dev/null +++ b/Lang/XPL0/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sum-multiples-of-3-and-5 b/Lang/XPL0/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..5ab1f5d872 --- /dev/null +++ b/Lang/XPL0/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/XPL0 \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Hello-world-Newbie b/Lang/ZX-Spectrum-Basic/Hello-world-Newbie new file mode 120000 index 0000000000..04bf705f52 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Meta/Task.yaml b/Meta/Task.yaml index 8921d14f75..35cfc1ffd0 100644 --- a/Meta/Task.yaml +++ b/Meta/Task.yaml @@ -11,6 +11,10 @@ name: 24 game/Solve path: 24-game-Solve url: 24_game/Solve +9 billion names of God the integer: + name: 9 billion names of God the integer + path: 9-billion-names-of-God-the-integer + url: 9_billion_names_of_God_the_integer 99 Bottles of Beer: name: 99 Bottles of Beer path: 99-Bottles-of-Beer @@ -19,10 +23,22 @@ A+B: name: A+B path: A+B url: A+B +ABC Problem: + name: ABC Problem + path: ABC-Problem + url: ABC_Problem +AKS test for primes: + name: AKS test for primes + path: AKS-test-for-primes + url: AKS_test_for_primes Abstract type: name: Abstract type path: Abstract-type url: Abstract_type +Abundant, deficient and perfect number classifications: + name: Abundant, deficient and perfect number classifications + path: Abundant,-deficient-and-perfect-number-classifications + url: Abundant,_deficient_and_perfect_number_classifications Accumulator factory: name: Accumulator factory path: Accumulator-factory @@ -55,6 +71,22 @@ Align columns: name: Align columns path: Align-columns url: Align_columns +Aliquot sequence classifications: + name: Aliquot sequence classifications + path: Aliquot-sequence-classifications + url: Aliquot_sequence_classifications +Almost prime: + name: Almost prime + path: Almost-prime + url: Almost_prime +Amb: + name: Amb + path: Amb + url: Amb +Amicable pairs: + name: Amicable pairs + path: Amicable-pairs + url: Amicable_pairs Anagrams: name: Anagrams path: Anagrams @@ -75,6 +107,10 @@ Anonymous recursion: name: Anonymous recursion path: Anonymous-recursion url: Anonymous_recursion +Append a record to the end of a text file: + name: Append a record to the end of a text file + path: Append-a-record-to-the-end-of-a-text-file + url: Append_a_record_to_the_end_of_a_text_file Apply a callback to an array: name: Apply a callback to an array path: Apply-a-callback-to-an-array @@ -95,6 +131,10 @@ Arithmetic-geometric mean: name: Arithmetic-geometric mean path: Arithmetic-geometric-mean url: Arithmetic-geometric_mean +Arithmetic-geometric mean/Calculate Pi: + name: Arithmetic-geometric mean/Calculate Pi + path: Arithmetic-geometric-mean-Calculate-Pi + url: Arithmetic-geometric_mean/Calculate_Pi Arithmetic/Complex: name: Arithmetic/Complex path: Arithmetic-Complex @@ -175,6 +215,14 @@ Balanced ternary: name: Balanced ternary path: Balanced-ternary url: Balanced_ternary +Benford's law: + name: Benford's law + path: Benfords-law + url: Benford's_law +Bernoulli numbers: + name: Bernoulli numbers + path: Bernoulli-numbers + url: Bernoulli_numbers Best shuffle: name: Best shuffle path: Best-shuffle @@ -195,6 +243,10 @@ Bitcoin/address validation: name: Bitcoin/address validation path: Bitcoin-address-validation url: Bitcoin/address_validation +Bitcoin/public point to address: + name: Bitcoin/public point to address + path: Bitcoin-public-point-to-address + url: Bitcoin/public_point_to_address Bitmap: name: Bitmap path: Bitmap @@ -275,6 +327,10 @@ CRC-32: name: CRC-32 path: CRC-32 url: CRC-32 +CSV data manipulation: + name: CSV data manipulation + path: CSV-data-manipulation + url: CSV_data_manipulation CSV to HTML translation: name: CSV to HTML translation path: CSV-to-HTML-translation @@ -287,10 +343,10 @@ Calendar: name: Calendar path: Calendar url: Calendar -Calendar - for "real" programmers: - name: Calendar - for "real" programmers - path: Calendar---for-real-programmers - url: Calendar_-_for_"real"_programmers +Calendar - for "REAL" programmers: + name: Calendar - for "REAL" programmers + path: Calendar---for-REAL-programmers + url: Calendar_-_for_"REAL"_programmers Call a foreign-language function: name: Call a foreign-language function path: Call-a-foreign-language-function @@ -319,10 +375,22 @@ Case-sensitivity of identifiers: name: Case-sensitivity of identifiers path: Case-sensitivity-of-identifiers url: Case-sensitivity_of_identifiers +Casting out nines: + name: Casting out nines + path: Casting-out-nines + url: Casting_out_nines Catalan numbers: name: Catalan numbers path: Catalan-numbers url: Catalan_numbers +Catalan numbers/Pascal's triangle: + name: Catalan numbers/Pascal's triangle + path: Catalan-numbers-Pascals-triangle + url: Catalan_numbers/Pascal's_triangle +Catamorphism: + name: Catamorphism + path: Catamorphism + url: Catamorphism Catmull–Clark subdivision surface: name: Catmull–Clark subdivision surface path: Catmull-Clark-subdivision-surface @@ -331,10 +399,6 @@ Character codes: name: Character codes path: Character-codes url: Character_codes -Character matching: - name: Character matching - path: Character-matching - url: Character_matching Chat server: name: Chat server path: Chat-server @@ -351,10 +415,18 @@ Checkpoint synchronization: name: Checkpoint synchronization path: Checkpoint-synchronization url: Checkpoint_synchronization +Chinese remainder theorem: + name: Chinese remainder theorem + path: Chinese-remainder-theorem + url: Chinese_remainder_theorem Cholesky decomposition: name: Cholesky decomposition path: Cholesky-decomposition url: Cholesky_decomposition +Circles of given radius through two points: + name: Circles of given radius through two points + path: Circles-of-given-radius-through-two-points + url: Circles_of_given_radius_through_two_points Classes: name: Classes path: Classes @@ -363,6 +435,10 @@ Closest-pair problem: name: Closest-pair problem path: Closest-pair-problem url: Closest-pair_problem +Closures/Value capture: + name: Closures/Value capture + path: Closures-Value-capture + url: Closures/Value_capture Collections: name: Collections path: Collections @@ -391,10 +467,18 @@ Combinations: name: Combinations path: Combinations url: Combinations +Combinations and permutations: + name: Combinations and permutations + path: Combinations-and-permutations + url: Combinations_and_permutations Combinations with repetitions: name: Combinations with repetitions path: Combinations-with-repetitions url: Combinations_with_repetitions +Comma quibbling: + name: Comma quibbling + path: Comma-quibbling + url: Comma_quibbling Command-line arguments: name: Command-line arguments path: Command-line-arguments @@ -423,6 +507,10 @@ Conditional structures: name: Conditional structures path: Conditional-structures url: Conditional_structures +Conjugate transpose: + name: Conjugate transpose + path: Conjugate-transpose + url: Conjugate_transpose Constrained genericity: name: Constrained genericity path: Constrained-genericity @@ -448,6 +536,10 @@ Continued fraction/Arithmetic/G(matrix NG, Contined Fraction N1, Contined Fracti Fraction N2) path: Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- url: Continued_fraction/Arithmetic/G(matrix_NG,_Contined_Fraction_N1,_Contined_Fraction_N2) +Convert decimal number to rational: + name: Convert decimal number to rational + path: Convert-decimal-number-to-rational + url: Convert_decimal_number_to_rational Conway's Game of Life: name: Conway's Game of Life path: Conways-Game-of-Life @@ -492,6 +584,10 @@ Create an object at a given address: name: Create an object at a given address path: Create-an-object-at-a-given-address url: Create_an_object_at_a_given_address +Currying: + name: Currying + path: Currying + url: Currying Cut a rectangle: name: Cut a rectangle path: Cut-a-rectangle @@ -560,6 +656,10 @@ Digital root: name: Digital root path: Digital-root url: Digital_root +Digital root/Multiplicative digital root: + name: Digital root/Multiplicative digital root + path: Digital-root-Multiplicative-digital-root + url: Digital_root/Multiplicative_digital_root Dinesman's multiple-dwelling problem: name: Dinesman's multiple-dwelling problem path: Dinesmans-multiple-dwelling-problem @@ -604,6 +704,10 @@ Dragon curve: name: Dragon curve path: Dragon-curve url: Dragon_curve +Draw a clock: + name: Draw a clock + path: Draw-a-clock + url: Draw_a_clock Draw a cuboid: name: Draw a cuboid path: Draw-a-cuboid @@ -724,6 +828,10 @@ Extend your language: name: Extend your language path: Extend-your-language url: Extend_your_language +Extensible prime generator: + name: Extensible prime generator + path: Extensible-prime-generator + url: Extensible_prime_generator Extreme floating point values: name: Extreme floating point values path: Extreme-floating-point-values @@ -752,10 +860,18 @@ Fibonacci sequence: name: Fibonacci sequence path: Fibonacci-sequence url: Fibonacci_sequence -File IO: - name: File IO - path: File-IO - url: File_IO +Fibonacci word: + name: Fibonacci word + path: Fibonacci-word + url: Fibonacci_word +Fibonacci word/fractal: + name: Fibonacci word/fractal + path: Fibonacci-word-fractal + url: Fibonacci_word/fractal +File input/output: + name: File input/output + path: File-input-output + url: File_input/output File modification time: name: File modification time path: File-modification-time @@ -780,6 +896,10 @@ Find limit of recursion: name: Find limit of recursion path: Find-limit-of-recursion url: Find_limit_of_recursion +Find the last Sunday of each month: + name: Find the last Sunday of each month + path: Find-the-last-Sunday-of-each-month + url: Find_the_last_Sunday_of_each_month Find the missing permutation: name: Find the missing permutation path: Find-the-missing-permutation @@ -808,6 +928,10 @@ Flatten a list: name: Flatten a list path: Flatten-a-list url: Flatten_a_list +Flipping bits game: + name: Flipping bits game + path: Flipping-bits-game + url: Flipping_bits_game Flow-control structures: name: Flow-control structures path: Flow-control-structures @@ -844,6 +968,10 @@ Fractal tree: name: Fractal tree path: Fractal-tree url: Fractal_tree +Fractran: + name: Fractran + path: Fractran + url: Fractran Function composition: name: Function composition path: Function-composition @@ -880,6 +1008,18 @@ Gamma function: name: Gamma function path: Gamma-function url: Gamma_function +Gaussian elimination: + name: Gaussian elimination + path: Gaussian-elimination + url: Gaussian_elimination +Generate Chess960 starting position: + name: Generate Chess960 starting position + path: Generate-Chess960-starting-position + url: Generate_Chess960_starting_position +Generate lower case ASCII alphabet: + name: Generate lower case ASCII alphabet + path: Generate-lower-case-ASCII-alphabet + url: Generate_lower_case_ASCII_alphabet Generator/Exponential: name: Generator/Exponential path: Generator-Exponential @@ -972,6 +1112,10 @@ Hash from two arrays: name: Hash from two arrays path: Hash-from-two-arrays url: Hash_from_two_arrays +Hash join: + name: Hash join + path: Hash-join + url: Hash_join Haversine formula: name: Haversine formula path: Haversine-formula @@ -984,6 +1128,10 @@ Hello world/Line printer: name: Hello world/Line printer path: Hello-world-Line-printer url: Hello_world/Line_printer +Hello world/Newbie: + name: Hello world/Newbie + path: Hello-world-Newbie + url: Hello_world/Newbie Hello world/Newline omission: name: Hello world/Newline omission path: Hello-world-Newline-omission @@ -1004,6 +1152,14 @@ Here document: name: Here document path: Here-document url: Here_document +Heronian triangles: + name: Heronian triangles + path: Heronian-triangles + url: Heronian_triangles +Hickerson series of almost integers: + name: Hickerson series of almost integers + path: Hickerson-series-of-almost-integers + url: Hickerson_series_of_almost_integers Higher-order functions: name: Higher-order functions path: Higher-order-functions @@ -1060,6 +1216,10 @@ I before E except after C: name: I before E except after C path: I-before-E-except-after-C url: I_before_E_except_after_C +IBAN: + name: IBAN + path: IBAN + url: IBAN Identity matrix: name: Identity matrix path: Identity-matrix @@ -1100,6 +1260,10 @@ Integer comparison: name: Integer comparison path: Integer-comparison url: Integer_comparison +Integer overflow: + name: Integer overflow + path: Integer-overflow + url: Integer_overflow Integer sequence: name: Integer sequence path: Integer-sequence @@ -1120,6 +1284,10 @@ Inverted syntax: name: Inverted syntax path: Inverted-syntax url: Inverted_syntax +Iterated digits squaring: + name: Iterated digits squaring + path: Iterated-digits-squaring + url: Iterated_digits_squaring JSON: name: JSON path: JSON @@ -1140,6 +1308,10 @@ Jump anywhere: name: Jump anywhere path: Jump-anywhere url: Jump_anywhere +K-d tree: + name: K-d tree + path: K-d-tree + url: K-d_tree K-means++ clustering: name: K-means++ clustering path: K-means++-clustering @@ -1224,6 +1396,10 @@ Least common multiple: name: Least common multiple path: Least-common-multiple url: Least_common_multiple +Left factorials: + name: Left factorials + path: Left-factorials + url: Left_factorials Letter frequency: name: Letter frequency path: Letter-frequency @@ -1264,6 +1440,10 @@ Longest common subsequence: name: Longest common subsequence path: Longest-common-subsequence url: Longest_common_subsequence +Longest increasing subsequence: + name: Longest increasing subsequence + path: Longest-increasing-subsequence + url: Longest_increasing_subsequence Longest string challenge: name: Longest string challenge path: Longest-string-challenge @@ -1324,6 +1504,10 @@ Lucas-Lehmer test: name: Lucas-Lehmer test path: Lucas-Lehmer-test url: Lucas-Lehmer_test +Ludic numbers: + name: Ludic numbers + path: Ludic-numbers + url: Ludic_numbers Luhn test of credit card numbers: name: Luhn test of credit card numbers path: Luhn-test-of-credit-card-numbers @@ -1340,14 +1524,26 @@ MD5/Implementation: name: MD5/Implementation path: MD5-Implementation url: MD5/Implementation +Machine code: + name: Machine code + path: Machine-code + url: Machine_code Mad Libs: name: Mad Libs path: Mad-Libs url: Mad_Libs +Magic squares of odd order: + name: Magic squares of odd order + path: Magic-squares-of-odd-order + url: Magic_squares_of_odd_order Main step of GOST 28147-89: name: Main step of GOST 28147-89 path: Main-step-of-GOST-28147-89 url: Main_step_of_GOST_28147-89 +Make directory path: + name: Make directory path + path: Make-directory-path + url: Make_directory_path Man or boy test: name: Man or boy test path: Man-or-boy-test @@ -1376,6 +1572,10 @@ Matrix-exponentiation operator: name: Matrix-exponentiation operator path: Matrix-exponentiation-operator url: Matrix-exponentiation_operator +Maximum triangle path sum: + name: Maximum triangle path sum + path: Maximum-triangle-path-sum + url: Maximum_triangle_path_sum Maze generation: name: Maze generation path: Maze-generation @@ -1448,6 +1648,10 @@ Mouse position: name: Mouse position path: Mouse-position url: Mouse_position +Move-to-front algorithm: + name: Move-to-front algorithm + path: Move-to-front-algorithm + url: Move-to-front_algorithm Multifactorial: name: Multifactorial path: Multifactorial @@ -1472,10 +1676,18 @@ Multisplit: name: Multisplit path: Multisplit url: Multisplit +Munching squares: + name: Munching squares + path: Munching-squares + url: Munching_squares Mutual recursion: name: Mutual recursion path: Mutual-recursion url: Mutual_recursion +N'th: + name: N'th + path: Nth + url: N'th N-queens problem: name: N-queens problem path: N-queens-problem @@ -1488,6 +1700,14 @@ Narcissist: name: Narcissist path: Narcissist url: Narcissist +Narcissistic decimal number: + name: Narcissistic decimal number + path: Narcissistic-decimal-number + url: Narcissistic_decimal_number +Natural sorting: + name: Natural sorting + path: Natural-sorting + url: Natural_sorting Nautical bell: name: Nautical bell path: Nautical-bell @@ -1544,6 +1764,14 @@ Object serialization: name: Object serialization path: Object-serialization url: Object_serialization +Odd word problem: + name: Odd word problem + path: Odd-word-problem + url: Odd_word_problem +Old lady swallowed a fly: + name: Old lady swallowed a fly + path: Old-lady-swallowed-a-fly + url: Old_lady_swallowed_a_fly One of n lines in a file: name: One of n lines in a file path: One-of-n-lines-in-a-file @@ -1564,6 +1792,10 @@ Optional parameters: name: Optional parameters path: Optional-parameters url: Optional_parameters +Order disjoint list items: + name: Order disjoint list items + path: Order-disjoint-list-items + url: Order_disjoint_list_items Order two numerical lists: name: Order two numerical lists path: Order-two-numerical-lists @@ -1584,6 +1816,10 @@ Pangram checker: name: Pangram checker path: Pangram-checker url: Pangram_checker +Paraffins: + name: Paraffins + path: Paraffins + url: Paraffins Parallel calculations: name: Parallel calculations path: Parallel-calculations @@ -1596,6 +1832,10 @@ Parametrized SQL statement: name: Parametrized SQL statement path: Parametrized-SQL-statement url: Parametrized_SQL_statement +Parse an IP Address: + name: Parse an IP Address + path: Parse-an-IP-Address + url: Parse_an_IP_Address Parsing/RPN calculator algorithm: name: Parsing/RPN calculator algorithm path: Parsing-RPN-calculator-algorithm @@ -1624,10 +1864,30 @@ Pattern matching: name: Pattern matching path: Pattern-matching url: Pattern_matching +Penney's game: + name: Penney's game + path: Penneys-game + url: Penney's_game Percentage difference between images: name: Percentage difference between images path: Percentage-difference-between-images url: Percentage_difference_between_images +Percolation/Bond percolation: + name: Percolation/Bond percolation + path: Percolation-Bond-percolation + url: Percolation/Bond_percolation +Percolation/Mean cluster density: + name: Percolation/Mean cluster density + path: Percolation-Mean-cluster-density + url: Percolation/Mean_cluster_density +Percolation/Mean run density: + name: Percolation/Mean run density + path: Percolation-Mean-run-density + url: Percolation/Mean_run_density +Percolation/Site percolation: + name: Percolation/Site percolation + path: Percolation-Site-percolation + url: Percolation/Site_percolation Perfect numbers: name: Perfect numbers path: Perfect-numbers @@ -1648,6 +1908,18 @@ Permutations/Derangements: name: Permutations/Derangements path: Permutations-Derangements url: Permutations/Derangements +Permutations/Rank of a permutation: + name: Permutations/Rank of a permutation + path: Permutations-Rank-of-a-permutation + url: Permutations/Rank_of_a_permutation +Pernicious numbers: + name: Pernicious numbers + path: Pernicious-numbers + url: Pernicious_numbers +Phrase reversals: + name: Phrase reversals + path: Phrase-reversals + url: Phrase_reversals Pi: name: Pi path: Pi @@ -1764,6 +2036,10 @@ Queue/Usage: name: Queue/Usage path: Queue-Usage url: Queue/Usage +Quickselect algorithm: + name: Quickselect algorithm + path: Quickselect-algorithm + url: Quickselect_algorithm Quine: name: Quine path: Quine @@ -1776,6 +2052,10 @@ RIPEMD-160: name: RIPEMD-160 path: RIPEMD-160 url: RIPEMD-160 +RSA code: + name: RSA code + path: RSA-code + url: RSA_code Random number generator (device): name: Random number generator (device) path: Random-number-generator--device- @@ -1796,6 +2076,10 @@ Range extraction: name: Range extraction path: Range-extraction url: Range_extraction +Ranking methods: + name: Ranking methods + path: Ranking-methods + url: Ranking_methods Rate counter: name: Rate counter path: Rate-counter @@ -1852,6 +2136,10 @@ Rendezvous: name: Rendezvous path: Rendezvous url: Rendezvous +Rep-string: + name: Rep-string + path: Rep-string + url: Rep-string Repeat a string: name: Repeat a string path: Repeat-a-string @@ -1872,6 +2160,10 @@ Reverse a string: name: Reverse a string path: Reverse-a-string url: Reverse_a_string +Reverse words in a string: + name: Reverse words in a string + path: Reverse-words-in-a-string + url: Reverse_words_in_a_string Rock-paper-scissors: name: Rock-paper-scissors path: Rock-paper-scissors @@ -1896,22 +2188,6 @@ Roots of unity: name: Roots of unity path: Roots-of-unity url: Roots_of_unity -Rosetta Code/Count examples: - name: Rosetta Code/Count examples - path: Rosetta-Code-Count-examples - url: Rosetta_Code/Count_examples -Rosetta Code/Find unimplemented tasks: - name: Rosetta Code/Find unimplemented tasks - path: Rosetta-Code-Find-unimplemented-tasks - url: Rosetta_Code/Find_unimplemented_tasks -Rosetta Code/Fix code tags: - name: Rosetta Code/Fix code tags - path: Rosetta-Code-Fix-code-tags - url: Rosetta_Code/Fix_code_tags -Rosetta Code/Rank languages by popularity: - name: Rosetta Code/Rank languages by popularity - path: Rosetta-Code-Rank-languages-by-popularity - url: Rosetta_Code/Rank_languages_by_popularity Rot-13: name: Rot-13 path: Rot-13 @@ -1920,6 +2196,10 @@ Run-length encoding: name: Run-length encoding path: Run-length-encoding url: Run-length_encoding +Runge-Kutta method: + name: Runge-Kutta method + path: Runge-Kutta-method + url: Runge-Kutta_method Runtime evaluation: name: Runtime evaluation path: Runtime-evaluation @@ -1984,6 +2264,10 @@ Self-referential sequence: name: Self-referential sequence path: Self-referential-sequence url: Self-referential_sequence +Semiprime: + name: Semiprime + path: Semiprime + url: Semiprime Semordnilap: name: Semordnilap path: Semordnilap @@ -2000,6 +2284,10 @@ Sequence of non-squares: name: Sequence of non-squares path: Sequence-of-non-squares url: Sequence_of_non-squares +Sequence of primes by Trial Division: + name: Sequence of primes by Trial Division + path: Sequence-of-primes-by-Trial-Division + url: Sequence_of_primes_by_Trial_Division Set: name: Set path: Set @@ -2096,6 +2384,22 @@ Solve a Hidato puzzle: name: Solve a Hidato puzzle path: Solve-a-Hidato-puzzle url: Solve_a_Hidato_puzzle +Solve a Holy Knight's tour: + name: Solve a Holy Knight's tour + path: Solve-a-Holy-Knights-tour + url: Solve_a_Holy_Knight's_tour +Solve a Hopido puzzle: + name: Solve a Hopido puzzle + path: Solve-a-Hopido-puzzle + url: Solve_a_Hopido_puzzle +Solve a Numbrix puzzle: + name: Solve a Numbrix puzzle + path: Solve-a-Numbrix-puzzle + url: Solve_a_Numbrix_puzzle +Solve the no connection puzzle: + name: Solve the no connection puzzle + path: Solve-the-no-connection-puzzle + url: Solve_the_no_connection_puzzle Sort an array of composite structures: name: Sort an array of composite structures path: Sort-an-array-of-composite-structures @@ -2196,6 +2500,10 @@ Soundex: name: Soundex path: Soundex url: Soundex +Sparkline in unicode: + name: Sparkline in unicode + path: Sparkline-in-unicode + url: Sparkline_in_unicode Special characters: name: Special characters path: Special-characters @@ -2236,10 +2544,26 @@ Start from a main routine: name: Start from a main routine path: Start-from-a-main-routine url: Start_from_a_main_routine +State name puzzle: + name: State name puzzle + path: State-name-puzzle + url: State_name_puzzle +Statistics/Basic: + name: Statistics/Basic + path: Statistics-Basic + url: Statistics/Basic Stem-and-leaf plot: name: Stem-and-leaf plot path: Stem-and-leaf-plot url: Stem-and-leaf_plot +Stern-Brocot sequence: + name: Stern-Brocot sequence + path: Stern-Brocot-sequence + url: Stern-Brocot_sequence +String append: + name: String append + path: String-append + url: String_append String case: name: String case path: String-case @@ -2260,6 +2584,14 @@ String length: name: String length path: String-length url: String_length +String matching: + name: String matching + path: String-matching + url: String_matching +String prepend: + name: String prepend + path: String-prepend + url: String_prepend Strip a set of characters from a string: name: Strip a set of characters from a string path: Strip-a-set-of-characters-from-a-string @@ -2304,6 +2636,10 @@ Sum digits of an integer: name: Sum digits of an integer path: Sum-digits-of-an-integer url: Sum_digits_of_an_integer +Sum multiples of 3 and 5: + name: Sum multiples of 3 and 5 + path: Sum-multiples-of-3-and-5 + url: Sum_multiples_of_3_and_5 Sum of a series: name: Sum of a series path: Sum-of-a-series @@ -2408,6 +2744,18 @@ Text processing/Max licenses in use: name: Text processing/Max licenses in use path: Text-processing-Max-licenses-in-use url: Text_processing/Max_licenses_in_use +Textonyms: + name: Textonyms + path: Textonyms + url: Textonyms +The ISAAC Cipher: + name: The ISAAC Cipher + path: The-ISAAC-Cipher + url: The_ISAAC_Cipher +The Twelve Days of Christmas: + name: The Twelve Days of Christmas + path: The-Twelve-Days-of-Christmas + url: The_Twelve_Days_of_Christmas Thiele's interpolation formula: name: Thiele's interpolation formula path: Thieles-interpolation-formula @@ -2440,6 +2788,10 @@ Topswops: name: Topswops path: Topswops url: Topswops +Total circles area: + name: Total circles area + path: Total-circles-area + url: Total_circles_area Towers of Hanoi: name: Towers of Hanoi path: Towers-of-Hanoi @@ -2476,6 +2828,10 @@ URL encoding: name: URL encoding path: URL-encoding url: URL_encoding +Ulam spiral (for primes): + name: Ulam spiral (for primes) + path: Ulam-spiral--for-primes- + url: Ulam_spiral_(for_primes) Unbias a random generator: name: Unbias a random generator path: Unbias-a-random-generator @@ -2496,6 +2852,10 @@ Universal Turing machine: name: Universal Turing machine path: Universal-Turing-machine url: Universal_Turing_machine +Unix/ls: + name: Unix/ls + path: Unix-ls + url: Unix/ls Update a configuration file: name: Update a configuration file path: Update-a-configuration-file @@ -2568,6 +2928,10 @@ Visualize a tree: name: Visualize a tree path: Visualize-a-tree url: Visualize_a_tree +Vogel's approximation method: + name: Vogel's approximation method + path: Vogels-approximation-method + url: Vogel's_approximation_method Voronoi diagram: name: Voronoi diagram path: Voronoi-diagram @@ -2604,6 +2968,10 @@ Word wrap: name: Word wrap path: Word-wrap url: Word_wrap +World Cup group stage: + name: World Cup group stage + path: World-Cup-group-stage + url: World_Cup_group_stage Write float arrays to a text file: name: Write float arrays to a text file path: Write-float-arrays-to-a-text-file @@ -2660,6 +3028,14 @@ Zeckendorf number representation: name: Zeckendorf number representation path: Zeckendorf-number-representation url: Zeckendorf_number_representation +Zero to the zero power: + name: Zero to the zero power + path: Zero-to-the-zero-power + url: Zero_to_the_zero_power +Zhang-Suen thinning algorithm: + name: Zhang-Suen thinning algorithm + path: Zhang-Suen-thinning-algorithm + url: Zhang-Suen_thinning_algorithm Zig-zag matrix: name: Zig-zag matrix path: Zig-zag-matrix diff --git a/Task/9-billion-names-of-God-the-integer/00DESCRIPTION b/Task/9-billion-names-of-God-the-integer/00DESCRIPTION new file mode 100644 index 0000000000..650f143d7d --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/00DESCRIPTION @@ -0,0 +1,28 @@ +This task is a variation of the [[wp:The Nine Billion Names of God#Plot_summary|short story by Arthur C. Clarke]]. +(Solvers should be aware of the consequences of completing this task.) +In detail, to specify what is meant by a “name”: +:The integer 1 has 1 name “1”. +:The integer 2 has 2 names “1+1”, and “2”. +:The integer 3 has 3 names “1+1+1”, “2+1”, and “3”. +:The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”. +:The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”. + +;Task +The task is to display the first 25 rows of a number triangle which begins: +
+                                      1
+                                    1   1
+                                  1   1   1
+                                1   2   1   1
+                              1   2   2   1   1
+                            1   3   3   2   1   1
+
+ +Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names begining with C. + +A function G(n) should return the sum of the n-th row. Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). +Optionally note that the sum of the n-th row P(n) is the [http://mathworld.wolfram.com/PartitionFunctionP.html integer partition function]. Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345). + +;Extra credit + +If your environment is able, plot P(n) against n for n=1\ldots 999. diff --git a/Task/9-billion-names-of-God-the-integer/AutoHotkey/9-billion-names-of-god-the-integer.ahk b/Task/9-billion-names-of-God-the-integer/AutoHotkey/9-billion-names-of-god-the-integer.ahk new file mode 100644 index 0000000000..cba3fdcd19 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/AutoHotkey/9-billion-names-of-god-the-integer.ahk @@ -0,0 +1,58 @@ +SetBatchLines -1 + +InputBox, Enter_value, Enter the no. of lines sought +array := [] +Loop, % 2*Enter_value - 1 + Loop, % x := A_Index + y := A_Index, Array[x, y] := 1 + +x := 3 + +Loop +{ + base_r := x - 1 + , x++ + , y := 2 + , index := x + , new := 1 + + Loop, % base_r - 1 + { + array[x, new+1] := array[x-1, new] + array[base_r, y] + , x++ + , new ++ + , y++ + } + x := index + If ( mod(x,2) = 0 ) + { + to_run := floor(x - x/2) + , y2 := to_run + 1 + } + Else + { + to_run := x - floor(x/2) + , y2 := to_run + } + Loop, % to_run + { + array[x, y2] := array[x-1, y2-1] + , y2++ + If ( y2 = Enter_value + 1 ) && ( x = Enter_value ) + { + Loop, % Enter_value + { + Loop, % x11 := A_Index + { + y11 := A_Index + , string2 .= " " array[x11, y11] + } + string2 .= "`n" + } + MsgBox % string2 + ExitApp + } + } +} + +~Esc::ExitApp diff --git a/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-1.cpp b/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-1.cpp new file mode 100644 index 0000000000..067a36adf2 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-1.cpp @@ -0,0 +1,8 @@ +// Calculate hypotenuse n of OTT assuming only nothingness, unity, and hyp[n-1] if n>1 +// Nigel Galloway, May 6th., 2013 +#include +int N{123456}; +mpz_class hyp[N-3]; +const mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];}; +void G_hyp(const int n){for(int i=0;i +#include +int main(){ + N=25; + for (int n=1; n0; g--) { + std::string t{hyp[g-1].get_str()}; + t.append(6-t.size(),' '); + std::cout << t; + } + std::cout << "1 1" << std::endl; + } diff --git a/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-4.cpp b/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-4.cpp new file mode 100644 index 0000000000..8eba2fe225 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/C++/9-billion-names-of-god-the-integer-4.cpp @@ -0,0 +1,11 @@ +#include +int main(){ + for (int n=1; n r[i + 1] - r[i]); +} + +void main() { + writeln("Rows:"); + foreach (x; 1 .. 11) + writefln("%2d: %s", x, x.row); + + writeln("\nSums:"); + foreach (x; [23, 123, 1234]) + writeln(x, " ", x.cumu.back); +} diff --git a/Task/9-billion-names-of-God-the-integer/D/9-billion-names-of-god-the-integer-2.d b/Task/9-billion-names-of-God-the-integer/D/9-billion-names-of-god-the-integer-2.d new file mode 100644 index 0000000000..7c131ac142 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/D/9-billion-names-of-god-the-integer-2.d @@ -0,0 +1,51 @@ +import std.stdio, std.bigint, std.algorithm; + +struct Names { + BigInt[] p = [1.BigInt]; + + int opApply(int delegate(ref immutable int, ref BigInt) dg) { + int result; + + foreach (immutable n; 1 .. int.max) { + p.assumeSafeAppend; + p ~= 0.BigInt; + + foreach (immutable k; 1 .. n + 1) { + auto d = n - k * (3 * k - 1) / 2; + if (d < 0) + break; + + if (k & 1) + p[n] += p[d]; + else + p[n] -= p[d]; + + d -= k; + if (d < 0) + break; + + if (k & 1) + p[n] += p[d]; + else + p[n] -= p[d]; + } + + result = dg(n, p[n]); + if (result) break; + } + + return result; + } +} + +void main() { + immutable ns = [23:0, 123:0, 1234:0, 12345:0]; + immutable maxNs = ns.byKey.reduce!max; + + foreach (immutable i, p; Names()) { + if (i > maxNs) + break; + if (i in ns) + writefln("%6d: %s", i, p); + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl b/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl new file mode 100644 index 0000000000..1280760e09 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Erlang/9-billion-names-of-god-the-integer.erl @@ -0,0 +1,29 @@ +-module(god_the_integer). +-export([example/0, names/1, print_pyramid/1]). + +example() -> + Names = names( 10 ), + print_pyramid( Names ). + +names( N ) -> + [names_row(X) || X <- lists:seq(1, N)]. + +print_pyramid( Names ) -> + Width = erlang:length( lists:last(Names) ), + [print_pyramid_row(Width, X) || X <- Names]. + + + +names_row( M ) -> + [p(M, X) || X <- lists:seq(1, M)]. + +p( N, K ) when K > N -> 0; +p( N, N ) -> 1; +p( _N, 0 ) -> 0; +p( N, K ) -> + p( N - 1, K - 1 ) + p( N - K, K ). + +print_pyramid_row( Width, Row ) -> + io:fwrite( "~*s", [Width - erlang:length(Row), " "] ), + [io:fwrite("~p ", [X]) || X <- Row], + io:nl(). diff --git a/Task/9-billion-names-of-God-the-integer/Frink/9-billion-names-of-god-the-integer.frink b/Task/9-billion-names-of-God-the-integer/Frink/9-billion-names-of-god-the-integer.frink new file mode 100644 index 0000000000..bcaf96eb10 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Frink/9-billion-names-of-god-the-integer.frink @@ -0,0 +1,54 @@ +class PartitionCount +{ + // Array of elements + class var triangle = [[0],[0,1]] + + // Array of cumulative sums in each row. + class var sumTriangle = [[1],[0,1]] + + class calcRowsTo[toRow] := + { + for row = length[triangle] to toRow + { + triangle@row = workrow = new array[[row+1],0] + sumTriangle@row = sumworkrow = new array[[row+1],0] + oversum = 0 + for col = 1 to row + { + otherRow = row-col + sum = sumTriangle@otherRow@min[col,otherRow] + workrow@col = sum + oversum = oversum + sum + sumworkrow@col = oversum + } + } + } + + class rowSum[row] := + { + calcRowsTo[row] + return sumTriangle@row@row + } +} + +PartitionCount.calcRowsTo[25] +for row=1 to 25 +{ + for col=1 to row + print[PartitionCount.triangle@row@col + " "] + println[] +} + +// Test against Frink's built-in much faster partitionCount function that uses +// Euler's pentagonal method for counting partitions. +testRow[row] := +{ + sum = PartitionCount.rowSum[row] + println["$row\t$sum\t" + (sum == partitionCount[row] ? "correct" : "incorrect")] +} + +println[] +testRow[23] +testRow[123] +testRow[1234] +testRow[12345] diff --git a/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-1.hs b/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-1.hs new file mode 100644 index 0000000000..ddca799a9f --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-1.hs @@ -0,0 +1,21 @@ +import Data.List (mapAccumL) + +cumu :: [[Integer]] +cumu = [1] : map (scanl (+) 0) rows + +rows :: [[Integer]] +rows = snd $ mapAccumL f [] cumu where + f r row = (rr, new_row) where + new_row = map head rr + rr = map tailKeepOne (row:r) + tailKeepOne [x] = [x] + tailKeepOne (_:xs) = xs + +sums n = cumu !! n !! n +--curiously, the following seems to be faster +--sums = sum . (rows!!) + +main :: IO () +main = do + mapM_ print $ take 10 rows + mapM_ (print.sums) [23, 123, 1234, 12345] diff --git a/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-2.hs b/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-2.hs new file mode 100644 index 0000000000..0f9af6f747 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Haskell/9-billion-names-of-god-the-integer-2.hs @@ -0,0 +1,25 @@ +procedure main(A) + n := integer(!A) | 10 + every r := 2 to (n+1) do write(right(r-1,2),": ",showList(row(r))) + write() + every r := 23 | 123 | 1234 | 12345 do write(r," ",cumu(r+1)[-1]) +end + +procedure cumu(n) + static cache + initial cache := [[1]] + every l := *cache to n do { + every (r := [0], x := !l) do put(r, r[-1]+cache[1+l-x][1+min(x,l-x)]) + put(cache, r) + } + return cache[n] +end + +procedure row(n) + return (r := cumu(n), [: (i := !(*r-1), r[i+1]-r[i]) :]) | r +end + +procedure showList(A) + every (s := "[") ||:= (!A||", ") + return s[1:-2]||"]" +end diff --git a/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-1.j b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-1.j new file mode 100644 index 0000000000..7b4d94e1c5 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-1.j @@ -0,0 +1 @@ +T=: 0:`1:`(($:&<:+ - $: ])`0:@.(0=]))@.(1+*@-) M. "0 diff --git a/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-2.j b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-2.j new file mode 100644 index 0000000000..43234b5e39 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-2.j @@ -0,0 +1 @@ +rows=: <@(#~0<])@({: T ])\@i. diff --git a/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-3.j b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-3.j new file mode 100644 index 0000000000..4975b99af3 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-3.j @@ -0,0 +1,11 @@ + ({.~1+1 i:~ '1'=])"1 ":> }.rows 1+10 +1 +1 1 +1 1 1 +1 2 1 1 +1 2 2 1 1 +1 3 3 2 1 1 +1 3 4 3 2 1 1 +1 4 5 5 3 2 1 1 +1 4 7 6 5 3 2 1 1 +1 5 8 9 7 5 3 2 1 1 diff --git a/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-4.j b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-4.j new file mode 100644 index 0000000000..b2c645086a --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/J/9-billion-names-of-god-the-integer-4.j @@ -0,0 +1,11 @@ +rowSums=: 3 :0"0 +z=. (y+1){. 1x +for_ks. <\1+i.y do. + n=.{: k=.>ks + r=.#c=. ({.~* i._1:)(n,0.5 _1.5) p. k + s=.#d=.({.~* i._1:)c-r{.k + 'v i'=.|: \:~(c,d),. r ,&({.&k) s + a=. +/(n{z),(_1^1x+2|i) * v{z + z=. a n}z +end. +) diff --git a/Task/9-billion-names-of-God-the-integer/JavaScript/9-billion-names-of-god-the-integer.js b/Task/9-billion-names-of-God-the-integer/JavaScript/9-billion-names-of-god-the-integer.js new file mode 100644 index 0000000000..c412aa5402 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/JavaScript/9-billion-names-of-god-the-integer.js @@ -0,0 +1,57 @@ +(function () { + var cache = [ + [1] + ]; +//this was never needed. + /* function PyRange(start, end, step) { + step = step || 1; + if (!end) { + end = start; + start = 0; + } + var arr = []; + for (var i = start; i < end; i += step) arr.push(i); + return arr; + }*/ + + function cumu(n) { + var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this + r, l, x, Aa, Mi; + // for (ll in ra) { too pythony + for (l=cache.length;l All] diff --git a/Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml b/Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml new file mode 100644 index 0000000000..a96b2c8c64 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml @@ -0,0 +1,78 @@ +let get, sum_unto = + let cache = ref [||] + let rec get i j = + if Array.length !cache < i then + cache := + Array.init i begin fun i -> + try !cache.(i) with Invalid_argument _ -> + Array.make (i+1) (Num.num_of_int 0) + end; + if Num.(!cache.(i-1).(j-1) =/ num_of_int 0) + then !cache.(i-1).(j-1) <- sum_unto (i-j) j; + !cache.(i-1).(j-1) + and sum_unto i j = + let rec sum_unto sum i j = + match (i,j) with + |(0,0) -> (Num.num_of_int 1) + |(_,0) -> sum + |(i,j) when j > i -> sum_unto sum i i + |(i,j) -> sum_unto Num.(sum +/ (get i j)) i (j-1) + in + sum_unto (Num.num_of_int 0) i j + in + get, sum_unto + +let sum_of_row n = sum_unto n n + +let euler_recurrence = + let cache = ref [||] in + let rec recurrence = function + |n when n < 0 -> Num.num_of_int 0 + |0 -> Num.num_of_int 1 + |n -> + if n >= Array.length !cache then + cache := + Array.init (n+1) (fun i -> + try !cache.(i) with Invalid_argument _ -> Num.num_of_int 0); + if Num.(!cache.(n) =/ num_of_int 0) + then begin + let rec summing sum = function + |0 -> sum + |k -> + let op = if k mod 2 = 0 then Num.sub_num else Num.add_num in + let sum = op sum (recurrence (n - k * (3*k - 1) / 2)) in + let sum = op sum (recurrence (n - k * (3*k + 1) / 2)) in + summing sum (k-1) + in + !cache.(n) <- summing (Num.num_of_int 0) n + end; + !cache.(n) + in + recurrence + +let print i_max = + for i=1 to i_max do + print_int (i+1); print_string ": "; + for j=1 to i do + print_string (Num.string_of_num (get i j)); + print_char ' '; + done; + print_newline (); + done + +let () = + print 30; + print_newline (); + List.iter begin fun i -> + Printf.printf "%i: %s ?= %s\n" i + (Num.string_of_num (sum_of_row i)) + (Num.string_of_num (euler_recurrence i)); + flush stdout; + end + [23;123;1234;]; + List.iter begin fun i -> + Printf.printf "%i: %s\n" i + (Num.string_of_num (euler_recurrence i)); + flush stdout; + end + [23;123;1234;12345;123456] diff --git a/Task/9-billion-names-of-God-the-integer/Perl-6/9-billion-names-of-god-the-integer.pl6 b/Task/9-billion-names-of-God-the-integer/Perl-6/9-billion-names-of-god-the-integer.pl6 new file mode 100644 index 0000000000..d3b8bd70f4 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Perl-6/9-billion-names-of-god-the-integer.pl6 @@ -0,0 +1,29 @@ +my @todo = [1]; +my @sums = 0; +sub nextrow($n) { + for +@todo .. $n -> $l { + @sums[$l] = 0; + print $l,"\r" if $l < $n; + my $r = []; + for reverse ^$l -> $x { + my @x := @todo[$x]; + if @x { + $r.push: @sums[$x] += @x.shift; + } + else { + $r.push: @sums[$x]; + } + } + @todo.push($r); + } + @todo[$n]; +} + +say "rows:"; +say .fmt('%2d'), ": ", nextrow($_)[] for 1..10; + + +say "\nsums:"; +for 23, 123, 1234, 10000 { + say $_, "\t", [+] nextrow($_)[]; +} diff --git a/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-1.pl b/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-1.pl new file mode 100644 index 0000000000..7dd88ded99 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-1.pl @@ -0,0 +1,12 @@ +use ntheory qw/:all/; + +sub triangle_row { + my($n,@row) = (shift); + # Tally by first element of the unrestricted integer partitions. + forpart { $row[ $_[0] - 1 ]++ } $n; + @row; +} + +printf "%2d: %s\n", $_, join(" ",triangle_row($_)) for 1..25; +print "\n"; +say "P($_) = ", partitions($_) for (23, 123, 1234, 12345); diff --git a/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-2.pl b/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-2.pl new file mode 100644 index 0000000000..614a2ccce5 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Perl/9-billion-names-of-god-the-integer-2.pl @@ -0,0 +1,40 @@ +use strict; +use warnings; + +# Where perl6 uses arbitrary precision integers everywhere +# that you don't tell it not to do so, perl5 will only use +# them where you *do* tell it do so. +use Math::BigInt; +use constant zero => Math::BigInt->bzero; +use constant one => Math::BigInt->bone; + +my @todo = [one]; +my @sums = (zero); +sub nextrow { + my $n = shift; + for my $l (@todo .. $n) { + $sums[$l] = zero; + #print "$l\r" if $l < $n; + my @r; + for my $x (reverse 0 .. $l-1) { + my $todo = $todo[$x]; + $sums[$x] += shift @$todo if @$todo; + push @r, $sums[$x]; + } + push @todo, \@r; + } + @{ $todo[$n] }; +} + +print "rows:\n"; +for(1..25) { + printf("%2d: ", $_); + print join(' ', nextrow($_)), "\n"; +} +print "\nsums:\n"; +for (23, 123, 1234, 12345) { + print $_, "." x (8 - length); + my $i = 0; + $i += $_ for nextrow($_); + print $i, "\n"; +} diff --git a/Task/9-billion-names-of-God-the-integer/PicoLisp/9-billion-names-of-god-the-integer.l b/Task/9-billion-names-of-God-the-integer/PicoLisp/9-billion-names-of-god-the-integer.l new file mode 100644 index 0000000000..46868b544f --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/PicoLisp/9-billion-names-of-god-the-integer.l @@ -0,0 +1,52 @@ +(de row (N) + (let C '((1)) + (do N + (push 'C (grow C)) ) + (mapcon + '((L) + (when (cdr L) + (cons (- (cadr L) (car L))) ) ) + (car C) ) ) ) + +(de grow (Lst) + (let (L (length Lst) S 0) + (cons + 0 + (mapcar + '((I X) + (inc 'S + (get I (inc (min X (- L X)))) ) ) + Lst + (range 1 L) ) ) ) ) + +(de sumr (N) + (let + (K 1 + S 1 + O (cons 1 (need N 0)) + D + (make + (while + (< + (* K (dec (* 3 K))) + (* 2 N) ) + (link (list (dec (* 2 K)) S)) + (link (list K S)) + (inc 'K) + (setq S (- S)) ) ) ) + (for (Y O (cdr Y) (cdr Y)) + (let Z Y + (for L D + (inc + (setq Z (cdr (nth Z (car L)))) + (* (car Y) (cadr L)) ) ) ) ) + (last O) ) ) + +(for I 25 + (println (row I)) ) + +(bench + (for I '(23 123 1234 12345) + (println (sumr I)) ) ) + +(bye) diff --git a/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-1.py b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-1.py new file mode 100644 index 0000000000..9fff750582 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-1.py @@ -0,0 +1,19 @@ +cache = [[1]] +def cumu(n): + for l in range(len(cache), n+1): + r = [0] + for x in range(1, l+1): + r.append(r[-1] + cache[l-x][min(x, l-x)]) + cache.append(r) + return cache[n] + +def row(n): + r = cumu(n) + return [r[i+1] - r[i] for i in range(n)] + +print "rows:" +for x in range(1, 11): print "%2d:"%x, row(x) + + +print "\nsums:" +for x in [23, 123, 1234, 12345]: print x, cumu(x)[-1] diff --git a/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-2.py b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-2.py new file mode 100644 index 0000000000..af4209c290 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-2.py @@ -0,0 +1,18 @@ +def partitions(N): + diffs,k,s = [],1,1 + while k * (3*k-1) < 2*N: + diffs.extend([(2*k - 1, s), (k, s)]) + k,s = k+1,-s + + out = [1] + [0]*N + for p in range(0, N+1): + x = out[p] + for (o,s) in diffs: + p += o + if p > N: break + out[p] += x*s + + return out + +p = partitions(12345) +for x in [23,123,1234,12345]: print x, p[x] diff --git a/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-3.py b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-3.py new file mode 100644 index 0000000000..1a67ccd4ab --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Python/9-billion-names-of-god-the-integer-3.py @@ -0,0 +1,38 @@ +def partitions(n): + partitions.p.append(0) + + for k in xrange(1, n + 1): + d = n - k * (3 * k - 1) // 2 + if d < 0: + break + + if k & 1: + partitions.p[n] += partitions.p[d] + else: + partitions.p[n] -= partitions.p[d] + + d -= k + if d < 0: + break + + if k & 1: + partitions.p[n] += partitions.p[d] + else: + partitions.p[n] -= partitions.p[d] + + return partitions.p[-1] + +partitions.p = [1] + +def main(): + ns = set([23, 123, 1234, 12345]) + max_ns = max(ns) + + for i in xrange(1, max_ns + 1): + if i > max_ns: + break + p = partitions(i) + if i in ns: + print "%6d: %s" % (i, p) + +main() diff --git a/Task/9-billion-names-of-God-the-integer/README b/Task/9-billion-names-of-God-the-integer/README new file mode 100644 index 0000000000..579a09b686 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/9_billion_names_of_God_the_integer diff --git a/Task/9-billion-names-of-God-the-integer/REXX/9-billion-names-of-god-the-integer.rexx b/Task/9-billion-names-of-God-the-integer/REXX/9-billion-names-of-god-the-integer.rexx new file mode 100644 index 0000000000..b953b64d23 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/REXX/9-billion-names-of-god-the-integer.rexx @@ -0,0 +1,52 @@ +/*REXX program generates a number triangle for partitions of a number.*/ +numeric digits 400 /*be able to handle large numbers*/ +parse arg N .; if N=='' then N=25 /*No input? Then use the default*/ +@.=0; @.0=1; aN=abs(N) +if N==N+0 then say ' G('aN"):" G(N) /*just for well formed #s*/ + say 'partitions('aN"):" partitions(aN) /*the easy way*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────G subroutine────────────────────────*/ +G: procedure; parse arg nn; !.=0; mx=1; aN=abs(nn); build=nn>0 +!.4.2=2; do j=1 for aN%2; !.j.j=1; end /*j*/ /*shortcuts.*/ + + do t=1 for 1+build; #.=1 /*gen triangle once or twice ∙∙∙*/ + do r=1 for aN; #.2=r%2 /*#.2 is a shortcut calc.*/ + do c=3 to r-2; #.c=gen#(r,c); end /*c*/ + L=length(mx); p=0; aLine= + do cc=1 for r /*only sum last row of numbers. */ + p=p+#.cc /*add last row of the triangle. */ + if \build then iterate /*skip building the triangle? */ + mx=max(mx,#.cc) /*used to build symmetric numbers*/ + aLine=aLine right(#.cc,L) /*build a row of the triangle. */ + end /*cc*/ + if t==1 then iterate /*Is first time through? No show*/ + L=length(mx); say centre(strip(aLine,'L'), 2+(aN-1)*(L+1)) + end /*r*/ /* [↑] centre the row (triangle).*/ + end /*t*/ +return p /*return with generated number. */ +/*──────────────────────────────────GEN# subroutine─────────────────────*/ +gen#: procedure expose !.; parse arg x,y /*obtain X and Y arguments.*/ +if !.x.y\==0 then return !.x.y /*was this # generated before? */ +if y>x%2 then do; nx=x+1-2*(y-x%2)-(x//2==0); ny=nx%2; !.x.y=!.nx.ny + return !.x.y /*return with the calculated num.*/ + end /*[↑] right half of the triangle.*/ +$=1 /*[↓] left half of the triangle.*/ + do q=2 to y; xy=x-y; if q>xy then iterate + if q==2 then $=$+xy%2 + else if q==xy-1 then $=$+1 + else $=$+gen#(xy,q) + end /*q*/ +!.x.y=$; return $ /*remember #, return with number.*/ +/*──────────────────────────────────PARTITIONS subroutine───────────────*/ +partitions: procedure expose @.; parse arg n +if @.n\==0 then return @.n /*Already computed? Return it. */ +$=0 /*[↓] Euler's recursive function.*/ + do k=1 for n; _=n-(k*3-1)*k%2; if _<0 then leave + if @._==0 then x=partitions(_); else x=@._ + _=_-k; if _<0 then y=0 + else if @._==0 then y=partitions(_) + else y=@._ + if k//2 then $=$+x+y /*sum this way if K is odd ···*/ + else $=$-x-y /* " " " " " " even ···*/ + end /*k*/ +@.n=$; return $ diff --git a/Task/9-billion-names-of-God-the-integer/Racket/9-billion-names-of-god-the-integer.rkt b/Task/9-billion-names-of-God-the-integer/Racket/9-billion-names-of-god-the-integer.rkt new file mode 100644 index 0000000000..1c9adfe4c0 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Racket/9-billion-names-of-god-the-integer.rkt @@ -0,0 +1,23 @@ +#lang racket + +(define (cdr-empty ls) (if (empty? ls) empty (cdr ls))) + +(define (names-of n) + (define (names-of-tail ans raws-rest n) + (if (zero? n) + ans + (names-of-tail (cons 1 (append (map + + (take ans (length raws-rest)) + (map car raws-rest)) + (drop ans (length raws-rest)))) + (filter (compose not empty?) + (map cdr-empty (cons ans raws-rest))) + (sub1 n)))) + (names-of-tail '() '() n)) + +(define (G n) (foldl + 0 (names-of n))) + +(module+ main + (build-list 25 (compose names-of add1)) + (newline) + (map G '(23 123 1234))) diff --git a/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-1.rb b/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-1.rb new file mode 100644 index 0000000000..5505c75695 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-1.rb @@ -0,0 +1,10 @@ +# Generate IPF triangle +# Nigel_Galloway: May 1st., 2013. +def g(n,g) + return 1 unless 1 < g and g < n-1 + (2..g).inject(1){|res,q| res + (q > n-g ? 0 : g(n-g,q))} +end + +(1..25).each {|n| + puts (1..n).map {|g| "%4s" % g(n,g)}.join +} diff --git a/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-2.rb b/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-2.rb new file mode 100644 index 0000000000..bf22f880f4 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Ruby/9-billion-names-of-god-the-integer-2.rb @@ -0,0 +1,30 @@ +# Find large values of IPF +# Nigel_Galloway: May 1st., 2013. +N = 12345 +@ng = [] +@ipn1 = [] +@ipn2 = [] +def g(n,g) + t = n-g-2 + return 1 if n<4 or t<0 + return @ng[g-2][n-4] unless n/2 B) extends (A => B) { + private val cache = Map.empty[A, B] + def apply(x: A) = cache getOrElseUpdate (x, f(x)) + } + + // Naive, but memoized solution + lazy val namesStartingMemo : Memo[Tuple2[Int, Int], BigInt] = Memo { + case (1, 1) => 1 + case (a, n) => + if (a > n/2) namesStartingMemo(a - 1, n - 1) + else if (n < a) 0 + else if (n == a) 1 + else (1 to a).map(i => namesStartingMemo(i, n - a)).sum + + } + + def partitions(n: Int) = (1 to n).map(namesStartingMemo(_, n)).sum + + // main method + def main(args: Array[String]): Unit = { + for (i <- 1 to 25) { + for (j <- 1 to i) { + print(namesStartingMemo(j, i)); + print(' '); + } + println() + } + println(partitions(23)) + println(partitions(123)) + println(partitions(1234)) + println(partitions(12345)) + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Scala/9-billion-names-of-god-the-integer-2.scala b/Task/9-billion-names-of-God-the-integer/Scala/9-billion-names-of-god-the-integer-2.scala new file mode 100644 index 0000000000..0ce4eb0f89 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Scala/9-billion-names-of-god-the-integer-2.scala @@ -0,0 +1,49 @@ +val cache = new Array[BigInt](15000) +cache(0) = 1 +val cacheNaive = scala.collection.mutable.Map[Tuple2[Int, Int], BigInt]() + +def p(n: Int, k: Int): BigInt = cacheNaive.getOrElseUpdate((n, k), (n, k) match { + case (n, 1) => 1 + case (n, k) if n < k => 0 + case (n, k) if n == k => 1 + case (n, k) => + if (k > n/2) p(n - 1, k - 1) + else p(n - 1, k - 1) + p(n - k, k) +}) + +def partitions(n: Int) = (1 to n).map(p(n, _)).sum + +def updateCache(n: Int, d: Int, k: Int) = + if ((k & 1) == 1) cache(n) = cache(n) + cache(d) + else cache(n) = cache(n) - cache(d) + +def quickPartitions(n: Int): BigInt = { + cache(n) = 0 + for (k <- 1 to n) { + val d = n - k * (3 * k - 1) / 2 + if (d >= 0) { + updateCache(n, d, k) + + val e = d - k + if (e >= 0) { + updateCache(n, e, k) + } + } + } + cache(n) +} + +for (i <- 1 to 23) { + for (j <- 1 to i) { + print(f"${p(i, j)}%4d") + } + println +} +println(partitions(23)) + +for (i <- 1 until cache.length) { + quickPartitions(i) +} +println(quickPartitions(123)) +println(quickPartitions(1234)) +println(quickPartitions(12345)) diff --git a/Task/9-billion-names-of-God-the-integer/Tcl/9-billion-names-of-god-the-integer.tcl b/Task/9-billion-names-of-God-the-integer/Tcl/9-billion-names-of-god-the-integer.tcl new file mode 100644 index 0000000000..8b53dde153 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Tcl/9-billion-names-of-god-the-integer.tcl @@ -0,0 +1,30 @@ +set cache 1 +proc cumu {n} { + global cache + for {set l [llength $cache]} {$l <= $n} {incr l} { + set r 0 + for {set x 1; set y [expr {$l-1}]} {$y >= 0} {incr x; incr y -1} { + lappend r [expr { + [lindex $r end] + [lindex $cache $y [expr {min($x, $y)}]] + }] + } + lappend cache $r + } + return [lindex $cache $n] +} +proc row {n} { + set r [cumu $n] + for {set i 0; set j 1} {$j < [llength $r]} {incr i; incr j} { + lappend result [expr {[lindex $r $j] - [lindex $r $i]}] + } + return $result +} + +puts "rows:" +foreach x {1 2 3 4 5 6 7 8 9 10} { + puts "${x}: \[[join [row $x] {, }]\]" +} +puts "\nsums:" +foreach x {23 123 1234 12345} { + puts "${x}: [lindex [cumu $x] end]" +} diff --git a/Task/ABC-Problem/00DESCRIPTION b/Task/ABC-Problem/00DESCRIPTION new file mode 100644 index 0000000000..13624d5561 --- /dev/null +++ b/Task/ABC-Problem/00DESCRIPTION @@ -0,0 +1,48 @@ +You are given a collection of ABC blocks. Just like the ones you had when you were a kid. There are twenty blocks with two letters on each block. You are guaranteed to have a complete alphabet amongst all sides of the blocks. The sample blocks are: + +:((B O) +: (X K) +: (D Q) +: (C P) +: (N A) +: (G T) +: (R E) +: (T G) +: (Q D) +: (F S) +: (J W) +: (H U) +: (V I) +: (A N) +: (O B) +: (E R) +: (F S) +: (L Y) +: (P C) +: (Z M)) + +The goal of this task is to write a function that takes a string and can determine whether you can spell the word with the given collection of blocks. +The rules are simple: + +#Once a letter on a block is used that block cannot be used again +#The function should be case-insensitive +# Show your output on this page for the following words: + +;Example: + + + >>> can_make_word("A") + True + >>> can_make_word("BARK") + True + >>> can_make_word("BOOK") + False + >>> can_make_word("TREAT") + True + >>> can_make_word("COMMON") + False + >>> can_make_word("SQUAD") + True + >>> can_make_word("CONFUSE") + True + diff --git a/Task/ABC-Problem/Ada/abc-problem.ada b/Task/ABC-Problem/Ada/abc-problem.ada new file mode 100644 index 0000000000..28ac345566 --- /dev/null +++ b/Task/ABC-Problem/Ada/abc-problem.ada @@ -0,0 +1,78 @@ +with Ada.Characters.Handling; +use Ada.Characters.Handling; + + +package Abc is + type Block_Faces is array(1..2) of Character; + type Block_List is array(positive range <>) of Block_Faces; + function Can_Make_Word(W: String; Blocks: Block_List) return Boolean; +end Abc; + + +package body Abc is + +function Can_Make_Word(W: String; Blocks: Block_List) return Boolean is + Used : array(Blocks'Range) of Boolean := (Others => False); + subtype wIndex is Integer range W'First..W'Last; + wPos : wIndex; +begin + if W'Length = 0 then + return True; + end if; + wPos := W'First; + while True loop + declare + C : Character := To_Upper(W(wPos)); + X : constant wIndex := wPos; + begin + for I in Blocks'Range loop + if (not Used(I)) then + if C = To_Upper(Blocks(I)(1)) or C = To_Upper(Blocks(I)(2)) then + Used(I) := True; + if wPos = W'Last then + return True; + end if; + wPos := wIndex'Succ(wPos); + exit; + end if; + end if; + end loop; + if X = wPos then + return False; + end if; + end; + end loop; + return False; +end Can_Make_Word; + +end Abc; + +with Ada.Text_IO, Ada.Strings.Unbounded, Abc; +use Ada.Text_IO, Ada.Strings.Unbounded, Abc; + +procedure Abc_Problem is + Blocks : Block_List := ( + ('B','O'), ('X','K'), ('D','Q'), ('C','P') + , ('N','A'), ('G','T'), ('R','E'), ('T','G') + , ('Q','D'), ('F','S'), ('J','W'), ('H','U') + , ('V','I'), ('A','N'), ('O','B'), ('E','R') + , ('F','S'), ('L','Y'), ('P','C'), ('Z','M') + ); + function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + words : array(positive range <>) of Unbounded_String := ( + +"A" + , +"BARK" + , +"BOOK" + , +"TREAT" + , +"COMMON" + , +"SQUAD" + , +"CONFUSE" + -- Border cases: + -- , +"CONFUSE2" + -- , +"" + ); +begin + for I in words'Range loop + Put_Line ( To_String(words(I)) & ": " & Boolean'Image(Can_Make_Word(To_String(words(I)),Blocks)) ); + end loop; +end Abc_Problem; diff --git a/Task/ABC-Problem/AutoHotkey/abc-problem-1.ahk b/Task/ABC-Problem/AutoHotkey/abc-problem-1.ahk new file mode 100644 index 0000000000..448f692c2b --- /dev/null +++ b/Task/ABC-Problem/AutoHotkey/abc-problem-1.ahk @@ -0,0 +1,24 @@ +isWordPossible(blocks, word){ + o := {} + loop, parse, blocks, `n, `r + o.Insert(A_LoopField) + loop, parse, word + if !(r := isWordPossible_contains(o, A_LoopField, word)) + return 0 + return 1 +} +isWordPossible_contains(byref o, letter, word){ + loop 2 { + for k,v in o + if Instr(v,letter) + { + StringReplace, op, v,% letter + if RegExMatch(op, "[" word "]") + sap := k + else added := 1 , sap := k + if added + return "1" o.remove(sap) + } + added := 1 + } +} diff --git a/Task/ABC-Problem/AutoHotkey/abc-problem-2.ahk b/Task/ABC-Problem/AutoHotkey/abc-problem-2.ahk new file mode 100644 index 0000000000..dff93522ac --- /dev/null +++ b/Task/ABC-Problem/AutoHotkey/abc-problem-2.ahk @@ -0,0 +1,38 @@ +blocks := " +( +BO +XK +DQ +CP +NA +GT +RE +TG +QD +FS +JW +HU +VI +AN +OB +ER +FS +LY +PC +ZM +)" + +wordlist := " +( +A +BARK +BOOK +TREAT +COMMON +SQUAD +CONFUSE +)" + +loop, parse, wordlist, `n + out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n" +msgbox % out diff --git a/Task/ABC-Problem/BBC-BASIC/abc-problem.bbc b/Task/ABC-Problem/BBC-BASIC/abc-problem.bbc new file mode 100644 index 0000000000..cea8d9fb56 --- /dev/null +++ b/Task/ABC-Problem/BBC-BASIC/abc-problem.bbc @@ -0,0 +1,22 @@ + BLOCKS$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" + PROCcan_make_word("A") + PROCcan_make_word("BARK") + PROCcan_make_word("BOOK") + PROCcan_make_word("TREAT") + PROCcan_make_word("COMMON") + PROCcan_make_word("SQUAD") + PROCcan_make_word("Confuse") + END + + DEF PROCcan_make_word(word$) + LOCAL b$,p% + b$=BLOCKS$ + PRINT word$ " -> "; + p%=INSTR(b$,CHR$(ASCword$ AND &DF)) + WHILE p%>0 AND word$>"" + MID$(b$,p%-1+(p% MOD 2),2)=".." + word$=MID$(word$,2) + p%=INSTR(b$,CHR$(ASCword$ AND &DF)) + ENDWHILE + IF word$>"" PRINT "False" ELSE PRINT "True" + ENDPROC diff --git a/Task/ABC-Problem/Batch-File/abc-problem.bat b/Task/ABC-Problem/Batch-File/abc-problem.bat new file mode 100644 index 0000000000..c7420baaec --- /dev/null +++ b/Task/ABC-Problem/Batch-File/abc-problem.bat @@ -0,0 +1,62 @@ +@echo off +::abc.bat +:: +::Batch file to evaluate if a given string can be represented with a set of +::20 2-faced blocks. +:: + +::Check if a string was provided +if "%1"=="" goto ERROR + +::Define blocks. Separate blocks by ':', and terminat with '::' +set "FACES=BO:XK:DQ:CP:NA:GT:RE:TG:QD:FS:JW:HU:VI:AN:OB:ER:FS:LY:PC:ZM::" +set INPUT=%1 +set "COUNTER=0" + +::The main loop steps through the input string, checking if an available +::block exists for each character +:LOOP_MAIN + + ::Get character, increase counter, and test if there are still characters + call set "char=%%INPUT:~%COUNTER%,1%%" + set /a "COUNTER+=1" + if "%CHAR%"=="" goto LOOP_MAIN_END + + set "OFFSET=0" + :LOOP_2 + + ::Read in two characters (one block) + call set "BLOCK=%%FACES%:~%OFFSET%,2%%" + + ::Test if the all blocks were checked. If so, no match was found + if "%BLOCK%"==":" goto FAIL + + ::Test if current input string character is in the current block + if /i "%BLOCK:~0,1%"=="%CHAR%" goto FOUND + if /i "%BLOCK:~1,1%"=="%CHAR%" goto FOUND + + ::Increase offset to point to the next block + set /a "OFFSET+=3" + + goto LOOP_2 + :LOOP_2_END + + ::If found, blank out the block used + :FOUND + call set "FACES=%%FACES:%BLOCK%:= :%%" + +goto LOOP_MAIN +:LOOP_MAIN_END + +echo %0: It is possible to write the '%INPUT%' with my blocks. +goto END + +:FAIL +echo %0: It is NOT possible to write the '%INPUT%' with my blocks. +goto END + +:ERROR +echo %0: Please enter a string to evaluate +echo. + +:END diff --git a/Task/ABC-Problem/Bracmat/abc-problem.bracmat b/Task/ABC-Problem/Bracmat/abc-problem.bracmat new file mode 100644 index 0000000000..ae1666bdc7 --- /dev/null +++ b/Task/ABC-Problem/Bracmat/abc-problem.bracmat @@ -0,0 +1,48 @@ +( + ( can-make-word + = ABC blocks + . (B O) + + (X K) + + (D Q) + + (C P) + + (N A) + + (G T) + + (R E) + + (T G) + + (Q D) + + (F S) + + (J W) + + (H U) + + (V I) + + (A N) + + (O B) + + (E R) + + (F S) + + (L Y) + + (P C) + + (Z M) + : ?blocks + & ( ABC + = letter blocks A Z + . !arg:(.?) + | !arg:(@(?:%?letter ?arg).?blocks) + & !blocks + : ? + + ?*(? !letter ?:?block) + + (?&ABC$(!arg.!blocks+-1*!block)) + ) + & out + $ ( !arg + ( ABC$(upp$!arg.!blocks)&yes + | no + ) + ) + ) +& can-make-word'A +& can-make-word'BARK +& can-make-word'BOOK +& can-make-word'TREAT +& can-make-word'COMMON +& can-make-word'SQUAD +& can-make-word'CONFUSE +); diff --git a/Task/ABC-Problem/C++/abc-problem.cpp b/Task/ABC-Problem/C++/abc-problem.cpp new file mode 100644 index 0000000000..986445dbc9 --- /dev/null +++ b/Task/ABC-Problem/C++/abc-problem.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include + + +typedef std::pair item_t; +typedef std::vector list_t; + +bool can_make_word(const std::string& w, const list_t& vals) { + std::set used; + while (used.size() < w.size()) { + const char c = toupper(w[used.size()]); + uint32_t x = used.size(); + for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) { + if (used.find(i) == used.end()) { + if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) { + used.insert(i); + break; + } + } + } + if (x == used.size()) break; + } + return used.size() == w.size(); +} + + +int main() { + list_t vals{ {'B','O'}, {'X','K'}, {'D','Q'}, {'C','P'}, {'N','A'}, {'G','T'}, {'R','E'}, {'T','G'}, {'Q','D'}, {'F','S'}, {'J','W'}, {'H','U'}, {'V','I'}, {'A','N'}, {'O','B'}, {'E','R'}, {'F','S'}, {'L','Y'}, {'P','C'}, {'Z','M'} }; + std::vector words{"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"}; + for (const std::string& w : words) { + std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n"; + } + +} diff --git a/Task/ABC-Problem/C-sharp/abc-problem.cs b/Task/ABC-Problem/C-sharp/abc-problem.cs new file mode 100644 index 0000000000..3b74191a56 --- /dev/null +++ b/Task/ABC-Problem/C-sharp/abc-problem.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using System.Linq; + +void Main() +{ + List blocks = + new List() { "bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", + "jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm" }; + List words = new List() { + "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"}; + + var solver = new ABC(blocks); + + foreach( var word in words) + { + Console.WriteLine("{0} :{1}", word, solver.CanMake(word)); + } +} + +class ABC +{ + readonly Dictionary> _blockDict = new Dictionary>(); + bool[] _used; + int _nextBlock; + + readonly List _blocks; + + private void AddBlockChar(char c) + { + if (!_blockDict.ContainsKey(c)) + { + _blockDict[c] = new List(); + } + _blockDict[c].Add(_nextBlock); + } + + private void AddBlock(string block) + { + AddBlockChar(block[0]); + AddBlockChar(block[1]); + _nextBlock++; + } + + public ABC(List blocks) + { + _blocks = blocks; + foreach (var block in blocks) + { + AddBlock(block); + } + } + + public bool CanMake(string word) + { + word = word.ToLower(); + if (word.Length > _blockDict.Count) + { + return false; + } + _used = new bool[_blocks.Count]; + return TryMake(word); + } + + public bool TryMake(string word) + { + if (word == string.Empty) + { + return true; + } + var blocks = _blockDict[word[0]].Where(b => !_used[b]); + foreach (var block in blocks) + { + _used[block] = true; + if (TryMake(word.Substring(1))) + { + return true; + } + _used[block] = false; + } + return false; + } +} diff --git a/Task/ABC-Problem/C/abc-problem.c b/Task/ABC-Problem/C/abc-problem.c new file mode 100644 index 0000000000..0a798cd2c4 --- /dev/null +++ b/Task/ABC-Problem/C/abc-problem.c @@ -0,0 +1,41 @@ +#include +#include + +int can_make_words(char **b, char *word) +{ + int i, ret = 0, c = toupper(*word); + +#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; } + + if (!c) return 1; + if (!b[0]) return 0; + + for (i = 0; b[i] && !ret; i++) { + if (b[i][0] != c && b[i][1] != c) continue; + SWAP(b[i], b[0]); + ret = can_make_words(b + 1, word + 1); + SWAP(b[i], b[0]); + } + + return ret; +} + +int main(void) +{ + char* blocks[] = { + "BO", "XK", "DQ", "CP", "NA", + "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", + "ER", "FS", "LY", "PC", "ZM", + 0 }; + + char *words[] = { + "", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse", 0 + }; + + char **w; + for (w = words; *w; w++) + printf("%s\t%d\n", *w, can_make_words(blocks, *w)); + + return 0; +} diff --git a/Task/ABC-Problem/Clojure/abc-problem.clj b/Task/ABC-Problem/Clojure/abc-problem.clj new file mode 100644 index 0000000000..00b43386e8 --- /dev/null +++ b/Task/ABC-Problem/Clojure/abc-problem.clj @@ -0,0 +1,21 @@ +(def blocks + (-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec)) + +(defn omit + "return bs with (one instance of) b omitted" + [bs b] + (let [[before after] (split-with #(not= b %) bs)] + (concat before (rest after)))) + +(defn abc + "return lazy sequence of solutions (i.e. block lists)" + [blocks [c & cs]] + (if-some c + (for [b blocks :when (some #(= c %) b) + bs (abc (omit blocks b) cs)] + (cons b bs)) + [[]])) + + +(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]] + (->> word .toUpperCase (abc blocks) first (printf "%s: %b\n" word))) diff --git a/Task/ABC-Problem/CoffeeScript/abc-problem.coffee b/Task/ABC-Problem/CoffeeScript/abc-problem.coffee new file mode 100644 index 0000000000..2bc54c4925 --- /dev/null +++ b/Task/ABC-Problem/CoffeeScript/abc-problem.coffee @@ -0,0 +1,15 @@ +canMakeWord = (word="") -> + # Create a shallow clone of the master blockList + blocks = blockList.slice 0 + # Check if blocks contains letter + checkBlocks = (letter) -> + # Loop through every remaining block + for block, idx in blocks + # If letter is in block, blocks.splice will return an array, which will evaluate as true + return blocks.splice idx, 1 if letter.toUpperCase() in block + return false + # Return true if there are no falsy values + return false not in (checkBlocks letter for letter in word) + +# Expect true, true, false, true, false, true, true, true +console.log (canMakeWord word for word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "squad", "CONFUSE", "STORM"]) diff --git a/Task/ABC-Problem/Common-Lisp/abc-problem.lisp b/Task/ABC-Problem/Common-Lisp/abc-problem.lisp new file mode 100644 index 0000000000..34642b4385 --- /dev/null +++ b/Task/ABC-Problem/Common-Lisp/abc-problem.lisp @@ -0,0 +1,14 @@ +(defun word-possible-p (word blocks) + (cond + ((= (length word) 0) t) + ((null blocks) nil) + (t (let* + ((c (aref word 0)) + (bs (remove-if-not #'(lambda (b) + (find c b :test #'char-equal)) + blocks))) + (some #'identity + (loop for b in bs + collect (word-possible-p + (subseq word 1) + (remove b blocks)))))))) diff --git a/Task/ABC-Problem/D/abc-problem-1.d b/Task/ABC-Problem/D/abc-problem-1.d new file mode 100644 index 0000000000..84eaeef371 --- /dev/null +++ b/Task/ABC-Problem/D/abc-problem-1.d @@ -0,0 +1,22 @@ +import std.stdio, std.algorithm, std.string; + +bool canMakeWord(in string word, in string[] blocks) pure /*nothrow*/ @safe { + auto bs = blocks.dup; + outer: foreach (immutable ch; word.toUpper) { + foreach (immutable block; bs) + if (block.canFind(ch)) { + bs = bs.remove(bs.countUntil(block)); + continue outer; + } + return false; + } + return true; +} + +void main() @safe { + immutable blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI + AN OB ER FS LY PC ZM".split; + + foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split) + writefln(`"%s" %s`, word, canMakeWord(word, blocks)); +} diff --git a/Task/ABC-Problem/D/abc-problem-2.d b/Task/ABC-Problem/D/abc-problem-2.d new file mode 100644 index 0000000000..5f9efd6445 --- /dev/null +++ b/Task/ABC-Problem/D/abc-problem-2.d @@ -0,0 +1,39 @@ +import std.ascii, core.stdc.stdlib; + +bool canMakeWord(in string word, in string[] blocks) nothrow @nogc +in { + foreach (immutable char ch; word) + assert(ch.isASCII); + foreach (const block; blocks) + assert(block.length == 2 && block[0].isASCII && block[1].isASCII); +} body { + auto ptr = cast(string*)alloca(blocks.length * string.sizeof); + if (ptr == null) + exit(1); + auto blocks2 = ptr[0 .. blocks.length]; + blocks2[] = blocks[]; + + outer: foreach (immutable i; 0 .. word.length) { + immutable ch = word[i].toUpper; + foreach (immutable j; 0 .. blocks2.length) { + if (blocks2[j][0] == ch || blocks2[j][1] == ch) { + if (blocks2.length > 1) + blocks2[j] = blocks2[$ - 1]; + blocks2 = blocks2[0 .. $ - 1]; + continue outer; + } + } + return false; + } + return true; +} + +void main() { + import std.stdio, std.string; + + immutable blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI + AN OB ER FS LY PC ZM".split; + + foreach (word; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split) + writefln(`"%s" %s`, word, canMakeWord(word, blocks)); +} diff --git a/Task/ABC-Problem/D/abc-problem-3.d b/Task/ABC-Problem/D/abc-problem-3.d new file mode 100644 index 0000000000..18a68f33c5 --- /dev/null +++ b/Task/ABC-Problem/D/abc-problem-3.d @@ -0,0 +1,38 @@ +import std.stdio, std.ascii, std.algorithm, std.array; + +alias Block = char[2]; + +// Modifies the order of the given blocks. +bool canMakeWord(Block[] blocks, in string word) pure nothrow +in { + assert(blocks.all!(w => w[].all!isAlpha)); + assert(word.all!isAlpha); +} body { + if (word.empty) + return true; + + immutable c = word[0].toUpper; + foreach (ref b; blocks) { + if (b[0].toUpper != c && b[1].toUpper != c) + continue; + blocks[0].swap(b); + if (blocks[1 .. $].canMakeWord(word[1 .. $])) + return true; + blocks[0].swap(b); + } + + return false; +} + +void main() { + enum Block[] blocks = "BO XK DQ CP NA GT RE TG QD FS + JW HU VI AN OB ER FS LY PC ZM".split; + + foreach (w; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split) + writefln(`"%s" %s`, w, blocks.canMakeWord(w)); + + // Extra test. + Block[] blocks2 = ["AB", "AB", "AC", "AC"]; + immutable word = "abba"; + writefln(`"%s" %s`, word, blocks2.canMakeWord(word)); +} diff --git a/Task/ABC-Problem/D/abc-problem-4.d b/Task/ABC-Problem/D/abc-problem-4.d new file mode 100644 index 0000000000..2dc87f707a --- /dev/null +++ b/Task/ABC-Problem/D/abc-problem-4.d @@ -0,0 +1,42 @@ +import std.stdio, std.ascii, std.algorithm, std.array, std.range; + +alias Block = char[2]; + +bool canMakeWord(immutable Block[] blocks, in string word) pure nothrow +in { + assert(blocks.all!(w => w[].all!isAlpha)); + assert(word.all!isAlpha); +} body { + bool inner(size_t[] indexes, in string w) pure nothrow { + if (w.empty) + return true; + + immutable c = w[0].toUpper; + foreach (ref idx; indexes) { + if (blocks[idx][0].toUpper != c && + blocks[idx][1].toUpper != c) + continue; + indexes[0].swap(idx); + if (inner(indexes[1 .. $], w[1 .. $])) + return true; + indexes[0].swap(idx); + } + + return false; + } + + return inner(blocks.length.iota.array, word); +} + +void main() { + enum Block[] blocks = "BO XK DQ CP NA GT RE TG QD FS + JW HU VI AN OB ER FS LY PC ZM".split; + + foreach (w; "" ~ "A BARK BoOK TrEAT COmMoN SQUAD conFUsE".split) + writefln(`"%s" %s`, w, blocks.canMakeWord(w)); + + // Extra test. + immutable Block[] blocks2 = ["AB", "AB", "AC", "AC"]; + immutable word = "abba"; + writefln(`"%s" %s`, word, blocks2.canMakeWord(word)); +} diff --git a/Task/ABC-Problem/Delphi/abc-problem.delphi b/Task/ABC-Problem/Delphi/abc-problem.delphi new file mode 100644 index 0000000000..442a1dc411 --- /dev/null +++ b/Task/ABC-Problem/Delphi/abc-problem.delphi @@ -0,0 +1,63 @@ +program ABC; +{$APPTYPE CONSOLE} + +uses SysUtils; + +type + TBlock = set of char; + +const + TheBlocks : array [0..19] of TBlock = + ( + [ 'B', 'O' ], [ 'X', 'K' ], [ 'D', 'Q' ], [ 'C', 'P' ], [ 'N', 'A' ], + [ 'G', 'T' ], [ 'R', 'E' ], [ 'T', 'G' ], [ 'Q', 'D' ], [ 'F', 'S' ], + [ 'J', 'W' ], [ 'H', 'U' ], [ 'V', 'I' ], [ 'A', 'N' ], [ 'O', 'B' ], + [ 'E', 'R' ], [ 'F', 'S' ], [ 'L', 'Y' ], [ 'P', 'C' ], [ 'Z', 'M' ] + ); + +function SolveABC(Target : string; Blocks : array of TBlock) : boolean; +var + iChr : integer; + Used : array [0..19] of boolean; + + function FindUnused(TargetChr : char) : boolean; // Nested routine + var + iBlock : integer; + begin + Result := FALSE; + for iBlock := low(Blocks) to high(Blocks) do + if (not Used[iBlock]) and ( TargetChr in Blocks[iBlock] ) then + begin + Result := TRUE; + Used[iBlock] := TRUE; + Break; + end; + end; + +begin + FillChar(Used, sizeof(Used), ord(FALSE)); + Result := TRUE; + iChr := 1; + while Result and (iChr <= length(Target)) do + if FindUnused(Target[iChr]) then inc(iChr) + else Result := FALSE; +end; + +procedure CheckABC(Target : string); +begin + if SolveABC(uppercase(Target), TheBlocks) then + writeln('Can make ' + Target) + else + writeln('Can NOT make ' + Target); +end; + +begin + CheckABC('A'); + CheckABC('BARK'); + CheckABC('BOOK'); + CheckABC('TREAT'); + CheckABC('COMMON'); + CheckABC('SQUAD'); + CheckABC('CONFUSE'); + readln; +end. diff --git a/Task/ABC-Problem/Erlang/abc-problem.erl b/Task/ABC-Problem/Erlang/abc-problem.erl new file mode 100644 index 0000000000..d60189c38f --- /dev/null +++ b/Task/ABC-Problem/Erlang/abc-problem.erl @@ -0,0 +1,16 @@ +-module(abc). +-export([can_make_word/1, can_make_word/2, blocks/0]). + +blocks() -> ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]. + +can_make_word(Word) -> can_make_word(Word, blocks()). +can_make_word(Word, Avail) -> can_make_word(string:to_upper(Word), Avail, []). +can_make_word([], _, _) -> true; +can_make_word(_, [], _) -> false; +can_make_word([L|Tail], [B|Rest], Tried) -> + (lists:member(L,B) andalso can_make_word(Tail, lists:append(Rest, Tried),[])) + orelse can_make_word([L|Tail], Rest, [B|Tried]). + +main(_) -> lists:map(fun(W) -> io:fwrite("~s: ~s~n", [W, can_make_word(W)]) end, + ["A","Bark","Book","Treat","Common","Squad","Confuse"]). diff --git a/Task/ABC-Problem/Euphoria/abc-problem.euphoria b/Task/ABC-Problem/Euphoria/abc-problem.euphoria new file mode 100644 index 0000000000..efa3352600 --- /dev/null +++ b/Task/ABC-Problem/Euphoria/abc-problem.euphoria @@ -0,0 +1,35 @@ +include std/text.e + +sequence blocks = {{'B','O'},{'X','K'},{'D','Q'},{'C','P'},{'N','A'}, + {'G','T'},{'R','E'},{'T','G'},{'Q','D'},{'F','S'}, + {'J','W'},{'H','U'},{'V','I'},{'A','N'},{'O','B'}, + {'E','R'},{'F','S'},{'L','Y'},{'P','C'},{'Z','M'}} +sequence words = {"A","BarK","BOOK","TrEaT","COMMON","SQUAD","CONFUSE"} + +sequence current_word +sequence temp +integer matches + +for i = 1 to length(words) do + current_word = upper(words[i]) + temp = blocks + matches = 0 + for j = 1 to length(current_word) do + for k = 1 to length(temp) do + if find(current_word[j],temp[k]) then + temp = remove(temp,k) + matches += 1 + exit + end if + end for + if length(current_word) = matches then + printf(1,"%s: TRUE\n",{words[i]}) + exit + end if + end for + if length(current_word) != matches then + printf(1,"%s: FALSE\n",{words[i]}) + end if +end for + +if getc(0) then end if diff --git a/Task/ABC-Problem/FBSL/abc-problem.fbsl b/Task/ABC-Problem/FBSL/abc-problem.fbsl new file mode 100644 index 0000000000..9c34a6ea72 --- /dev/null +++ b/Task/ABC-Problem/FBSL/abc-problem.fbsl @@ -0,0 +1,44 @@ +#APPTYPE CONSOLE +SUB MAIN() + BlockCheck("A") + BlockCheck("BARK") + BlockCheck("BooK") + BlockCheck("TrEaT") + BlockCheck("comMON") + BlockCheck("sQuAd") + BlockCheck("Confuse") + pause +END SUB + +FUNCTION BlockCheck(str) + print str " " iif( Blockable( str ), "can", "cannot" ) " be spelled with blocks." +END FUNCTION + +FUNCTION Blockable(str AS STRING) + DIM blocks AS STRING = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" + DIM C AS STRING = "" + DIM POS AS INTEGER = 0 + + FOR DIM I = 1 TO LEN(str) + C = str{i} + POS = INSTR(BLOCKS, C, 0, 1) 'case insensitive + IF POS > 0 THEN + 'if the pos is odd, it's the first of the pair + IF POS MOD 2 = 1 THEN + 'so clear the first and the second + poke(@blocks + pos - 1," ") + poke(@blocks + pos," ") + 'otherwise, it's the last of the pair + ELSE + 'clear the second and the first + poke(@blocks + pos - 1," ") + poke(@blocks + pos - 2," ") + END IF + ELSE + 'not found, so can't be spelled + RETURN FALSE + END IF + NEXT + 'got thru to here, so can be spelled + RETURN TRUE +END FUNCTION diff --git a/Task/ABC-Problem/Fortran/abc-problem.f b/Task/ABC-Problem/Fortran/abc-problem.f new file mode 100644 index 0000000000..41ab0d9942 --- /dev/null +++ b/Task/ABC-Problem/Fortran/abc-problem.f @@ -0,0 +1,70 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Thu Jun 5 01:52:03 +! +!make f && for a in '' a bark book treat common squad confuse ; do echo $a | ./f ; done +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f +! T +! T A NA +! T BARK BO NA RE XK +! F BOOK OB BO -- -- +! T TREAT GT RE ER NA TG +! F COMMON PC OB ZM -- -- -- +! T SQUAD FS DQ HU NA QD +! T CONFUSE CP BO NA FS HU FS RE +! +!Compilation finished at Thu Jun 5 01:52:03 + +program abc + implicit none + integer, parameter :: nblocks = 20 + character(len=nblocks) :: goal + integer, dimension(nblocks) :: solution + character(len=2), dimension(0:nblocks) :: blocks_copy, blocks = & + &(/'--','BO','XK','DQ','CP','NA','GT','RE','TG','QD','FS','JW','HU','VI','AN','OB','ER','FS','LY','PC','ZM'/) + logical :: valid + integer :: i, iostat + read(5,*,iostat=iostat) goal + if (iostat .ne. 0) goal = '' + call ucase(goal) + solution = 0 + blocks_copy = blocks + valid = assign_block(goal(1:len_trim(goal)), blocks, solution, 1) + write(6,*) valid, ' '//goal, (' '//blocks_copy(solution(i)), i=1,len_trim(goal)) + +contains + + recursive function assign_block(goal, blocks, solution, n) result(valid) + implicit none + logical :: valid + character(len=*), intent(in) :: goal + character(len=2), dimension(0:), intent(inout) :: blocks + integer, dimension(:), intent(out) :: solution + integer, intent(in) :: n + integer :: i + character(len=2) :: backing_store + valid = .true. + if (len(goal)+1 .eq. n) return + do i=1, size(blocks) + if (index(blocks(i),goal(n:n)) .ne. 0) then + backing_store = blocks(i) + blocks(i) = '' + solution(n) = i + if (assign_block(goal, blocks, solution, n+1)) return + blocks(i) = backing_store + end if + end do + valid = .false. + return + end function assign_block + + subroutine ucase(a) + implicit none + character(len=*), intent(inout) :: a + integer :: i, j + do i = 1, len_trim(a) + j = index('abcdefghijklmnopqrstuvwxyz',a(i:i)) + if (j .ne. 0) a(i:i) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'(j:j) + end do + end subroutine ucase + +end program abc diff --git a/Task/ABC-Problem/Go/abc-problem.go b/Task/ABC-Problem/Go/abc-problem.go new file mode 100644 index 0000000000..5ad1a85f59 --- /dev/null +++ b/Task/ABC-Problem/Go/abc-problem.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "strings" +) + +func newSpeller(blocks string) func(string) bool { + bl := strings.Fields(blocks) + return func(word string) bool { + return r(word, bl) + } +} + +func r(word string, bl []string) bool { + if word == "" { + return true + } + c := word[0] | 32 + for i, b := range bl { + if c == b[0]|32 || c == b[1]|32 { + bl[i], bl[0] = bl[0], b + if r(word[1:], bl[1:]) == true { + return true + } + bl[i], bl[0] = bl[0], bl[i] + } + } + return false +} + +func main() { + sp := newSpeller( + "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM") + for _, word := range []string{ + "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} { + fmt.Println(word, sp(word)) + } +} diff --git a/Task/ABC-Problem/Groovy/abc-problem-1.groovy b/Task/ABC-Problem/Groovy/abc-problem-1.groovy new file mode 100644 index 0000000000..5d3cd45b11 --- /dev/null +++ b/Task/ABC-Problem/Groovy/abc-problem-1.groovy @@ -0,0 +1,12 @@ +class ABCSolver { + def blocks + + ABCSolver(blocks = []) { this.blocks = blocks } + + boolean canMakeWord(rawWord) { + if (rawWord == '' || rawWord == null) { return true; } + def word = rawWord.toUpperCase() + def blocksLeft = [] + blocks + word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) } + } +} diff --git a/Task/ABC-Problem/Groovy/abc-problem-2.groovy b/Task/ABC-Problem/Groovy/abc-problem-2.groovy new file mode 100644 index 0000000000..d55aea5884 --- /dev/null +++ b/Task/ABC-Problem/Groovy/abc-problem-2.groovy @@ -0,0 +1,6 @@ +def a = new ABCSolver(["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]) + +['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each { + println "'${it}': ${a.canMakeWord(it)}" +} diff --git a/Task/ABC-Problem/Haskell/abc-problem.hs b/Task/ABC-Problem/Haskell/abc-problem.hs new file mode 100644 index 0000000000..76258b53e9 --- /dev/null +++ b/Task/ABC-Problem/Haskell/abc-problem.hs @@ -0,0 +1,15 @@ +import Data.List (delete) +import Data.Char (toUpper) + +-- returns list of all solutions, each solution being a list of blocks +abc :: (Eq a) => [[a]] -> [a] -> [[[a]]] +abc _ [] = [[]] +abc blocks (c:cs) = [b:ans | b <- blocks, c `elem` b, + ans <- abc (delete b blocks) cs] + +blocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"] + +main :: IO () +main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w))) + ["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"] diff --git a/Task/ABC-Problem/Icon/abc-problem.icon b/Task/ABC-Problem/Icon/abc-problem.icon new file mode 100644 index 0000000000..8c841b34ce --- /dev/null +++ b/Task/ABC-Problem/Icon/abc-problem.icon @@ -0,0 +1,24 @@ +procedure main(A) + blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs", + "jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null] + every write("\"",word := !A,"\" ",checkSpell(map(word),blocks)," with blocks.") +end + +procedure checkSpell(w,blocks) + blks := copy(blocks) + w ? return if canMakeWord(blks) then "can be spelled" + else "can not be spelled" +end + +procedure canMakeWord(blks) + c := move(1) | return + if /blks[1] then fail + every i := 1 to *blks do { + if /blks[i] then (move(-1),fail) + if c == !blks[i] then { + blks[1] :=: blks[i] + if canMakeWord(blks[2:0]) then return + blks[1] :=: blks[i] + } + } +end diff --git a/Task/ABC-Problem/J/abc-problem-1.j b/Task/ABC-Problem/J/abc-problem-1.j new file mode 100644 index 0000000000..a934ff56bc --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-1.j @@ -0,0 +1,11 @@ +reduce=: verb define + 'rows cols'=. i.&.> $y + for_c. cols do. + r=. 1 i.~ c {"1 y NB. row idx of first 1 in col + if. r = #rows do. continue. end. + y=. 0 (<((r+1)}.rows);c) } y NB. zero rest of col + y=. 0 (<(r;(c+1)}.cols)) } y NB. zero rest of row + end. +) + +abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0: diff --git a/Task/ABC-Problem/J/abc-problem-2.j b/Task/ABC-Problem/J/abc-problem-2.j new file mode 100644 index 0000000000..92b6be9062 --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-2.j @@ -0,0 +1,14 @@ + Blocks=: ];._2 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM ' + ExampleWords=: <;._2 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE ' + + Blocks&abc &> ExampleWords +1 1 0 1 0 1 1 + require 'format/printf' + '%10s %s' printf (dquote ; 'FT' {~ Blocks&abc) &> ExampleWords + "A" T + "BaRK" T + "BOoK" F + "tREaT" T + "COmMOn" F + "SqUAD" T + "CoNfuSE" T diff --git a/Task/ABC-Problem/J/abc-problem-3.j b/Task/ABC-Problem/J/abc-problem-3.j new file mode 100644 index 0000000000..56e3992269 --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-3.j @@ -0,0 +1,3 @@ +delElem=: {~<@<@< +uppc=:(-32*96&<*.123&>)&.(3&u:) +reduc=: ] delElem 1 i.~e."0 1 diff --git a/Task/ABC-Problem/J/abc-problem-4.j b/Task/ABC-Problem/J/abc-problem-4.j new file mode 100644 index 0000000000..10190ed384 --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-4.j @@ -0,0 +1,10 @@ +Blocks=: >;:'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM ' +ExampleWords=: ;: 'A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE ' + +canform=:4 :0 + word=: toupper y + need=: #/.~ word,word + relevant=: (x +./@e."1 word) # x + candidates=: word,"1>,{{relevant + +./(((#need){. #/.~)"1 candidates) */ .>:need +) diff --git a/Task/ABC-Problem/J/abc-problem-5.j b/Task/ABC-Problem/J/abc-problem-5.j new file mode 100644 index 0000000000..24e2166934 --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-5.j @@ -0,0 +1,14 @@ + Blocks canform 0{::ExampleWords +1 + Blocks canform 1{::ExampleWords +1 + Blocks canform 2{::ExampleWords +0 + Blocks canform 3{::ExampleWords +1 + Blocks canform 4{::ExampleWords +0 + Blocks canform 5{::ExampleWords +1 + Blocks canform 6{::ExampleWords +1 diff --git a/Task/ABC-Problem/Java/abc-problem.java b/Task/ABC-Problem/Java/abc-problem.java new file mode 100644 index 0000000000..8cd74ed0ba --- /dev/null +++ b/Task/ABC-Problem/Java/abc-problem.java @@ -0,0 +1,44 @@ +import java.util.Arrays; + +public class ABC{ + private static void swap(int i, int j, Object... arr){ + Object tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + + public static boolean canMakeWord(String word, String... blocks) { + if(word.length() == 0) + return true; + + char c = Character.toUpperCase(word.charAt(0)); + for(int i = 0; i < blocks.length; i++) { + String b = blocks[i]; + if(Character.toUpperCase(b.charAt(0)) != c && Character.toUpperCase(b.charAt(1)) != c) + continue; + swap(0, i, blocks); + if(canMakeWord(word.substring(1), Arrays.copyOfRange(blocks, 1, blocks.length))) + return true; + swap(0, i, blocks); + } + + return false; + } + + public static void main(String[] args){ + String[] blocks = {"BO", "XK", "DQ", "CP", "NA", + "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", + "ER", "FS", "LY", "PC", "ZM"}; + + System.out.println("\"\": " + canMakeWord("", blocks)); + System.out.println("A: " + canMakeWord("A", blocks)); + System.out.println("BARK: " + canMakeWord("BARK", blocks)); + System.out.println("book: " + canMakeWord("book", blocks)); + System.out.println("treat: " + canMakeWord("treat", blocks)); + System.out.println("COMMON: " + canMakeWord("COMMON", blocks)); + System.out.println("SQuAd: " + canMakeWord("SQuAd", blocks)); + System.out.println("CONFUSE: " + canMakeWord("CONFUSE", blocks)); + + } +} diff --git a/Task/ABC-Problem/JavaScript/abc-problem.js b/Task/ABC-Problem/JavaScript/abc-problem.js new file mode 100644 index 0000000000..b7a0a153cc --- /dev/null +++ b/Task/ABC-Problem/JavaScript/abc-problem.js @@ -0,0 +1,32 @@ +let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"; +let blocks = characters.split(" ").map(pair => pair.split("")); + +function isWordPossible(word) { + var letters = [...word.toUpperCase()]; + var length = letters.length; + var copy = new Set(blocks); + + for (let letter of letters) { + for (let block of copy) { + let index = block.indexOf(letter); + + if (index !== -1) { + length--; + copy.delete(block); + break; + } + } + + } + return !length; +} + +[ + "A", + "BARK", + "BOOK", + "TREAT", + "COMMON", + "SQUAD", + "CONFUSE" +].forEach(word => console.log(`${word}: ${isWordPossible(word)}`)); diff --git a/Task/ABC-Problem/Julia/abc-problem.julia b/Task/ABC-Problem/Julia/abc-problem.julia new file mode 100644 index 0000000000..06d600fbc6 --- /dev/null +++ b/Task/ABC-Problem/Julia/abc-problem.julia @@ -0,0 +1,9 @@ +function abc (str, list) + isempty(str) && return true + for i = 1:length(list) + str[end] in list[i] && + any([abc(str[1:end-1], deleteat!(copy(list), i))]) && + return true + end + false +end diff --git a/Task/ABC-Problem/Logo/abc-problem.logo b/Task/ABC-Problem/Logo/abc-problem.logo new file mode 100644 index 0000000000..65666745dd --- /dev/null +++ b/Task/ABC-Problem/Logo/abc-problem.logo @@ -0,0 +1,21 @@ +make "blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S] + [J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]] + +to can_make? :word [:avail :blocks] + if empty? :word [output "true] + local "letter make "letter first :word + foreach :avail [ + local "i make "i # + local "block make "block ? + if member? :letter :block [ + if (can_make? bf :word filter [notequal? # :i] :avail) [output "true] + ] + ] + output "false +end + +foreach [A BARK BOOK TREAT COMMON SQUAD CONFUSE] [ + print sentence word ? ": can_make? ? +] + +bye diff --git a/Task/ABC-Problem/MATLAB/abc-problem.m b/Task/ABC-Problem/MATLAB/abc-problem.m new file mode 100644 index 0000000000..e8ab76b86e --- /dev/null +++ b/Task/ABC-Problem/MATLAB/abc-problem.m @@ -0,0 +1,26 @@ +function testABC + combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ... + 'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ... + 'PC' ; 'ZM']; + words = {'A' 'BARK' 'BOOK' 'TREAT' 'COMMON' 'SQUAD' 'CONFUSE'}; + for k = 1:length(words) + possible = canMakeWord(words{k}, combos); + fprintf('Can%s make word %s.\n', char(~possible.*'NOT'), words{k}) + end +end + +function isPossible = canMakeWord(word, combos) + word = lower(word); + combos = lower(combos); + isPossible = true; + k = 1; + while isPossible && k <= length(word) + [r, c] = find(combos == word(k), 1); + if ~isempty(r) + combos(r, :) = ''; + else + isPossible = false; + end + k = k+1; + end +end diff --git a/Task/ABC-Problem/MAXScript/abc-problem-1.max b/Task/ABC-Problem/MAXScript/abc-problem-1.max new file mode 100644 index 0000000000..c05646f32e --- /dev/null +++ b/Task/ABC-Problem/MAXScript/abc-problem-1.max @@ -0,0 +1,98 @@ +-- This is the blocks array +global GlobalBlocks = #("BO","XK","DQ","CP","NA", \ + "GT","RE","TG","QD","FS", \ + "JW","HU","VI","AN","OB", \ + "ER","FS","LY","PC","ZM") + +-- This function returns true if "_str" is part of "_word", false otherwise +fn occurs _str _word = +( + if _str != undefined and _word != undefined then + ( + matchpattern _word pattern:("*"+_str+"*") + ) else return false +) + +-- This is the main function +fn isWordPossible word blocks: = -- blocks is a keyword argument +( + word = toupper word -- convert the string to upper case, to make it case insensitive + if blocks == unsupplied do blocks = GlobalBlocks + -- if blocks (keyword argument) is unsupplied, use the global blocks array (this is for recursion) + + blocks = deepcopy blocks + + local pos = 1 -- start at the beginning of the word + local solvedLetters = #() -- this array stores the indices of solved letters + + while pos <= word.count do -- loop through every character in the word + ( + local possibleBlocks = #() -- this array stores the blocks which can be used to make that letter + for b = 1 to Blocks.count do -- this loop finds all the possible blocks that can be used to make that letter + ( + if occurs word[pos] blocks[b] do + ( + appendifunique possibleBlocks b + ) + ) + if possibleBlocks.count > 0 then -- if it found any blocks + ( + if possibleBlocks.count == 1 then -- if it found one block, then continue + ( + appendifunique solvedLetters pos + deleteitem blocks possibleblocks[1] + pos += 1 + ) + else -- if it found more than one + ( + for b = 1 to possibleBlocks.count do -- loop through every possible block + ( + local possibleBlock = blocks[possibleBlocks[b]] + local blockFirstLetter = possibleBlock[1] + local blockSecondLetter = possibleBlock[2] + local matchingLetter = if blockFirstLetter == word[pos] then 1 else 2 + -- ^ this is the index of the matching letter on the block + + local notMatchingIndex = if matchingLetter == 1 then 2 else 1 + local notMatchingLetter = possibleBlock[notMatchingIndex] + -- ^ this is the other letter on the block + + if occurs notMatchingLetter (substring word (pos+1) -1) then + ( -- if the other letter occurs in the rest of the word + local removedBlocks = deepcopy blocks -- copy the current blocks array + deleteitem removedBlocks possibleBlocks[b] -- remove the item from the copied array + + -- recursively check if the word is possible if that block is taken away from the array: + if (isWordPossible (substring word (pos+1) -1) blocks:removedBlocks) then + ( -- if it is, then remove the block and move to next character + appendifunique solvedLetters pos + deleteitem blocks possibleblocks[1] + pos += 1 + exit + ) + else + ( -- if it isn't and it looped through every possible block, then the word is not possible + if b == possibleBlocks.count do return false + ) + ) + else + ( -- if the other letter on this block doesn't occur in the rest of the word, then the letter is solved, continue + appendifunique solvedLetters pos + deleteitem blocks possibleblocks[b] + pos += 1 + exit + ) + ) + ) + ) else return false -- if it didn't find any blocks, then return false + ) + + makeuniquearray solvedLetters -- make sure there are no duplicates in the solved array + if solvedLetters.count != word.count then return false -- if number of solved letters is not equal to word length + else + ( -- this checks if all the solved letters are the same as the word + check = "" + for bit in solvedLetters do append check word[bit] + if check == word then return true else return false + ) +) diff --git a/Task/ABC-Problem/MAXScript/abc-problem-2.max b/Task/ABC-Problem/MAXScript/abc-problem-2.max new file mode 100644 index 0000000000..588811d229 --- /dev/null +++ b/Task/ABC-Problem/MAXScript/abc-problem-2.max @@ -0,0 +1,14 @@ +iswordpossible "a" +true +iswordpossible "bark" +true +iswordpossible "book" +false +iswordpossible "treat" +true +iswordpossible "common" +false +iswordpossible "squad" +true +iswordpossible "confuse" +true diff --git a/Task/ABC-Problem/MAXScript/abc-problem-3.max b/Task/ABC-Problem/MAXScript/abc-problem-3.max new file mode 100644 index 0000000000..4681f1b686 --- /dev/null +++ b/Task/ABC-Problem/MAXScript/abc-problem-3.max @@ -0,0 +1,30 @@ +fn isWordPossible2 word = +( + Blocks = #("BO","XK","DQ","CP","NA", \ + "GT","RE","TG","QD","FS", \ + "JW","HU","VI","AN","OB", \ + "ER","FS","LY","PC","ZM") + word = toupper word + local pos = 1 + local solvedLetters = #() + while pos <= word.count do + ( + for i = 1 to blocks.count do + ( + if (matchpattern blocks[i] pattern:("*"+word[pos]+"*")) then + ( + deleteitem blocks i + appendifunique solvedLetters pos + pos +=1 + exit + ) + else if i == blocks.count do return false + ) + ) + if solvedLetters.count == word.count then + ( + local check = "" + for bit in solvedLetters do append check word[bit] + if check == word then return true else return false + ) else return false +) diff --git a/Task/ABC-Problem/MAXScript/abc-problem-4.max b/Task/ABC-Problem/MAXScript/abc-problem-4.max new file mode 100644 index 0000000000..de896ca7ec --- /dev/null +++ b/Task/ABC-Problem/MAXScript/abc-problem-4.max @@ -0,0 +1,4 @@ +iswordpossible "water" +true +iswordpossible2 "water" +false diff --git a/Task/ABC-Problem/Mathematica/abc-problem.math b/Task/ABC-Problem/Mathematica/abc-problem.math new file mode 100644 index 0000000000..7e1e87644e --- /dev/null +++ b/Task/ABC-Problem/Mathematica/abc-problem.math @@ -0,0 +1,12 @@ +blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2]; +ClearAll[DoStep,ABCBlockQ] +DoStep[chars_List,blcks_List,chosen_List]:=Module[{opts}, + If[chars=!={}, + opts=Select[blcks,MemberQ[#,First[chars]]&]; + {Rest[chars],DeleteCases[blcks,#,1,1],Append[chosen,#]}&/@opts + , + {{chars,blcks,chosen}} + ] +] +DoStep[opts_List]:=Flatten[DoStep@@@opts,1] +ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={}) diff --git a/Task/ABC-Problem/OCaml/abc-problem.ocaml b/Task/ABC-Problem/OCaml/abc-problem.ocaml new file mode 100644 index 0000000000..f65ef95aa9 --- /dev/null +++ b/Task/ABC-Problem/OCaml/abc-problem.ocaml @@ -0,0 +1,40 @@ +let blocks = [ + ('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P'); + ('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G'); + ('Q', 'D'); ('F', 'S'); ('J', 'W'); ('H', 'U'); + ('V', 'I'); ('A', 'N'); ('O', 'B'); ('E', 'R'); + ('F', 'S'); ('L', 'Y'); ('P', 'C'); ('Z', 'M'); +] + +let find_letter blocks c = + let found, remaining = + List.partition (fun (c1, c2) -> c1 = c || c2 = c) blocks + in + match found with + | _ :: res -> Some (res @ remaining) + | _ -> None + +let can_make_word w = + let n = String.length w in + let rec aux i _blocks = + if i >= n then true else + match find_letter _blocks w.[i] with + | None -> false + | Some rem_blocks -> + aux (succ i) rem_blocks + in + aux 0 blocks + +let test label f (word, should) = + Printf.printf "- %s %S = %B (should: %B)\n" label word (f word) should + +let () = + List.iter (test "can make word" can_make_word) [ + "A", true; + "BARK", true; + "BOOK", false; + "TREAT", true; + "COMMON", false; + "SQUAD", true; + "CONFUSE", true; + ] diff --git a/Task/ABC-Problem/Oberon-2/abc-problem.oberon-2 b/Task/ABC-Problem/Oberon-2/abc-problem.oberon-2 new file mode 100644 index 0000000000..fbddd4d9bb --- /dev/null +++ b/Task/ABC-Problem/Oberon-2/abc-problem.oberon-2 @@ -0,0 +1,83 @@ +MODULE ABCBlocks; +IMPORT + Object, + Out; + +VAR + blocks: ARRAY 20 OF STRING; + + PROCEDURE CanMakeWord(w: STRING): BOOLEAN; + VAR + used: ARRAY 20 OF LONGINT; + wChars: Object.CharsLatin1; + i,j: LONGINT; + + PROCEDURE IsUsed(i: LONGINT): BOOLEAN; + VAR + b: LONGINT; + BEGIN + b := 0; + WHILE (b < LEN(used) - 1) & (used[b] # -1) DO + IF used[b] = i THEN RETURN TRUE END; + INC(b) + END; + RETURN FALSE + END IsUsed; + + PROCEDURE GetBlockFor(blocks: ARRAY OF STRING; c: CHAR): LONGINT; + VAR + i: LONGINT; + BEGIN + i := 0; + WHILE (i < LEN(blocks)) DO + IF (blocks[i].IndexOf(c,0) >= 0) & (~IsUsed(i)) THEN RETURN i END; + INC(i) + END; + + RETURN -1; + END GetBlockFor; + + BEGIN + FOR i := 0 TO LEN(used) - 1 DO used[i] := -1 END; + wChars := w(Object.String8).CharsLatin1(); + + i := 0; + WHILE (i < LEN(wChars^) - 1) DO + j := GetBlockFor(blocks,CAP(wChars[i])); + IF j < 0 THEN RETURN FALSE END; + used[i] := j; + INC(i) + END; + RETURN TRUE + END CanMakeWord; + +BEGIN + blocks[0] := "BO"; + blocks[1] := "XK"; + blocks[2] := "DQ"; + blocks[3] := "CP"; + blocks[4] := "NA"; + blocks[5] := "GT"; + blocks[6] := "RE"; + blocks[7] := "TG"; + blocks[8] := "QD"; + blocks[9] := "FS"; + blocks[10] := "JW"; + blocks[11] := "HU"; + blocks[12] := "VI"; + blocks[13] := "AN"; + blocks[14] := "OB"; + blocks[15] := "ER"; + blocks[16] := "FS"; + blocks[17] := "LY"; + blocks[18] := "PC"; + blocks[19] := "ZM"; + + Out.String("A: ");Out.Bool(CanMakeWord("A"));Out.Ln; + Out.String("BARK: ");Out.Bool(CanMakeWord("BARK"));Out.Ln; + Out.String("BOOK: ");Out.Bool(CanMakeWord("BOOK"));Out.Ln; + Out.String("TREAT: ");Out.Bool(CanMakeWord("TREAT"));Out.Ln; + Out.String("COMMON: ");Out.Bool(CanMakeWord("COMMON"));Out.Ln; + Out.String("SQAD: ");Out.Bool(CanMakeWord("SQUAD"));Out.Ln; + Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln; +END ABCBlocks. diff --git a/Task/ABC-Problem/PHP/abc-problem.php b/Task/ABC-Problem/PHP/abc-problem.php new file mode 100644 index 0000000000..14d5f206b3 --- /dev/null +++ b/Task/ABC-Problem/PHP/abc-problem.php @@ -0,0 +1,29 @@ + $block) { + if (strpos($block, $char) !== FALSE) { + unset($blocks[$k]); + continue(2); + } + } + return false; + } + return true; +} + +foreach ($words as $word) { + echo $word.': '; + echo canMakeWord($word) ? "True" : "False"; + echo "\r\n"; +} diff --git a/Task/ABC-Problem/PL-I/abc-problem-1.pli b/Task/ABC-Problem/PL-I/abc-problem-1.pli new file mode 100644 index 0000000000..3592b2aec8 --- /dev/null +++ b/Task/ABC-Problem/PL-I/abc-problem-1.pli @@ -0,0 +1,25 @@ +ABC: procedure options (main); /* 12 January 2014 */ + + declare word character (20) varying, blocks character (200) varying initial + ('((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) + (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M))'); + declare tblocks character (200) varying; + declare (true value ('1'b), false value ('0'b), flag) bit (1); + declare ch character (1); + declare (i, k) fixed binary; + + do word = 'A', 'BARK', 'BOOK', 'TREAT', 'COMMON', 'SQuAd', 'CONFUSE'; + flag = true; + tblocks = blocks; + do i = 1 to length(word); + ch = substr(word, i, 1); + k = index(tblocks, uppercase(ch)); + if k = 0 then + flag = false; + else /* Found a block with the letter on it. */ + substr(tblocks, k-1, 4) = ' '; /* Delete the block. */ + end; + if flag then put skip list (word, 'true'); else put skip list (word, 'false'); + end; + +end ABC; diff --git a/Task/ABC-Problem/PL-I/abc-problem-2.pli b/Task/ABC-Problem/PL-I/abc-problem-2.pli new file mode 100644 index 0000000000..7e1907395b --- /dev/null +++ b/Task/ABC-Problem/PL-I/abc-problem-2.pli @@ -0,0 +1,121 @@ +*process source attributes xref or(!) options nest; + abc: Proc Options(main); + /* REXX -------------------------------------------------------------- + * 10.01.2013 Walter Pachl counts the number of possible ways + * translated from Rexx version 2 + *-------------------------------------------------------------------*/ + + Dcl (ADDR,HBOUND,INDEX,LEFT,LENGTH,MAX,SUBSTR,TRANSLATE) builtin; + Dcl sysprint Print; + Dcl (i,j,k,m,mm,wi,wj,wlen,ways,lw) Bin Fixed(15); + Dcl blocks(20) Char(2) + Init('BO','XK','DQ','CP','NA','GT','RE','TG','QD','FS','JW', + 'HU','VI','AN','OB','ER','FS','LY','PC','ZM'); + Dcl blk Char(2); + Dcl words(8) Char(7) Var + Init('$','A','baRk','bOOk','trEat','coMMon','squaD','conFuse'); + Dcl word Char(7) Var; + Dcl c Char(1); + Dcl (show,cannot) Bit(1) Init('0'b); + Dcl poss(100,0:100) Pic'99'; poss=0; + Dcl s(20,100) char(100) Var; + Dcl str Char(100); + Dcl 1 *(30) Based(addr(str)), + 2 strp Pic'99', + 2 * Char(1); + Dcl ns(20) Bin Fixed(15) Init((20)0); + Dcl ol(100) Char(100) Var; + Dcl os Char(100) Var; + wlen=0; + Dcl lower Char(26) Init('abcdefghijklmnopqrstuvwxyz'); + Dcl upper Char(26) Init('ABCDEFGHIJKLMNOPQRSTUVWXYZ'); + Do wi=1 To hbound(words); + wlen=max(wlen,length(words(wi))); + End; + Do wi=1 To hbound(words); + word = translate(words(wi),upper,lower); + ways=0; + lw=length(word); + cannot='0'b; + poss=0; + ns=0; + ol=''; + iloop: + Do i=1 To lw; /* loop over the characters */ + c=substr(word,i,1); /* the current character */ + Do j=1 To hbound(blocks); /* loop over blocks */ + blk=blocks(j); + If index(blk,c)>0 Then Do; /* block can be used in this pos( */ + poss(i,0)+=1; /* number of possible blocks for pos i */ + poss(i,poss(i,0))=j; + End; + End; + If poss(i,0)=0 Then Do; + Leave iloop; + End; + End; + If i>lw Then Do; /* no prohibitive character */ + ns=0; + Do j=1 To poss(1,0); /* build possible strings for char 1 */ + ns(1)+=1;; + s(1,j)=poss(1,j); + End; + Do m=2 To lw; /* build possible strings for chars 1 to i */ + mm=m-1; + Do j=1 To ns(mm); + Do k=1 To poss(m,0); + ns(m)+=1; + s(m,ns(m))=s(mm,j)!!' '!!poss(m,k); + End; + End; + End; + Do m=1 To ns(lw); + If valid(s(lw,m)) Then Do; + ways+=1; + str=s(lw,m); + Do k=1 To lw; + ol(ways)=ol(ways)!!blocks(strp(k))!!' '; + End; + End; + End; + End; + /*-------------------------------------------------------------------- + * now show the result + *-------------------------------------------------------------------*/ + os=left(''''!!word!!'''',wlen+2); + Select; + When(ways=0) + os=os!!' cannot be spelt.'; + When(ways=1) + os=os!!' can be spelt.'; + Otherwise + os=os!!' can be spelt in'!!ways!!' ways.'; + End; + Put Skip List(os); + If show Then Do; + Do wj=1 To ways; + Put Edit(' '!!ol(wj))(Skip,a); + End; + End; + End; + Return; + + valid: Procedure(list) Returns(bit(1)); + /*-------------------------------------------------------------------- + * Check if the same block is used more than once -> 0 + * Else: the combination is valid + *-------------------------------------------------------------------*/ + Dcl list Char(*) Var; + Dcl i Bin Fixed(15); + Dcl used(20) Bit(1); + str=list; + used='0'b; + Do i=1 To lw; + If used(strp(i)) Then + Return('0'b); + used(strp(i))='1'b; + End; + Return('1'b); + End; + + End; diff --git a/Task/ABC-Problem/Perl-6/abc-problem.pl6 b/Task/ABC-Problem/Perl-6/abc-problem.pl6 new file mode 100644 index 0000000000..0f331a2891 --- /dev/null +++ b/Task/ABC-Problem/Perl-6/abc-problem.pl6 @@ -0,0 +1,21 @@ +multi can-spell-word(Str $word, @blocks) { + my @regex = @blocks.map({ EVAL "/{.comb.join('|')}/" }).grep: { .ACCEPTS($word.uc) } + can-spell-word $word.uc.comb, @regex; +} + +multi can-spell-word([$head,*@tail], @regex) { + for @regex -> $re { + if $head ~~ $re { + return True unless @tail; + return False if @regex == 1; + return True if can-spell-word @tail, @regex.grep: * !=== $re; + } + } + False; +} + +my @b = ; + +for { + say "$_ &can-spell-word($_, @b)"; +} diff --git a/Task/ABC-Problem/Perl/abc-problem-1.pl b/Task/ABC-Problem/Perl/abc-problem-1.pl new file mode 100644 index 0000000000..ea2ee774f0 --- /dev/null +++ b/Task/ABC-Problem/Perl/abc-problem-1.pl @@ -0,0 +1,26 @@ +#!/usr/bin/perl +use warnings; +use strict; + + +sub can_make_word { + my ($word, @blocks) = @_; + $_ = uc join q(), sort split // for @blocks; + my %blocks; + $blocks{$_}++ for @blocks; + return _can_make_word(uc $word, %blocks) +} + + +sub _can_make_word { + my ($word, %blocks) = @_; + my $char = substr $word, 0, 1, q(); + + my @candidates = grep 0 <= index($_, $char), keys %blocks; + for my $candidate (@candidates) { + next if $blocks{$candidate} <= 0; + local $blocks{$candidate} = $blocks{$candidate} - 1; + return 1 if q() eq $word or _can_make_word($word, %blocks); + } + return +} diff --git a/Task/ABC-Problem/Perl/abc-problem-2.pl b/Task/ABC-Problem/Perl/abc-problem-2.pl new file mode 100644 index 0000000000..e16cfe094f --- /dev/null +++ b/Task/ABC-Problem/Perl/abc-problem-2.pl @@ -0,0 +1,13 @@ +use Test::More tests => 8; + +my @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM); +is(can_make_word("A", @blocks1), 1); +is(can_make_word("BARK", @blocks1), 1); +is(can_make_word("BOOK", @blocks1), undef); +is(can_make_word("TREAT", @blocks1), 1); +is(can_make_word("COMMON", @blocks1), undef); +is(can_make_word("SQUAD", @blocks1), 1); +is(can_make_word("CONFUSE", @blocks1), 1); + +my @blocks2 = qw(US TZ AO QA); +is(can_make_word('auto', @blocks2), 1); diff --git a/Task/ABC-Problem/PicoLisp/abc-problem.l b/Task/ABC-Problem/PicoLisp/abc-problem.l new file mode 100644 index 0000000000..2034d57658 --- /dev/null +++ b/Task/ABC-Problem/PicoLisp/abc-problem.l @@ -0,0 +1,33 @@ +(setq *Blocks + '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) + (T G) (Q D) (F S) (J W) (H U) (V I) (A N) + (O B) (E R) (F S) (L Y) (P C) (Z M) ) ) +(setq *Words '("" "1" "A" "BARK" "BOOK" "TREAT" + "Bbb" "COMMON" "SQUAD" "Confuse" + "abba" "ANBOCPDQERSFTGUVWXLZ") ) + +(de abc (W B) + (let Myblocks (copy B) + (fully + '((C) + (when (seek '((Lst) (member C (car Lst))) Myblocks) + (set @) + T ) ) + (chop (uppc W)) ) ) ) + +(de abcR (W B) + (nond + ((car W) T) + ((car B) NIL) + (NIL + (setq W (chop W)) + (let? I + (find + '((Lst) (member (uppc (car W)) Lst)) + B ) + (abcR (cdr W) (delete I B)) ) ) ) ) + +(for Word *Words + (println Word (abc Word *Blocks) (abcR Word *Blocks)) ) + +(bye) diff --git a/Task/ABC-Problem/PowerBASIC/abc-problem.powerbasic b/Task/ABC-Problem/PowerBASIC/abc-problem.powerbasic new file mode 100644 index 0000000000..ff524d89eb --- /dev/null +++ b/Task/ABC-Problem/PowerBASIC/abc-problem.powerbasic @@ -0,0 +1,155 @@ +#COMPILE EXE +#DIM ALL +' +' A B C p r o b l e m . b a s +' +' by Geary Chopoff +' for Chopoff Consulting and RosettaCode.org +' on 2014Jul23 +' +'2014Jul23 +' +'You are given a collection of ABC blocks. Just like the ones you had when you were a kid. +'There are twenty blocks with two letters on each block. You are guaranteed to have a complete +'alphabet amongst all sides of the blocks. The sample blocks are: +'((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M)) +'The goal of this task is to write a function that takes a string and can determine whether +'you can spell the word with the given collection of blocks. +' +'The rules are simple: +'1.Once a letter on a block is used that block cannot be used again +'2.The function should be case-insensitive +'3. Show your output on this page for the following words: +' A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE +'----------------------------------------------------------------------------- +' G l o b a l C o n s t a n t s +' +%Verbose = 0 'make this 1 to have a lot of feedback +%MAX_BLOCKS = 20 'total number of blocks +%MAX_SIDES = 2 'total number of sides containing a unique letter per block + +%MAX_ASC = 255 +%FALSE = 0 'this is correct because there is ONLY ONE value for FALSE +%TRUE = (NOT %FALSE) 'this is one of MANY values of TRUE! +$FLAG_TRUE = "1" +$FLAG_FALSE = "0" +'----------------------------------------------------------------------------- +' G l o b a l V a r i a b l e s +' +GLOBAL blk() AS STRING +'----------------------------------------------------------------------------- +'i n i t B l o c k s +' +' as we will use this array only once we build it each time program is run +' +SUB initBlocks + LOCAL j AS INTEGER + j=1 + blk(j)="BO" + j=j+1 + blk(j)="XK" + j=j+1 + blk(j)="DQ" + j=j+1 + blk(j)="CP" + j=j+1 + blk(j)="NA" + j=j+1 + blk(j)="GT" + j=j+1 + blk(j)="RE" + j=j+1 + blk(j)="TG" + j=j+1 + blk(j)="QD" + j=j+1 + blk(j)="FS" + j=j+1 + blk(j)="JW" + j=j+1 + blk(j)="HU" + j=j+1 + blk(j)="VI" + j=j+1 + blk(j)="AN" + j=j+1 + blk(j)="OB" + j=j+1 + blk(j)="ER" + j=j+1 + blk(j)="FS" + j=j+1 + blk(j)="LY" + j=j+1 + blk(j)="PC" + j=j+1 + blk(j)="ZM" + IF j <> %MAX_BLOCKS THEN + STDOUT "initBlocks:Error: j is not same as MAX_BLOCKS!",j,%MAX_BLOCKS + END IF +END SUB +'----------------------------------------------------------------------------- +' m a k e W o r d +' +FUNCTION makeWord(tryWord AS STRING) AS BYTE + LOCAL retTF AS BYTE + LOCAL j AS INTEGER + LOCAL s AS INTEGER 'which side of block we are looking at + LOCAL k AS INTEGER + LOCAL c AS STRING 'character in tryWord we are looking for + + + FOR j = 1 TO LEN(tryWord) + c = UCASE$(MID$(tryWord,j,1)) 'character we want to show with block + + retTF = %FALSE 'we assume this will fail + + FOR k = 1 TO %MAX_BLOCKS + IF LEN(blk(k)) = %MAX_SIDES THEN + FOR s = 1 TO %MAX_SIDES + IF c = MID$(blk(k),s,1) THEN + retTF = %TRUE 'this block has letter we want + blk(k) = "" 'remove this block from further consideration + EXIT FOR + END IF + NEXT s + END IF + IF retTF THEN EXIT FOR 'can go on to next character in word + NEXT k + IF ISFALSE retTF THEN EXIT FOR 'if character not found then all is done + NEXT j + + FUNCTION = retTF +END FUNCTION +'----------------------------------------------------------------------------- +' P B M A I N +' +FUNCTION PBMAIN () AS LONG + DIM blk(1 TO %MAX_BLOCKS, 1 TO %MAX_SIDES) AS STRING + LOCAL cmdLine AS STRING + + initBlocks 'setup global array of blocks + + cmdLine=COMMAND$ + IF LEN(cmdLine)= 0 THEN + STDOUT "Useage for ABCproblem Version 1.00:" + STDOUT "" + STDOUT " >ABCproblem tryThisWord" + STDOUT "" + STDOUT "Where tryThisWord is a word you want to see if"+STR$(%MAX_BLOCKS)+" blocks can make." + STDOUT "If word can be made TRUE is returned." + STDOUT "Otherwise FALSE is returned." + EXIT FUNCTION + END IF + + IF INSTR(TRIM$(cmdLine)," ") = 0 THEN + IF makeWord(cmdLine) THEN + STDOUT "TRUE" + ELSE + STDOUT "FALSE" + END IF + ELSE + STDOUT "Error:Missing word to try to make with blocks! <" & cmdLine & ">" + EXIT FUNCTION + END IF +END FUNCTION diff --git a/Task/ABC-Problem/Prolog/abc-problem.pro b/Task/ABC-Problem/Prolog/abc-problem.pro new file mode 100644 index 0000000000..99d543c21b --- /dev/null +++ b/Task/ABC-Problem/Prolog/abc-problem.pro @@ -0,0 +1,22 @@ +abc_problem :- + maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']). + + +abc_problem(Word) :- + L = [[b,o],[x,k],[d,q],[c,p],[n,a],[g,t],[r,e],[t,g],[q,d],[f,s], + [j,w],[h,u],[v,i],[a,n],[o,b],[e,r],[f,s],[l,y],[p,c],[z,m]], + + ( abc_problem(L, Word) + -> format('~w OK~n', [Word]) + ; format('~w KO~n', [Word])). + +abc_problem(L, Word) :- + atom_chars(Word, C_Words), + maplist(downcase_atom, C_Words, D_Words), + can_makeword(L, D_Words). + +can_makeword(_L, []). + +can_makeword(L, [H | T]) :- + ( select([H, _], L, L1); select([_, H], L, L1)), + can_makeword(L1, T). diff --git a/Task/ABC-Problem/Python/abc-problem-1.py b/Task/ABC-Problem/Python/abc-problem-1.py new file mode 100644 index 0000000000..355da9cc93 --- /dev/null +++ b/Task/ABC-Problem/Python/abc-problem-1.py @@ -0,0 +1,63 @@ +blocks = [("B", "O"), + ("X", "K"), + ("D", "Q"), + ("C", "P"), + ("N", "A"), + ("G", "T"), + ("R", "E"), + ("T", "G"), + ("Q", "D"), + ("F", "S"), + ("J", "W"), + ("H", "U"), + ("V", "I"), + ("A", "N"), + ("O", "B"), + ("E", "R"), + ("F", "S"), + ("L", "Y"), + ("P", "C"), + ("Z", "M")] + + +def can_make_word(word, block_collection=blocks): + """ + Return True if `word` can be made from the blocks in `block_collection`. + + >>> can_make_word("") + False + >>> can_make_word("a") + True + >>> can_make_word("bark") + True + >>> can_make_word("book") + False + >>> can_make_word("treat") + True + >>> can_make_word("common") + False + >>> can_make_word("squad") + True + >>> can_make_word("coNFused") + True + """ + if not word: + return False + + blocks_remaining = block_collection[:] + for char in word.upper(): + for block in blocks_remaining: + if char in block: + blocks_remaining.remove(block) + break + else: + return False + return True + + +if __name__ == "__main__": + import doctest + doctest.testmod() + print(", ".join("'%s': %s" % (w, can_make_word(w)) for w in + ["", "a", "baRk", "booK", "treat", + "COMMON", "squad", "Confused"])) diff --git a/Task/ABC-Problem/Python/abc-problem-2.py b/Task/ABC-Problem/Python/abc-problem-2.py new file mode 100644 index 0000000000..6e0a1569b8 --- /dev/null +++ b/Task/ABC-Problem/Python/abc-problem-2.py @@ -0,0 +1,25 @@ +BLOCKS = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'.split() + +def _abc(word, blocks): + for i, ch in enumerate(word): + for blk in (b for b in blocks if ch in b): + whatsleft = word[i + 1:] + blksleft = blocks[:] + blksleft.remove(blk) + if not whatsleft: + return True, blksleft + if not blksleft: + return False, blksleft + ans, blksleft = _abc(whatsleft, blksleft) + if ans: + return ans, blksleft + else: + break + return False, blocks + +def abc(word, blocks=BLOCKS): + return _abc(word.upper(), blocks)[0] + +if __name__ == '__main__': + for word in [''] + 'A BARK BoOK TrEAT COmMoN SQUAD conFUsE'.split(): + print('Can we spell %9r? %r' % (word, abc(word))) diff --git a/Task/ABC-Problem/Python/abc-problem-3.py b/Task/ABC-Problem/Python/abc-problem-3.py new file mode 100644 index 0000000000..16ba9fdad6 --- /dev/null +++ b/Task/ABC-Problem/Python/abc-problem-3.py @@ -0,0 +1,16 @@ +def mkword(w, b): + if not w: return [] + + c,w = w[0],w[1:] + for i in range(len(b)): + if c in b[i]: + m = mkword(w, b[0:i] + b[i+1:]) + if m != None: return [b[i]] + m + +def abc(w, blk): + return mkword(w.upper(), [a.upper() for a in blk]) + +blocks = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'.split() + +for w in ", A, bark, book, treat, common, SQUAD, conFUsEd".split(', '): + print '\'' + w + '\'' + ' ->', abc(w, blocks) diff --git a/Task/ABC-Problem/R/abc-problem-1.r b/Task/ABC-Problem/R/abc-problem-1.r new file mode 100644 index 0000000000..e20e0680eb --- /dev/null +++ b/Task/ABC-Problem/R/abc-problem-1.r @@ -0,0 +1,43 @@ +blocks <- rbind(c("B","O"), + c("X","K"), + c("D","Q"), + c("C","P"), + c("N","A"), + c("G","T"), + c("R","E"), + c("T","G"), + c("Q","D"), + c("F","S"), + c("J","W"), + c("H","U"), + c("V","I"), + c("A","N"), + c("O","B"), + c("E","R"), + c("F","S"), + c("L","Y"), + c("P","C"), + c("Z","M")) + +canMake <- function(x) { + x <- toupper(x) + used <- rep(FALSE, dim(blocks)[1L]) + charList <- strsplit(x, character(0)) + tryChars <- function(chars, pos, used, inUse=NA) { + if (pos > length(chars)) { + TRUE + } else { + used[inUse] <- TRUE + possible <- which(blocks == chars[pos] & !used, arr.ind=TRUE)[, 1L] + any(vapply(possible, function(possBlock) tryChars(chars, pos + 1, used, possBlock), logical(1))) + } + } + setNames(vapply(charList, tryChars, logical(1), 1L, used), x) +} +canMake(c("A", + "BARK", + "BOOK", + "TREAT", + "COMMON", + "SQUAD", + "CONFUSE")) diff --git a/Task/ABC-Problem/R/abc-problem-2.r b/Task/ABC-Problem/R/abc-problem-2.r new file mode 100644 index 0000000000..92e478a134 --- /dev/null +++ b/Task/ABC-Problem/R/abc-problem-2.r @@ -0,0 +1,21 @@ +canMakeNoRecursion <- function(x) { + x <- toupper(x) + charList <- strsplit(x, character(0)) + getCombos <- function(chars) { + charBlocks <- data.matrix(expand.grid(lapply(chars, function(char) which(blocks == char, arr.ind=TRUE)[, 1L]))) + charBlocks <- charBlocks[!apply(charBlocks, 1, function(row) any(duplicated(row))), , drop=FALSE] + if (dim(charBlocks)[1L] > 0L) { + t(apply(charBlocks, 1, function(row) apply(blocks[row, , drop=FALSE], 1, paste, collapse=""))) + } else { + character(0) + } + } + setNames(lapply(charList, getCombos), x) +} +canMakeNoRecursion(c("A", + "BARK", + "BOOK", + "TREAT", + "COMMON", + "SQUAD", + "CONFUSE")) diff --git a/Task/ABC-Problem/README b/Task/ABC-Problem/README new file mode 100644 index 0000000000..fbb90afaf2 --- /dev/null +++ b/Task/ABC-Problem/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/ABC_Problem diff --git a/Task/ABC-Problem/REXX/abc-problem-1.rexx b/Task/ABC-Problem/REXX/abc-problem-1.rexx new file mode 100644 index 0000000000..4e78f30afe --- /dev/null +++ b/Task/ABC-Problem/REXX/abc-problem-1.rexx @@ -0,0 +1,24 @@ +/*REXX pgm checks if a word list can be spelt from a pool of toy blocks.*/ +list = 'A bark bOOk treat common squaD conFuse' /*words can be any case.*/ +blocks = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' + do k=1 for words(list) /*traipse through list of words. */ + call spell word(list,k) /*show if word be spelt (or not).*/ + end /*k*/ /* [↑] tests each word in list. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SPELL subroutine────────────────────*/ +spell: procedure expose blocks; parse arg ox . 1 x . /*get word to spell*/ +z=blocks; upper x z; oz=z; p.=0; L=length(x) /*uppercase the blocks. */ + /* [↓] try to spell it.*/ + do try=1 for L; z=oz /*use a fresh copy of Z.*/ + do n=1 for L; y=substr(x,n,1) /*attempt another letter*/ + p.n=pos(y,z,1+p.n); if p.n==0 then iterate try /*¬ found? Try again.*/ + z=overlay(' ',z,p.n) /*mutate block──► onesy.*/ + do k=1 for words(blocks) /*scrub block pool (¬1s)*/ + if length(word(z,k))==1 then z=delword(z,k,1) /*1 char? Delete.*/ + end /*k*/ /* [↑] elide any onesy.*/ + if n==L then leave try /*the last letter spelt?*/ + end /*n*/ /* [↑] end of an attempt*/ + end /*try*/ /* [↑] end TRY permute.*/ + +say right(ox,30) right(word("can't can", (n==L)+1), 6) 'be spelt.' +return n==L /*also, return the flag.*/ diff --git a/Task/ABC-Problem/REXX/abc-problem-2.rexx b/Task/ABC-Problem/REXX/abc-problem-2.rexx new file mode 100644 index 0000000000..779f1645f2 --- /dev/null +++ b/Task/ABC-Problem/REXX/abc-problem-2.rexx @@ -0,0 +1,103 @@ +/* REXX --------------------------------------------------------------- +* 10.01.2014 Walter Pachl counts the number of possible ways +* 12.01.2014 corrected date and output +*--------------------------------------------------------------------*/ +show=(arg(1)<>'') +blocks = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' +list = '$ A baRk bOOk trEat coMMon squaD conFuse' +list=translate(list) +Do i=1 To words(blocks) + blkn.i=word(blocks,i)'-'i + blk.i=word(blocks,i) + End +w.='' +wlen=0 +Do i=1 To words(list) + w.i=word(list,i) + wlen=max(wlen,length(w.i)) + End +Do wi=0 To words(list) + word = w.wi + ways=0 + poss.=0 + lw=length(word) + cannot=0 + Do i=1 To lw /* loop over the characters */ + c=substr(word,i,1) /* the current character */ + Do j=1 To words(blocks) /* loop over blocks */ + blk=word(blocks,j) + If pos(c,blk)>0 Then Do /* block can be used in this position */ + z=poss.i.0+1 + poss.i.z=j + poss.i.0=z /* number of possible blocks for pos i */ + End + End + If poss.i.0=0 Then Do + cannot=1 + Leave i + End + End + + If cannot=0 Then Do /* no prohibitive character */ + s.=0 + Do j=1 To poss.1.0 /* build possible strings for char 1 */ + z=s.1.0+1 + s.1.z=poss.1.j + s.1.0=z + End + Do i=2 To lw /* build possible strings for chars 1 to i */ + ii=i-1 + Do j=1 To poss.i.0 + Do k=1 To s.ii.0 + z=s.i.0+1 + s.i.z=s.ii.k poss.i.j + s.i.0=z + End + End + End + Do p=1 To s.lw.0 /* loop through all possible strings */ + v=valid(s.lw.p) /* test if the string is valid*/ + If v Then Do /* it is */ + ways=ways+1 /* increment number of ways */ + way.ways='' /* and store the string's blocks */ + Do ii=1 To lw + z=word(s.lw.p,ii) + way.ways=way.ways blk.z + End + End + End + End +/*--------------------------------------------------------------------- +* now show the result +*--------------------------------------------------------------------*/ + ol=left(''''word'''',wlen+2) + Select + When ways=0 Then + ol=ol 'cannot be spelt' + When ways=1 Then + ol=ol 'can be spelt' + Otherwise + ol=ol 'can be spelt in' ways 'ways' + End + Say ol'.' + If show Then Do + Do wj=1 To ways + Say copies(' ',10) way.wj + End + End + End +Exit + +valid: Procedure +/*--------------------------------------------------------------------- +* Check if the same block is used more than once -> 0 +* Else: the combination is valid +*--------------------------------------------------------------------*/ + Parse Arg list + used.=0 + Do i=1 To words(list) + w=word(list,i) + If used.w Then Return 0 + used.w=1 + End + Return 1 diff --git a/Task/ABC-Problem/Racket/abc-problem.rkt b/Task/ABC-Problem/Racket/abc-problem.rkt new file mode 100644 index 0000000000..94ace663ef --- /dev/null +++ b/Task/ABC-Problem/Racket/abc-problem.rkt @@ -0,0 +1,43 @@ +#lang racket +(define block-strings + (list "BO" "XK" "DQ" "CP" "NA" + "GT" "RE" "TG" "QD" "FS" + "JW" "HU" "VI" "AN" "OB" + "ER" "FS" "LY" "PC" "ZM")) +(define BLOCKS (map string->list block-strings)) + +(define (can-make-word? w) + (define (usable-block blocks word-char) + (for/first ((b (in-list blocks)) #:when (memf (curry char-ci=? word-char) b)) b)) + + (define (inner word-chars blocks tried-blocks) + (cond + [(null? word-chars) #t] + [(usable-block blocks (car word-chars)) + => + (lambda (b) + (or + (inner (cdr word-chars) (append tried-blocks (remove b blocks)) null) + (inner word-chars (remove b blocks) (cons b tried-blocks))))] + [else #f])) + (inner (string->list w) BLOCKS null)) + +(define WORD-LIST '("" "A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE")) +(define (report-word w) + (printf "Can we make: ~a? ~a~%" + (~s w #:min-width 9) + (if (can-make-word? w) "yes" "no"))) + +(module+ main + (for-each report-word WORD-LIST)) + +(module+ test + (require rackunit) + (check-true (can-make-word? "")) + (check-true (can-make-word? "A")) + (check-true (can-make-word? "BARK")) + (check-false (can-make-word? "BOOK")) + (check-true (can-make-word? "TREAT")) + (check-false (can-make-word? "COMMON")) + (check-true (can-make-word? "SQUAD")) + (check-true (can-make-word? "CONFUSE"))) diff --git a/Task/ABC-Problem/RapidQ/abc-problem.rapidq b/Task/ABC-Problem/RapidQ/abc-problem.rapidq new file mode 100644 index 0000000000..3a6e61650a --- /dev/null +++ b/Task/ABC-Problem/RapidQ/abc-problem.rapidq @@ -0,0 +1,26 @@ +dim Blocks as string +dim InWord as string + +Function CanMakeWord (FInWord as string, FBlocks as string) as integer + dim WIndex as integer, BIndex as integer + + FBlocks = UCase$(FBlocks) - " " - "," + FInWord = UCase$(FInWord) + + for WIndex = 1 to len(FInWord) + BIndex = instr(FBlocks, FInWord[WIndex]) + + if BIndex then + FBlocks = Replace$(FBlocks,"**",iif(BIndex mod 2,BIndex,BIndex-1)) + else + Result = 0 + exit function + end if + next + + Result = 1 +end function + +InWord = "Confuse" +Blocks = "BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM" +showmessage "Can make: " + InWord + " = " + iif(CanMakeWord(InWord, Blocks), "True", "False") diff --git a/Task/ABC-Problem/Ruby/abc-problem.rb b/Task/ABC-Problem/Ruby/abc-problem.rb new file mode 100644 index 0000000000..08fe02a3c6 --- /dev/null +++ b/Task/ABC-Problem/Ruby/abc-problem.rb @@ -0,0 +1,7 @@ +words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << "" + +words.each do |word| + blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" + res = word.each_char.all?{|c| blocks.sub!(/\w?#{c}\w?/i, "")} #regexps can be interpolated like strings + puts "#{word.inspect}: #{res}" +end diff --git a/Task/ABC-Problem/Rust/abc-problem.rust b/Task/ABC-Problem/Rust/abc-problem.rust new file mode 100644 index 0000000000..7ae452408a --- /dev/null +++ b/Task/ABC-Problem/Rust/abc-problem.rust @@ -0,0 +1,33 @@ +#![feature(core, unicode)] +extern crate core; +extern crate unicode; + +use core::iter::repeat; +use core::str::StrExt; +use unicode::char::CharExt; + +fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool { + let c = word.char_at(index).to_uppercase(); + for i in range(0, blocks.len()) { + if !used[i] && blocks[i].chars().any(|s| s == c) { + used[i] = true; + if index == 0 || rec_can_make_word(index - 1, word, blocks, used) { + return true; + } + used[i] = false; + } + } + false +} + +fn can_make_word(word: &str, blocks: &[&str]) -> bool { + return rec_can_make_word(word.char_len() - 1, word, blocks, repeat(false).take(blocks.len()).collect::>().as_mut_slice()); +} + +fn main() { + let blocks = [("BO"), ("XK"), ("DQ"), ("CP"), ("NA"), ("GT"), ("RE"), ("TG"), ("QD"), ("FS"), ("JW"), ("HU"), ("VI"), ("AN"), ("OB"), ("ER"), ("FS"), ("LY"), ("PC"), ("ZM")]; + let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]; + for word in words.iter() { + println!("{} -> {}", word, can_make_word(word.as_slice(), blocks.as_slice())) + } +} diff --git a/Task/ABC-Problem/Scala/abc-problem.scala b/Task/ABC-Problem/Scala/abc-problem.scala new file mode 100644 index 0000000000..09af8540aa --- /dev/null +++ b/Task/ABC-Problem/Scala/abc-problem.scala @@ -0,0 +1,50 @@ +object AbcBlocks extends App { + + protected class Block(face1: Char, face2: Char) { + + def isFacedWith(that: Char) = { that == face1 || that == face2 } + override def toString() = face1.toString + face2 + } + protected object Block { + def apply(faces: String) = new Block(faces.head, faces.last) + } + + type word = Seq[Block] + + private val blocks = List(Block("BO"), Block("XK"), Block("DQ"), Block("CP"), Block("NA"), + Block("GT"), Block("RE"), Block("TG"), Block("QD"), Block("FS"), + Block("JW"), Block("HU"), Block("VI"), Block("AN"), Block("OB"), + Block("ER"), Block("FS"), Block("LY"), Block("PC"), Block("ZM")) + + private def isMakeable(word: String, blocks: word) = { + + def getTheBlocks(word: String, blocks: word) = { + + def inner(word: String, toCompare: word, rest: word, accu: word): word = { + if (word.isEmpty || rest.isEmpty || toCompare.isEmpty) accu + else if (toCompare.head.isFacedWith(word.head)) { + val restant = rest diff List(toCompare.head) + inner(word.tail, restant, restant, accu :+ toCompare.head) + } else inner(word, toCompare.tail, rest, accu) + } + inner(word, blocks, blocks, Nil) + } + + word.lengthCompare(getTheBlocks(word, blocks).size) == 0 + } + + val words = List("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSED", "ANBOCPDQERSFTGUVWXLZ") + // Automatic tests + assert(isMakeable(words(0), blocks)) + assert(isMakeable(words(1), blocks)) + assert(!isMakeable(words(2), blocks)) // BOOK not + assert(isMakeable(words(3), blocks)) + assert(!isMakeable(words(4), blocks)) // COMMON not + assert(isMakeable(words(5), blocks)) + assert(isMakeable(words(6), blocks)) + assert(isMakeable(words(7), blocks)) + + //words(7).mkString.permutations.foreach(s => assert(isMakeable(s, blocks))) + + words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made.")) +} diff --git a/Task/ABC-Problem/Seed7/abc-problem.seed7 b/Task/ABC-Problem/Seed7/abc-problem.seed7 new file mode 100644 index 0000000000..36ab406bda --- /dev/null +++ b/Task/ABC-Problem/Seed7/abc-problem.seed7 @@ -0,0 +1,34 @@ +$ include "seed7_05.s7i"; + +const func boolean: canMakeWords (in array string: blocks, in string: word) is func + result + var boolean: okay is FALSE; + local + var integer: index is 1; + begin + if word = "" then + okay := TRUE; + elsif length(blocks) <> 0 then + while index <= length(blocks) and not okay do + if blocks[index][1] = word[1] or blocks[index][2] = word[1] then + okay := canMakeWords(blocks[.. pred(index)] & blocks[succ(index) ..], word[2 ..]); + end if; + incr(index); + end while; + end if; + end func; + +const array string: blocks is [] ("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"); + +const func boolean: canMakeWords (in string: word) is + return canMakeWords(blocks, upper(word)); + +const proc: main is func + local + var string: word is ""; + begin + for word range [] ("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse") do + writeln(word rpad 10 <& canMakeWords(word)); + end for; + end func; diff --git a/Task/ABC-Problem/Smalltalk/abc-problem.st b/Task/ABC-Problem/Smalltalk/abc-problem.st new file mode 100644 index 0000000000..d6a10f2fbe --- /dev/null +++ b/Task/ABC-Problem/Smalltalk/abc-problem.st @@ -0,0 +1,21 @@ +ABCPuzzle>>test + #('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each | + Transcript crShow: each, ': ', (self solveFor: each) asString ] + +ABCPuzzle>>solveFor: letters + | blocks | + blocks := #('BO' 'XK' 'DQ' 'CP' 'NA' 'GT' 'RE' 'TG' 'QD' 'FS' 'JW' 'HU' 'VI' 'AN' 'OB' 'ER' 'FS' 'LY' 'PC' 'ZM'). + ^ self solveFor: letters asUppercase with: blocks asOrderedCollection + +ABCPuzzle>>solveFor: letters with: blocks + | l ldash matches | + letters isEmpty ifTrue: [ ^ true ]. + l := letters first. + ldash := letters allButFirst. + matches := blocks select: [ :b | b includes: l ]. + matches isEmpty ifTrue: [ ^ false ]. + matches do: [ :m | | bdash | + bdash := blocks copy. + bdash remove: m. + (self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ]. + ^ false diff --git a/Task/ABC-Problem/TUSCRIPT/abc-problem.tu b/Task/ABC-Problem/TUSCRIPT/abc-problem.tu new file mode 100644 index 0000000000..a380b44dd2 --- /dev/null +++ b/Task/ABC-Problem/TUSCRIPT/abc-problem.tu @@ -0,0 +1,18 @@ +set words = "A'BARK'BOOK'TREAT'COMMON'SQUAD'CONFUSE" +set result = * +loop word = words + set blocks = "BO'XK'DQ'CP'NA'GT'RE'TG'QD'FS'JW'HU'VI'AN'OB'ER'FS'LY'PC'ZM" + set wordx = split (word, |"~ (A B C) + ;; intern -- convert a string to an interned symbol "A" -> A + ;; tuples -- turn string into 1-element tuples: "ABC" -> ("A" "B" "C") + ;; square brackets around mapcar -- Lisp-1 style evaluation, allowing + ;; the intern function binding to be treated as a variable binding. + + (defun string-to-syms (str) + [mapcar intern (tuples 1 (upcase-str str))]) + + ;; Recursive part of algorithm working purely with Lisp symbols. + ;; alpha -- single symbol denoting a letter + ;; [alpha2blocks alpha] -- look up list of blocks for given letter + ;; (memq item list) -- is item a member of list, under eq equality? + ;; (remq item list) -- remove items from list which are eq to item. + + (defun can-make-word-guts (letters blocks) + (cond + ((null letters) t) + ((null blocks) nil) + (t (let ((alpha (first letters))) + (each ((bl [alpha2blocks alpha])) + (if (and (memq bl blocks) + (can-make-word-guts (rest letters) + (remq bl blocks))) + (return-from can-make-word-guts t))))))) + + (defun can-make-word (str) + (can-make-word-guts (string-to-syms str) blocks))) +@(repeat) +@w +@(output) +>>> can_make_word("@(upcase-str w)") +@(if (can-make-word w) "True" "False") +@(end) +@(end) diff --git a/Task/ABC-Problem/Tcl/abc-problem.tcl b/Task/ABC-Problem/Tcl/abc-problem.tcl new file mode 100644 index 0000000000..d3f4b8f321 --- /dev/null +++ b/Task/ABC-Problem/Tcl/abc-problem.tcl @@ -0,0 +1,21 @@ +package require Tcl 8.6 + +proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} { + set abc {{letters blocks abc} { + set rest [lassign $letters ch] + set i 0 + foreach blk $blocks { + if {$ch in $blk && (![llength $rest] + || [apply $abc $rest [lreplace $blocks $i $i] $abc])} { + return true + } + incr i + } + return false + }} + return [apply $abc [split $word ""] [lmap b $blocks {split $b ""}] $abc] +} + +foreach word {"" A BARK BOOK TREAT COMMON SQUAD CONFUSE} { + puts [format "Can we spell %9s? %s" '$word' [abc $word]] +} diff --git a/Task/ABC-Problem/UNIX-Shell/abc-problem.sh b/Task/ABC-Problem/UNIX-Shell/abc-problem.sh new file mode 100644 index 0000000000..c683d77800 --- /dev/null +++ b/Task/ABC-Problem/UNIX-Shell/abc-problem.sh @@ -0,0 +1,39 @@ +can_build_word() { + if [[ $1 ]]; then + can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM + else + return 1 + fi +} + +can_build_word_rec() { + [[ -z $1 ]] && return 0 + + local -u word=$1 # uppercase the first parameter + shift + local blocks=("$@") + + # see if we have a block for the first letter + local letter=${word:0:1} indices=() i + for (( i=0; i<${#blocks[@]}; i++ )); do + if [[ ${blocks[i]} == *$letter* ]]; then + indices+=($i) + fi + done + (( ${#indices[@]} == 0 )) && return 1 + + local tmp + for i in ${indices[@]}; do + tmp=( "${blocks[@]}" ) + unset "tmp[$i]" + can_build_word_rec "${word:1}" "${tmp[@]}" && return 0 + done + + return 1 +} + +words=( "" A BARK Book treat COMMON Squad confuse ) +for word in "${words[@]}"; do + can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no + printf "%s\t%s\n" "$word" $ans +done diff --git a/Task/AKS-test-for-primes/00DESCRIPTION b/Task/AKS-test-for-primes/00DESCRIPTION new file mode 100644 index 0000000000..9b1322f542 --- /dev/null +++ b/Task/AKS-test-for-primes/00DESCRIPTION @@ -0,0 +1,30 @@ +The [http://www.cse.iitk.ac.in/users/manindra/algebra/primality_v6.pdf AKS algorithm] for testing whether a number is prime is a +polynomial-time algorithm based on an elementary theorem about Pascal triangles. + +The theorem on which the test is based can be stated as follows: + +* a number p is prime if and only if all the coefficients of the polynomial expansion of +: (x-1)^p - (x^p - 1) +are divisible by p. + +For example, trying p=3: + +: (x-1)^3 - (x^3 - 1) += (x^3 -3x^2 +3x -1) - (x^3 - 1) += -3x^2 +3x + +:And all the coefficients are divisible by 3 so 3 is prime. + +;The task: +# Create a function/subroutine/method that given p generates the coefficients of the expanded polynomial representation of (x-1)^p. +# Use the function to show here the polynomial expansions of (x-1)^p for p in the range 0 to at least 7, inclusive. +# Use the previous function in creating another function that when given p returns whether p is prime using the theorem. +# Use your test to generate a list of all primes ''under'' 35. +# '''As a stretch goal''', generate all primes under 50 (Needs greater than 31 bit integers). + +;Note: +The task given here is related to the elementary theorem, not the actual AKS algorithm. Using the elementary theorem directly as a way of testing for primes is interesting as an exercise but impractical. + +;References: +* [https://en.wikipedia.org/wiki/AKS_primality_test Agrawal-Kayal-Saxena (AKS) primality test] (Wikipedia) +* [http://www.youtube.com/watch?v=HvMSRWTE2mI Fool-Proof Test for Primes] - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification. diff --git a/Task/AKS-test-for-primes/00META.yaml b/Task/AKS-test-for-primes/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/AKS-test-for-primes/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/AKS-test-for-primes/AutoHotkey/aks-test-for-primes.ahk b/Task/AKS-test-for-primes/AutoHotkey/aks-test-for-primes.ahk new file mode 100644 index 0000000000..9a9d1104d0 --- /dev/null +++ b/Task/AKS-test-for-primes/AutoHotkey/aks-test-for-primes.ahk @@ -0,0 +1,53 @@ +; 1. Create a function/subroutine/method that given p generates the coefficients of the expanded polynomial representation of (x-1)^p. +; Function modified from http://rosettacode.org/wiki/Pascal%27s_triangle#AutoHotkey +pascalstriangle(n=8) ; n rows of Pascal's triangle +{ + p := Object(), z:=Object() + Loop, % n + Loop, % row := A_Index + col := A_Index + , p[row, col] := row = 1 and col = 1 + ? 1 + : (p[row-1, col-1] = "" ; math operations on blanks return blanks; I want to assume zero + ? 0 + : p[row-1, col-1]) + - (p[row-1, col] = "" + ? 0 + : p[row-1, col]) + Return p +} + +; 2. Use the function to show here the polynomial expansions of p for p in the range 0 to at least 7, inclusive. +For k, v in pascalstriangle() +{ + s .= "`n(x-1)^" k-1 . "=" + For k, w in v + s .= "+" w "x^" k-1 +} +s := RegExReplace(s, "\+-", "-") +s := RegExReplace(s, "x\^0", "") +s := RegExReplace(s, "x\^1", "x") +Msgbox % clipboard := s + +; 3. Use the previous function in creating another function that when given p returns whether p is prime using the AKS test. +aks(n) +{ + isnotprime := False + For k, v in pascalstriangle(n+1)[n+1] + (k != 1 and k != n+1) ? isnotprime |= !(v // n = v / n) ; if any is not divisible, returns true + Return !isnotprime +} + +; 4. Use your AKS test to generate a list of all primes under 35. +i := 49 +p := pascalstriangle(i+1) +Loop, % i +{ + n := A_Index + isnotprime := False + For k, v in p[n+1] + (k != 1 and k != n+1) ? isnotprime |= !(v // n = v / n) ; if any is not divisible, returns true + t .= isnotprime ? "" : A_Index " " +} +Msgbox % t +Return diff --git a/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-1.bracmat b/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-1.bracmat new file mode 100644 index 0000000000..7f56cc4900 --- /dev/null +++ b/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-1.bracmat @@ -0,0 +1,27 @@ +( (forceExpansion=.1+!arg+-1) +& (expandx-1P=.forceExpansion$((x+-1)^!arg)) +& ( isPrime + = + . forceExpansion + $ (!arg^-1*(expandx-1P$!arg+-1*(x^!arg+-1))) + : ?+/*?+? + & ~` + | + ) +& out$"Polynomial representations of (x-1)^p for p <= 7 :" +& -1:?n +& whl + ' ( 1+!n:~>7:?n + & out$(str$("n=" !n ":") expandx-1P$!n) + ) +& 1:?n +& :?primes +& whl + ' ( 1+!n:~>50:?n + & ( isPrime$!n&!primes !n:?primes + | + ) + ) +& out$"2 <= Primes <= 50:" +& out$!primes +); diff --git a/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-2.bracmat b/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-2.bracmat new file mode 100644 index 0000000000..7ec0df5629 --- /dev/null +++ b/Task/AKS-test-for-primes/Bracmat/aks-test-for-primes-2.bracmat @@ -0,0 +1,9 @@ +( out$"Primes between 980 and 1000, short version:" +& 980:?n +& whl + ' ( !n+1:<1000:?n + & ( 1+!n^-1*((x+-1)^!n+-1*(x^!n+-1))+-1:?+/*?+? + | out$!n + ) + ) +); diff --git a/Task/AKS-test-for-primes/C/aks-test-for-primes.c b/Task/AKS-test-for-primes/C/aks-test-for-primes.c new file mode 100644 index 0000000000..cf35e19a90 --- /dev/null +++ b/Task/AKS-test-for-primes/C/aks-test-for-primes.c @@ -0,0 +1,51 @@ +#include +#include + +long long c[100]; + +void coef(int n) +{ + int i, j; + + if (n < 0 || n > 63) abort(); // gracefully deal with range issue + + for (c[i=0] = 1; i < n; c[0] = -c[0], i++) + for (c[1 + (j=i)] = 1; j > 0; j--) + c[j] = c[j-1] - c[j]; +} + +int is_prime(int n) +{ + int i; + + coef(n); + c[0] += 1, c[i=n] -= 1; + while (i-- && !(c[i] % n)); + + return i < 0; +} + +void show(int n) +{ + do printf("%+lldx^%d", c[n], n); while (n--); +} + +int main(void) +{ + int n; + + for (n = 0; n < 10; n++) { + coef(n); + printf("(x-1)^%d = ", n); + show(n); + putchar('\n'); + } + + printf("\nprimes (never mind the 1):"); + for (n = 1; n <= 63; n++) + if (is_prime(n)) + printf(" %d", n); + + putchar('\n'); + return 0; +} diff --git a/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj b/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj new file mode 100644 index 0000000000..377a586076 --- /dev/null +++ b/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj @@ -0,0 +1,18 @@ +(defn c + "kth coefficient of (x - 1)^n" + [n k] + (/ (apply *' (range n (- n k) -1)) + (apply *' (range k 0 -1)) + (if (and (even? k) (< k n)) -1 1))) + +(defn cs + "coefficient series for (x - 1)^n, k=[0..n]" + [n] + (map #(c n %) (range (inc n)))) + +(defn aks? [p] (->> (cs p) rest butlast (every? #(-> % (mod p) zero?)))) + +(println "coefficient series n (k[0] .. k[n])") +(doseq [n (range 10)] (println n (cs n))) +(println) +(println "primes < 50 per AKS:" (filter aks? (range 2 50))) diff --git a/Task/AKS-test-for-primes/CoffeeScript/aks-test-for-primes.coffee b/Task/AKS-test-for-primes/CoffeeScript/aks-test-for-primes.coffee new file mode 100644 index 0000000000..52fb636e4b --- /dev/null +++ b/Task/AKS-test-for-primes/CoffeeScript/aks-test-for-primes.coffee @@ -0,0 +1,39 @@ +pascal = () -> + a = [] + return () -> + if a.length is 0 then a = [1] + else + b = (a[i] + a[i+1] for i in [0 ... a.length - 1]) + a = [1].concat(b).concat [1] + +show = (a) -> + show_x = (e) -> + switch e + when 0 then "" + when 1 then "x" + else "x^#{e}" + + degree = a.length - 1 + str = "(x - 1)^#{degree} =" + sgn = 1 + + for i in [0...a.length] + str += ' ' + (if sgn > 0 then "+" else "-") + ' ' + a[i] + show_x(degree - i) + sgn = -sgn + + return str + +primerow = (row) -> + degree = row.length - 1 + row[1 ... degree].every (x) -> x % degree is 0 + +p = pascal() +console.log show p() for i in [0..7] + +p = pascal() +p(); p() # skip 0 and 1 + +primes = (i+1 for i in [1..49] when primerow p()) + +console.log "" +console.log "The primes upto 50 are: #{primes}" diff --git a/Task/AKS-test-for-primes/Common-Lisp/aks-test-for-primes.lisp b/Task/AKS-test-for-primes/Common-Lisp/aks-test-for-primes.lisp new file mode 100644 index 0000000000..6ccf10dcdc --- /dev/null +++ b/Task/AKS-test-for-primes/Common-Lisp/aks-test-for-primes.lisp @@ -0,0 +1,36 @@ +(defun coefficients (p) + (cond + ((= p 0) #(1)) + + (t (loop for i from 1 upto p + for result = #(1 -1) then (map 'vector + #'- + (concatenate 'vector result #(0)) + (concatenate 'vector #(0) result)) + finally (return result))))) + +(defun primep (p) + (cond + ((< p 2) nil) + + (t (let ((c (coefficients p))) + (decf (elt c 0)) + (loop for i from 0 upto (/ (length c) 2) + for x across c + never (/= (mod x p) 0)))))) + +(defun main () + (format t "# p: (x-1)^p for small p:~%") + (loop for p from 0 upto 7 + do (format t "~D: " p) + (loop for i from 0 + for x across (reverse (coefficients p)) + do (when (>= x 0) (format t "+")) + (format t "~D" x) + (if (> i 0) + (format t "X^~D " i) + (format t " "))) + (format t "~%")) + (loop for i from 0 to 50 + do (when (primep i) (format t "~D " i))) + (format t "~%")) diff --git a/Task/AKS-test-for-primes/D/aks-test-for-primes.d b/Task/AKS-test-for-primes/D/aks-test-for-primes.d new file mode 100644 index 0000000000..d2f0ac8d42 --- /dev/null +++ b/Task/AKS-test-for-primes/D/aks-test-for-primes.d @@ -0,0 +1,29 @@ +import std.stdio, std.range, std.algorithm, std.string, std.bigint; + +BigInt[] expandX1(in uint p) pure /*nothrow*/ { + if (p == 0) return [1.BigInt]; + typeof(return) r = [1.BigInt, BigInt(-1)]; + foreach (immutable _; 1 .. p) + r = zip(r~0.BigInt, 0.BigInt~r).map!(xy => xy[0]-xy[1]).array; + r.reverse(); + return r; +} + +bool aksTest(in uint p) pure /*nothrow*/ { + if (p < 2) return false; + auto ex = p.expandX1; + ex[0]++; + return !ex[0 .. $ - 1].any!(mult => mult % p); +} + +void main() { + "# p: (x-1)^p for small p:".writeln; + foreach (immutable p; 0 .. 12) + writefln("%3d: %s", p, p.expandX1.zip(iota(p + 1)).retro + .map!q{"%+dx^%d ".format(a[])}.join.replace("x^0", "") + .replace("^1 ", " ").replace("+", "+ ") + .replace("-", "- ").replace(" 1x", " x")[2 .. $]); + + "\nSmall primes using the AKS test:".writeln; + 101.iota.filter!aksTest.writeln; +} diff --git a/Task/AKS-test-for-primes/Erlang/aks-test-for-primes.erl b/Task/AKS-test-for-primes/Erlang/aks-test-for-primes.erl new file mode 100644 index 0000000000..28588baf35 --- /dev/null +++ b/Task/AKS-test-for-primes/Erlang/aks-test-for-primes.erl @@ -0,0 +1,39 @@ +#! /usr/bin/escript + +-import(lists, [all/2, seq/2, zip/2]). + +iterate(F, X) -> fun() -> [X | iterate(F, F(X))] end. + +take(0, _lazy) -> []; +take(N, Lazy) -> + [Value | Next] = Lazy(), + [Value | take(N-1, Next)]. + + +pascal() -> iterate(fun (Row) -> [1 | sum_adj(Row)] end, [1]). + +sum_adj([_] = L) -> L; +sum_adj([A, B | _] = Row) -> [A+B | sum_adj(tl(Row))]. + + +show_binomial(Row) -> + Degree = length(Row) - 1, + ["(x - 1)^", integer_to_list(Degree), " =", binomial_rhs(Row, 1, Degree)]. + +show_x(0) -> ""; +show_x(1) -> "x"; +show_x(N) -> [$x, $^ | integer_to_list(N)]. + +binomial_rhs([], _, _) -> []; +binomial_rhs([Coef | Coefs], Sgn, Exp) -> + SignChar = if Sgn > 0 -> $+; true -> $- end, + [$ , SignChar, $ , integer_to_list(Coef), show_x(Exp) | binomial_rhs(Coefs, -Sgn, Exp-1)]. + + +primerow(Row, N) -> all(fun (Coef) -> (Coef =:= 1) or (Coef rem N =:= 0) end, Row). + +main(_) -> + [io:format("~s~n", [show_binomial(Row)]) || Row <- take(8, pascal())], + io:format("~nThe primes upto 50: ~p~n", + [[N || {Row, N} <- zip(tl(tl(take(51, pascal()))), seq(2, 50)), + primerow(Row, N)]]). diff --git a/Task/AKS-test-for-primes/Go/aks-test-for-primes.go b/Task/AKS-test-for-primes/Go/aks-test-for-primes.go new file mode 100644 index 0000000000..6bd81a3487 --- /dev/null +++ b/Task/AKS-test-for-primes/Go/aks-test-for-primes.go @@ -0,0 +1,65 @@ +package main + +import "fmt" + +func bc(p int) []int64 { + c := make([]int64, p+1) + r := int64(1) + for i, half := 0, p/2; i <= half; i++ { + c[i] = r + c[p-i] = r + r = r * int64(p-i) / int64(i+1) + } + for i := p - 1; i >= 0; i -= 2 { + c[i] = -c[i] + } + return c +} + +func main() { + for p := 0; p <= 7; p++ { + fmt.Printf("%d: %s\n", p, pp(bc(p))) + } + for p := 2; p < 50; p++ { + if aks(p) { + fmt.Print(p, " ") + } + } + fmt.Println() +} + +var e = []rune("²³⁴⁵⁶⁷") + +func pp(c []int64) (s string) { + if len(c) == 1 { + return fmt.Sprint(c[0]) + } + p := len(c) - 1 + if c[p] != 1 { + s = fmt.Sprint(c[p]) + } + for i := p; i > 0; i-- { + s += "x" + if i != 1 { + s += string(e[i-2]) + } + if d := c[i-1]; d < 0 { + s += fmt.Sprintf(" - %d", -d) + } else { + s += fmt.Sprintf(" + %d", d) + } + } + return +} + +func aks(p int) bool { + c := bc(p) + c[p]-- + c[0]++ + for _, d := range c { + if d%int64(p) != 0 { + return false + } + } + return true +} diff --git a/Task/AKS-test-for-primes/Haskell/aks-test-for-primes.hs b/Task/AKS-test-for-primes/Haskell/aks-test-for-primes.hs new file mode 100644 index 0000000000..10b280c1d0 --- /dev/null +++ b/Task/AKS-test-for-primes/Haskell/aks-test-for-primes.hs @@ -0,0 +1,20 @@ +expand p = scanl (\z i -> z * (p-i+1) `div` i) 1 [1..p] + + +test p | p < 2 = False + | otherwise = and [mod n p == 0 | n <- init . tail $ expand p] + + +printPoly [1] = "1" +printPoly p = concat [ unwords [pow i, sgn (l-i), show (p!!(i-1))] + | i <- [l-1,l-2..1] ] where + l = length p + sgn i = if even i then "+" else "-" + pow i = take i "x^" ++ if i > 1 then show i else "" + + +main = do + putStrLn "-- p: (x-1)^p for small p" + putStrLn $ unlines [show i ++ ": " ++ printPoly (expand i) | i <- [0..10]] + putStrLn "-- Primes up to 100:" + print (filter test [1..100]) diff --git a/Task/AKS-test-for-primes/J/aks-test-for-primes-1.j b/Task/AKS-test-for-primes/J/aks-test-for-primes-1.j new file mode 100644 index 0000000000..ff08443623 --- /dev/null +++ b/Task/AKS-test-for-primes/J/aks-test-for-primes-1.j @@ -0,0 +1,2 @@ + binomialExpansion =: (!~ * _1 ^ 2 | ]) i.&.:<: NB. 1) Create a function that gives the coefficients of (x-1)^p. + testAKS =: 0 *./ .= ] | binomialExpansion NB. 3) Use that function to create another which determines whether p is prime using AKS. diff --git a/Task/AKS-test-for-primes/J/aks-test-for-primes-2.j b/Task/AKS-test-for-primes/J/aks-test-for-primes-2.j new file mode 100644 index 0000000000..e57ebad41e --- /dev/null +++ b/Task/AKS-test-for-primes/J/aks-test-for-primes-2.j @@ -0,0 +1,10 @@ + binomialExpansion&.> i. 8 NB. 2) show the polynomial expansions p in the range 0 to at 7 inclusive. ++-++--+----+-------+-----------+---------------+------------------+ +|0||_2|_3 3|_4 6 _4|_5 10 _10 5|_6 15 _20 15 _6|_7 21 _35 35 _21 7| ++-++--+----+-------+-----------+---------------+------------------+ + (#~ testAKS&> ) 2+i. 35 NB. 4) Generate a list of all primes under 35. +2 3 5 7 11 13 17 19 23 29 31 + (#~ testAKS&> ) 2+i. 50 NB. 5) [stretch] Generate all primes under 50 +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 + i.&.:(_1&p:) 50 NB. Double-check our results using built-in prime filter. +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 diff --git a/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes.js b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes.js new file mode 100644 index 0000000000..d7a7910d5a --- /dev/null +++ b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes.js @@ -0,0 +1,79 @@ +var i, p, pascal, primerow, primes, show, _i; + +pascal = function() { + var a; + a = []; + return function() { + var b, i; + if (a.length === 0) { + return a = [1]; + } else { + b = (function() { + var _i, _ref, _results; + _results = []; + for (i = _i = 0, _ref = a.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + _results.push(a[i] + a[i + 1]); + } + return _results; + })(); + return a = [1].concat(b).concat([1]); + } + }; +}; + +show = function(a) { + var degree, i, sgn, show_x, str, _i, _ref; + show_x = function(e) { + switch (e) { + case 0: + return ""; + case 1: + return "x"; + default: + return "x^" + e; + } + }; + degree = a.length - 1; + str = "(x - 1)^" + degree + " ="; + sgn = 1; + for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + str += ' ' + (sgn > 0 ? "+" : "-") + ' ' + a[i] + show_x(degree - i); + sgn = -sgn; + } + return str; +}; + +primerow = function(row) { + var degree; + degree = row.length - 1; + return row.slice(1, degree).every(function(x) { + return x % degree === 0; + }); +}; + +p = pascal(); + +for (i = _i = 0; _i <= 7; i = ++_i) { + console.log(show(p())); +} + +p = pascal(); + +p(); + +p(); + +primes = (function() { + var _j, _results; + _results = []; + for (i = _j = 1; _j <= 49; i = ++_j) { + if (primerow(p())) { + _results.push(i + 1); + } + } + return _results; +})(); + +console.log(""); + +console.log("The primes upto 50 are: " + primes); diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-1.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-1.maple new file mode 100644 index 0000000000..e82760b06e --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-1.maple @@ -0,0 +1,22 @@ +> for xpr in seq( expand( (x-1)^p ), p = 0 .. 7 ) do print( xpr ) end: + 1 + + x - 1 + + 2 + x - 2 x + 1 + + 3 2 + x - 3 x + 3 x - 1 + + 4 3 2 + x - 4 x + 6 x - 4 x + 1 + + 5 4 3 2 + x - 5 x + 10 x - 10 x + 5 x - 1 + + 6 5 4 3 2 + x - 6 x + 15 x - 20 x + 15 x - 6 x + 1 + + 7 6 5 4 3 2 + x - 7 x + 21 x - 35 x + 35 x - 21 x + 7 x - 1 diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-2.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-2.maple new file mode 100644 index 0000000000..ae2918dd85 --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-2.maple @@ -0,0 +1 @@ + polc := p -> [coeffs]( expand( (x-1)^p - (x^p-1) ) ): diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-3.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-3.maple new file mode 100644 index 0000000000..49dc774b48 --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-3.maple @@ -0,0 +1 @@ +prime? := n -> n > 1 and {op}( map( modp, polc( n ), n ) ) = {0} diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-4.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-4.maple new file mode 100644 index 0000000000..22916f30c2 --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-4.maple @@ -0,0 +1 @@ +prime? := (n::posint) -> n > 1 and {op}( map( modp, [coeffs]( expand( (x-1)^n - (x^n-1) ) ), n ) ) = {0} diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-5.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-5.maple new file mode 100644 index 0000000000..5f977da948 --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-5.maple @@ -0,0 +1,2 @@ +> evalb( seq( prime?(i), i = 1 .. 1000 ) = seq( isprime( i ), i = 1 .. 1000 ) ); + true diff --git a/Task/AKS-test-for-primes/Maple/aks-test-for-primes-6.maple b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-6.maple new file mode 100644 index 0000000000..4dab05cbe4 --- /dev/null +++ b/Task/AKS-test-for-primes/Maple/aks-test-for-primes-6.maple @@ -0,0 +1,2 @@ +> select( prime?, [seq](1..50) ); + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] diff --git a/Task/AKS-test-for-primes/Mathematica/aks-test-for-primes.math b/Task/AKS-test-for-primes/Mathematica/aks-test-for-primes.math new file mode 100644 index 0000000000..4806e2685b --- /dev/null +++ b/Task/AKS-test-for-primes/Mathematica/aks-test-for-primes.math @@ -0,0 +1,7 @@ +Print["powers of (x-1)"] +(x - 1)^( Range[0, 7]) // Expand // TableForm +Print["primes under 50"] +poly[p_] := (x - 1)^p - (x^p - 1) // Expand; +coefflist[p_Integer] := Coefficient[poly[p], x, #] & /@ Range[0, p - 1]; +AKSPrimeQ[p_Integer] := (Mod[coefflist[p] , p] // Union) == {0}; +Select[Range[1, 50], AKSPrimeQ] diff --git a/Task/AKS-test-for-primes/PARI-GP/aks-test-for-primes.pari b/Task/AKS-test-for-primes/PARI-GP/aks-test-for-primes.pari new file mode 100644 index 0000000000..588302154d --- /dev/null +++ b/Task/AKS-test-for-primes/PARI-GP/aks-test-for-primes.pari @@ -0,0 +1,5 @@ +getPoly(n)=('x-1)^n; +vector(8,n,getPoly(n-1)) +AKS_slow(n)=my(P=getPoly(n));for(i=1,n-1,if(polcoeff(P,i)%n,return(0))); 1; +AKS(n)=my(X=('x-1)*Mod(1,n));X^n=='x^n-1; +select(AKS, [1..50]) diff --git a/Task/AKS-test-for-primes/Pascal/aks-test-for-primes.pascal b/Task/AKS-test-for-primes/Pascal/aks-test-for-primes.pascal new file mode 100644 index 0000000000..048f436b40 --- /dev/null +++ b/Task/AKS-test-for-primes/Pascal/aks-test-for-primes.pascal @@ -0,0 +1,108 @@ +const + pasTriMax = 61; +type + tpasTri =array[0..pasTriMax] of UInt64; + +var + pasTri : tpasTri; + +procedure pastriangle(n:longInt); +//calculate the n'th line 0.. middle +var + j,k: longWord; +begin + pasTri[0] := 1; + j := 1; + while (j<=n) do + begin + inc(j); + k := j SHR 1; + pasTri[k] :=pasTri[k-1]; + For k := k downto 1 do + inc(pasTri[k],pasTri[k-1]); + end; +end; + +function CheckPrime(n:longWord):boolean; +var + i : integer; + res: boolean; +Begin + + IF n > pasTriMax then + begin + writeln(n,' is out of range '); + EXIT; + end; + + pastriangle(n); + res := true; + i := n shr 1; + while res AND (i >1) do + Begin + res := res AND(pasTri[i] mod n = 0); + dec(i); + end; + CheckPrime := res; +end; + +procedure ExpandPoly(n:longWord); +const + Vz :array[boolean] of char = ('+','-'); +var + j,k: longWord; + bVz: Boolean; +Begin + IF n < 2 then + Begin + IF n = 0 then + writeln('(x-1)^0 = 1') + else + writeln('(x-1)^1 = x-1'); + EXIT; + end; + + IF n > pasTriMax then + begin + writeln(n,' is out of range '); + EXIT; + end; + + pastriangle(n); + write('(x-1)^',n,' = '); + k := 0; + j := n; + bVz := false; + repeat + IF j=n then + write('x^',j) + else + write(Vz[bVz],pasTri[k],'*x^',j); + bVz := Not(bVz); + inc(k); + dec(j); + until k>= j; + k := j; + while k > 0 do + Begin + IF j <> 1 then + write(Vz[bVz],pasTri[k],'*x^',j) + else + write(Vz[bVz],pasTri[k],'*x'); + bVz := Not(bVz); + dec(k); + dec(j); + end; + write(Vz[bVz],pasTri[0]); + writeln; +end; + +var + n: LongWord; +Begin + For n := 0 to 9 do + ExpandPoly(n); + For n := 2 to pasTriMax do + IF CheckPrime(n) then + write(n:3); +end. diff --git a/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-1.pl6 b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-1.pl6 new file mode 100644 index 0000000000..c79e49e1f9 --- /dev/null +++ b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-1.pl6 @@ -0,0 +1,3 @@ +constant expansions = [1], [1,-1], -> @prior { [@prior,0 Z- 0,@prior] } ... *; + +sub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p } diff --git a/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-2.pl6 b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-2.pl6 new file mode 100644 index 0000000000..5fcbb0706e --- /dev/null +++ b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-2.pl6 @@ -0,0 +1,21 @@ +say ' p: (x-1)ᵖ'; +say '-----------'; + +sub super ($n) { + $n.trans: '0123456789' + => '⁰¹²³⁴⁵⁶⁷⁸⁹'; +} + +for ^13 -> $d { + say $d.fmt('%2i: '), ( + expansions[$d].kv.map: -> $i, $n { + my $p = $d - $i; + [~] gather { + take < + - >[$n < 0] ~ ' ' unless $p == $d; + take $n.abs unless $p == $d > 0; + take 'x' if $p > 0; + take super $p - $i if $p > 1; + } + } + ) +} diff --git a/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-3.pl6 b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-3.pl6 new file mode 100644 index 0000000000..ccefe36582 --- /dev/null +++ b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes-3.pl6 @@ -0,0 +1 @@ +print "\nPrimes up to 100:\n { grep &polyprime, 2..100 }\n"; diff --git a/Task/AKS-test-for-primes/Perl/aks-test-for-primes.pl b/Task/AKS-test-for-primes/Perl/aks-test-for-primes.pl new file mode 100644 index 0000000000..5dafc47c2c --- /dev/null +++ b/Task/AKS-test-for-primes/Perl/aks-test-for-primes.pl @@ -0,0 +1,29 @@ +use strict; +use warnings; +# Select one of these lines. Math::BigInt is in core, but quite slow. +use Math::BigInt; sub binomial { Math::BigInt->new(shift)->bnok(shift) } +# use Math::Pari "binomial"; +# use ntheory "binomial"; + +sub binprime { + my $p = shift; + return 0 unless $p >= 2; + # binomial is symmetric, so only test half the terms + for (1 .. ($p>>1)) { return 0 if binomial($p,$_) % $p } + 1; +} +sub coef { # For prettier printing + my($n,$e) = @_; + return $n unless $e; + $n = "" if $n==1; + $e==1 ? "${n}x" : "${n}x^$e"; +} +sub binpoly { + my $p = shift; + join(" ", coef(1,$p), + map { join("",("+","-")[($p-$_)&1]," ",coef(binomial($p,$_),$_)) } + reverse 0..$p-1 ); +} +print "expansions of (x-1)^p:\n"; +print binpoly($_),"\n" for 0..9; +print "Primes to 80: [", join(",", grep { binprime($_) } 2..80), "]\n"; diff --git a/Task/AKS-test-for-primes/PicoLisp/aks-test-for-primes.l b/Task/AKS-test-for-primes/PicoLisp/aks-test-for-primes.l new file mode 100644 index 0000000000..1fa3fdbe96 --- /dev/null +++ b/Task/AKS-test-for-primes/PicoLisp/aks-test-for-primes.l @@ -0,0 +1,20 @@ +(de pascal (N) + (let D 1 + (make + (for X (inc N) + (link D) + (setq D + (*/ D (- (inc N) X) (- X)) ) ) ) ) ) + +(for (X 0 (> 10 X) (inc X)) + (println X '-> (pascal X) ) ) + +(println + (filter + '((X) + (fully + '((Y) (=0 (% Y X))) + (cdr (head -1 (pascal X))) ) ) + (range 2 50) ) ) + +(bye) diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-1.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-1.pro new file mode 100644 index 0000000000..92a49575ac --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-1.pro @@ -0,0 +1,4 @@ + prime(P) :- + pascal([1,P|Xs]), + append(Xs, [1], Rest), + forall( member(X,Xs), 0 is X mod P). diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-2.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-2.pro new file mode 100644 index 0000000000..338aaf51df --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-2.pro @@ -0,0 +1,43 @@ +% To generate the n-th row of a Pascal triangle +% pascal(+N, Row) +pascal(0, [1]). +pascal(N, Row) :- + N > 0, optpascal( [1, N|Xs] ), + !, + pascalize( [1, N|Xs], Row ). + +pascalize( Opt, Row ) :- + % if Opt ends in a pair, then peel off the pair: + ( append(X, [R,R], Opt) -> true ; append(X, [R], Opt) ), + reverse(X, Rs), + append( Opt, Rs, Row ). + +% optpascal(-X) generates optpascal lines: +optpascal(X) :- + optpascal_successor( [], X). + +% optpascal_successor(+P, -Q) is true if Q is an optpascal list beneath the optpascal list P: +optpascal_successor(P, Q) :- + optpascal(P, NextP), + (Q = NextP ; optpascal_successor(NextP, Q)). + +% optpascal(+Row, NextRow) is true if Row and NextRow are adjacent rows in the Pascal triangle. +% optpascal(+Row, NextRow) where the optpascal representation is used +optpascal(X, [1|Y]) :- + add_pairs(X, Y). + +% add_pairs(+OptPascal, NextOptPascal) is a helper function for optpascal/2. +% Given one OptPascal list, it generates the next by adding adjacent +% items, but if the last two items are unequal, then their sum is +% repeated. This is intended to be a deterministic predicate, and to +% avoid a probable compiler limitation, we therefore use one cut. +add_pairs([], []). +add_pairs([X], [X]). +add_pairs([X,Y], Ans) :- + S is X + Y, + (X = Y -> Ans=[S] ; Ans=[S,S]), + !. % To overcome potential limitation of compiler + +add_pairs( [X1, X2, X3|Xs], [S|Ys]) :- + S is X1 + X2, + add_pairs( [X2, X3|Xs], Ys). diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-3.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-3.pro new file mode 100644 index 0000000000..41e31bd9b1 --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-3.pro @@ -0,0 +1,22 @@ +%%% Task 1: "A method to generate the coefficients of (1-X)^p" + +coefficients(N, Coefficients) :- + pascal(N, X), + alternate_signs(X, Coefficients). + +alternate_signs( [], [] ). +alternate_signs( [A], [A] ). +alternate_signs( [A,B | X], [A, MB | Y] ) :- + MB is -B, + alternate_signs(X,Y). + +%%% Task 2. "Show here the polynomial expansions of (x − 1)p for p in the range 0 to at least 7, inclusive." + +coefficients(Coefficients) :- + optpascal( Opt), + pascalize( Opt, Row ), + alternate_signs(Row, Coefficients). + + +% As required by the problem statement, but necessarily very inefficient: +:- between(0, 7, N), coefficients(N, Coefficients), writeln(Coefficients), fail ; true. diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-4.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-4.pro new file mode 100644 index 0000000000..736c8e0b63 --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-4.pro @@ -0,0 +1,11 @@ +%%% Task 3. Use the previous function in creating [sic] +%%% another function that when given p returns whether p is prime +%%% using the AKS test. + +% Even for testing whether a given number, N, is prime, +% this approach is inefficient, but here is a Prolog implementation: + + prime_test_per_requirements(N) :- + coefficients(N, [1|Coefficients]), + append(Cs, [_], Coefficients), + forall( member(C, Cs), 0 is C mod N). diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-5.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-5.pro new file mode 100644 index 0000000000..0aeb583a1a --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-5.pro @@ -0,0 +1 @@ + prime(N) :- optpascal([1,N|Xs]), forall( member(X,Xs), 0 is X mod N). diff --git a/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-6.pro b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-6.pro new file mode 100644 index 0000000000..40f1f62d26 --- /dev/null +++ b/Task/AKS-test-for-primes/Prolog/aks-test-for-primes-6.pro @@ -0,0 +1,11 @@ +%%% Task 4. Use your AKS test to generate a list of all primes under 35. + +:- prime(N), (N < 35 -> write(N), write(' '), fail ; nl). + +% Output: 1 2 3 5 7 11 13 17 19 23 29 31 + +%%% Task 5. As a stretch goal, generate all primes under 50. + +:- prime(N), (N < 50 -> write(N), write(' '), fail ; nl). + +% Output: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 diff --git a/Task/AKS-test-for-primes/Python/aks-test-for-primes-1.py b/Task/AKS-test-for-primes/Python/aks-test-for-primes-1.py new file mode 100644 index 0000000000..da7833f1ec --- /dev/null +++ b/Task/AKS-test-for-primes/Python/aks-test-for-primes-1.py @@ -0,0 +1,20 @@ +def expand_x_1(p): + ex = [1] + for i in range(p): + ex.append(ex[-1] * -(p-i) / (i+1)) + return ex[::-1] + +def aks_test(p): + if p < 2: return False + ex = expand_x_1(p) + ex[0] += 1 + return not any(mult % p for mult in ex[0:-1]) + + +print('# p: (x-1)^p for small p') +for p in range(12): + print('%3i: %s' % (p, ' '.join('%+i%s' % (e, ('x^%i' % n) if n else '') + for n,e in enumerate(expand_x_1(p))))) + +print('\n# small primes using the aks test') +print([p for p in range(101) if aks_test(p)]) diff --git a/Task/AKS-test-for-primes/Python/aks-test-for-primes-2.py b/Task/AKS-test-for-primes/Python/aks-test-for-primes-2.py new file mode 100644 index 0000000000..4e7140c616 --- /dev/null +++ b/Task/AKS-test-for-primes/Python/aks-test-for-primes-2.py @@ -0,0 +1,15 @@ +print(''' +{| class="wikitable" style="text-align:left;" +|+ Polynomial Expansions and AKS prime test +|- +! p +! (x-1)^p +|-''') +for p in range(12): + print('! %i\n| %s\n| %r\n|-' + % (p, + ' '.join('%s%s' % (('%+i' % e) if (e != 1 or not p or (p and not n) ) else '+', + (('x^{%i}' % n) if n > 1 else 'x') if n else '') + for n,e in enumerate(expand_x_1(p))), + aks_test(p))) +print('|}') diff --git a/Task/AKS-test-for-primes/README b/Task/AKS-test-for-primes/README new file mode 100644 index 0000000000..24614ea647 --- /dev/null +++ b/Task/AKS-test-for-primes/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/AKS_test_for_primes diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-1.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-1.rexx new file mode 100644 index 0000000000..31fa66cb02 --- /dev/null +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-1.rexx @@ -0,0 +1,49 @@ +/* REXX --------------------------------------------------------------- +* 09.02.2014 Walter Pachl +* 22.02.2014 WP fix 'accounting' problem (courtesy GS) +*--------------------------------------------------------------------*/ +c.=1 +Numeric Digits 100 +limit=200 +pl='' +mmm=0 +Do p=3 To limit + pm1=p-1 + c.p.1=1 + c.p.p=1 + Do j=2 To p-1 + jm1=j-1 + c.p.j=c.pm1.jm1+c.pm1.j + mmm=max(mmm,c.p.j) + End + End +Say '(x-1)**0 = 1' +do i=2 To limit + im1=i-1 + sign='+' + ol='(x-1)^'im1 '=' + Do j=i to 2 by -1 + If j=2 Then + term='x ' + Else + term='x^'||(j-1) + If j=i Then + ol=ol term + Else + ol=ol sign c.i.j'*'term + sign=translate(sign,'+-','-+') + End + If i<10 then + Say ol sign 1 + Do j=2 To i-1 + If c.i.j//(i-1)>0 Then + Leave + End + If j>i-1 Then + pl=pl (i-1) + End +Say ' ' +Say 'Primes:' subword(pl,2,27) +Say ' ' subword(pl,29) +Say 'Largest coefficient:' mmm +Say 'This has' length(mmm) 'digits' diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx new file mode 100644 index 0000000000..49977af5a2 --- /dev/null +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -0,0 +1,42 @@ +/*REXX pgm calculates primes via the Agrawal-Kayal-Saxena primality test*/ +parse arg top .; if top=='' then top=200 /*Not specified? Use default.*/ +oTop=top; tell=top<0; top=abs(top) /*TOP negative? Show expression.*/ +numeric digits max(9,top%3) /*define a dynamic number of digs*/ +@.=1; big=1 /*set all coefficients to unity. */ +#= /*define a list of prime numbers.*/ + do p=3 for top; pm=p-1; pp=p+1 /*PM & PP: used as a convenience.*/ + do m=2 to pp%2; mm=m-1 /*calc. coefficients for a power.*/ + @.p.m=@.pm.mm + @.pm.m; mh=pp-m /*calculate left side of coeff.*/ + @.p.mh=@.p.m /* " right " " " */ + if @.p.m>big then big=@.p.m /*This coefficient the biggest? */ + end /*m*/ /* [↑] The M DO loop does both*/ + end /*p*/ /* sides in the same loop, */ + /* saving a bunch of time. */ +if tell then say '(x-1)^0: 1' /*maybe show the first expression*/ +$.0='-'; $.1="+" /*$.x is the sign to be used.*/ + /* [↓] test for primality by ÷ */ + do n=2 for top; nh=n%2; nm=n-1 /*create expressions/find primes.*/ + do k=3 to nh until @.n.k//nm\==0 /*coefficients divisible by N-1 ?*/ + end /*k*/ /* [↑] skip the 1st & 2nd coeff.*/ + /* [↓] search for a good coeff. */ + if k>nh & nm\==1 & n\==5 then #=# nm /*add a number to the prime list.*/ + if \tell then iterate /*¬tell? Don't show expressions.*/ + s=1 /*S: is the sign indicator. */ + y='(x-1)^'nm": " /*define first part of expression*/ + /* [↓] create higher powers 1st.*/ + do j=n to 2 by -1; jm=j-1 /*JM is used as a convenience.*/ + if j==2 then exp='x' /*if power=1, don't show the pow.*/ + else exp='x^'jm /* ··· else show the power with ^*/ + if j==n then y=y exp /*no sign for the 1st expression.*/ + else y=y $.s @.n.j'∙'exp /*build the expression with sign.*/ + s=\s /*flip the sign in the expression*/ + end /*j*/ /* [↑] the sign (now) is 0 | 1,*/ + /* and is shown as - | + */ + say y $.s 1 /*just show first N expressions, */ + end /*n*/ /* [↑] ··· but only for neg TOP.*/ + say /* [↓] Has TOP a leading +? Show*/ +if left(oTop,1)=='+' then say top is 'prime.' /*tell is/isn't. */ + else say 'primes:' # /*display prime # list. */ +say /* [↓] size of big 'un.*/ +say 'Found ' words(#) ' primes and the largest coefficient has' , + length(big) "decimal digits." /*stick a fork in it, we're done.*/ diff --git a/Task/AKS-test-for-primes/Racket/aks-test-for-primes.rkt b/Task/AKS-test-for-primes/Racket/aks-test-for-primes.rkt new file mode 100644 index 0000000000..e4d9260d7c --- /dev/null +++ b/Task/AKS-test-for-primes/Racket/aks-test-for-primes.rkt @@ -0,0 +1,61 @@ +#lang racket +(require math/number-theory) + +;; 1. coefficients of expanded polynomial (x-1)^p +;; produces a vector because in-vector can provide a start +;; and stop (of 1 and p) which allow us to drop the (-1)^p +;; and the x^p terms, respectively. +;; +;; (vector-ref (coefficients p) e) is the coefficient for p^e +(define (coefficients p) + (for/vector ((e (in-range 0 (add1 p)))) + (define sign (expt -1 (- p e))) + (* sign (binomial p e)))) + +;; 2. Show the polynomial expansions from p=0 .. 7 (inclusive) +;; (it's possible some of these can be merged...) +(define (format-coefficient c e leftmost?) + (define (format-c.x^e c e) + (define +c (abs c)) + (match* (+c e) + [(_ 0) (format "~a" +c)] + [(1 _) (format "x^~a" e)] + [(_ _) (format "~ax^~a" +c e)])) + (define +/- (if (negative? c) "-" "+")) + (define +c.x^e (format-c.x^e c e)) + (match* (c e leftmost?) + [(0 _ _) ""] + [((? negative?) _ #t) (format "-~a" +c.x^e)] + [(_ _ #t) +c.x^e] + [(_ _ _) (format " ~a ~a" +/- +c.x^e)])) + +(define (format-polynomial cs) + (define cs-length (sequence-length cs)) + (apply + string-append + (reverse ; convention is to display highest exponent first + (for/list ((c cs) (e (in-naturals))) + (format-coefficient c e (= e (sub1 cs-length))))))) + +(for ((p (in-range 0 (add1 11)))) + (printf "p=~a: ~a~%" p (format-polynomial (coefficients p)))) + +;; 3. AKS primeality test +(define (prime?/AKS p) + (define cs (coefficients p)) + (and + (or (= (vector-ref cs 0) -1) ; c_0 = -1 -> c_0 - (-1) = 0 + (divides? p 2)) ; c_0 = 1 -> c_0 - (-1) = 2 -> divides? + (for/and ((c (in-vector cs 1 p))) (divides? p c)))) + +;; there is some discussion (see Discussion) about what to do with the perennial "1" +;; case. This is my way of saying that I'm ignoring it +(define lowest-tested-number 2) + +;; 4. list of numbers < 35 that are prime (note that 1 is prime +;; by the definition of the AKS test for primes): +(displayln (for/list ((i (in-range lowest-tested-number 35)) #:when (prime?/AKS i)) i)) + +;; 5. stretch goal: all prime numbers under 50 +(displayln (for/list ((i (in-range lowest-tested-number 50)) #:when (prime?/AKS i)) i)) +(displayln (for/list ((i (in-range lowest-tested-number 100)) #:when (prime?/AKS i)) i)) diff --git a/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-1.rb b/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-1.rb new file mode 100644 index 0000000000..a32f37c73e --- /dev/null +++ b/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-1.rb @@ -0,0 +1,18 @@ +require 'polynomial' + +def x_minus_1_to_the(p) + return Polynomial.new(-1,1)**p +end + +def prime?(p) + return false if p < 2 + (x_minus_1_to_the(p) - Polynomial.from_string("x**#{p}-1")).coefs.all?{|n| n%p==0} +end + +8.times do |n| + # the default Polynomial#to_s would be OK here; the substitutions just make the + # output match the other version below. + puts "(x-1)^#{n} = #{x_minus_1_to_the(n).to_s.gsub(/\*\*/,'^').gsub(/\*/,'')}" +end + +puts "\nPrimes below 50:", 50.times.select {|n| prime? n}.join(',') diff --git a/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-2.rb b/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-2.rb new file mode 100644 index 0000000000..f73a774b9c --- /dev/null +++ b/Task/AKS-test-for-primes/Ruby/aks-test-for-primes-2.rb @@ -0,0 +1,26 @@ +def x_minus_1_to_the(p) + p.times.inject([1]) do |ex, _| + ([0] + ex).zip(ex + [0]).map { |x,y| x - y } + end +end + +def prime?(p) + return false if p < 2 + coeff = x_minus_1_to_the(p) + coeff[0] += coeff.pop + coeff.all?{|n| n%p==0} +end + +8.times do |n| + puts "(x-1)^#{n} = " + + x_minus_1_to_the(n). + each_with_index. + map { |c, p| + if p.zero? then c.to_s + else + (c<0 ? " - " : " + ") + (c.abs==1 ? "x" : "#{c.abs}x") + (p==1 ? "" : "^#{p}") + end + }.join +end + +puts "\nPrimes below 50:", 50.times.select {|n| prime? n}.join(',') diff --git a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust new file mode 100644 index 0000000000..c60dccf84d --- /dev/null +++ b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust @@ -0,0 +1,38 @@ +//Rust 1.0.0-alpha +#![feature(core)] +extern crate core; + +use core::iter::repeat; + +fn aks_coefficients(k: usize) -> Vec { + let mut coefficients = repeat(0i64).take(k + 1).collect::>(); + coefficients[0] = 1; + for i in 1..(k + 1) { + coefficients[i] = -(1..i).fold(coefficients[0], |&mut: prev, j|{ + let old = coefficients[j]; + coefficients[j] = old - prev; + old + }); + } + coefficients +} + + +fn is_prime(p: usize) -> bool { + if p < 2 { + false + } else { + let c = aks_coefficients(p); + core::iter::range_inclusive(1, (c.len() - 1) / 2) + .all(|&:i| (c[i] % (p as i64)) == 0) + } +} + +fn main() { + for i in 0us..8 { + println!("{}: {:?}", i, aks_coefficients(i)); + } + for i in (1us..51).filter(|&: &i| is_prime(i)) { + print!("{} ", i); + } +} diff --git a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-2.rust b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-2.rust new file mode 100644 index 0000000000..9cd3c46cb7 --- /dev/null +++ b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-2.rust @@ -0,0 +1,12 @@ +fn aks_coefficients(k: usize) -> Vec { + if k == 0 { + vec![1i64] + } else { + let zero = Some(0i64); + range(1, k).fold(vec![1i64, -1], |r, _| { + let a = r.iter().chain(zero.iter()); + let b = zero.iter().chain(r.iter()); + a.zip(b).map(|(x, &y)| x-y).collect() + }) + } +} diff --git a/Task/AKS-test-for-primes/Scala/aks-test-for-primes.scala b/Task/AKS-test-for-primes/Scala/aks-test-for-primes.scala new file mode 100644 index 0000000000..e069d2c329 --- /dev/null +++ b/Task/AKS-test-for-primes/Scala/aks-test-for-primes.scala @@ -0,0 +1,30 @@ +def powerMin1(n: BigInt) = if (n % 2 == 0) BigInt(1) else BigInt(-1) + +val pascal = (( Vector(Vector(BigInt(1))) /: (1 to 50)) { (rows, i) => + val v = rows.head + val newVector = ((1 until v.length) map (j => + powerMin1(j+i) * (v(j-1).abs + v(j).abs)) + ).toVector + (powerMin1(i) +: newVector :+ powerMin1(i+v.length)) +: rows +}).reverse + +def poly2String(poly: Vector[BigInt]) = ((0 until poly.length) map { i => + (i, poly(i)) match { + case (0, c) => c.toString + case (_, c) => + (if (c >= 0) "+" else "-") + + (if (c == 1) "x" else c.abs + "x") + + (if (i == 1) "" else "^" + i) + } +}) mkString "" + +def isPrime(n: Int) = { + val poly = pascal(n) + poly.slice(1, poly.length - 1).forall(i => i % n == 0) +} + +for(i <- 0 to 7) { println( f"(x-1)^$i = ${poly2String( pascal(i) )}" ) } + +val primes = (2 to 50).filter(isPrime) +println +println(primes mkString " ") diff --git a/Task/AKS-test-for-primes/Scilab/aks-test-for-primes.scilab b/Task/AKS-test-for-primes/Scilab/aks-test-for-primes.scilab new file mode 100644 index 0000000000..bd06f3720e --- /dev/null +++ b/Task/AKS-test-for-primes/Scilab/aks-test-for-primes.scilab @@ -0,0 +1,67 @@ +clear +xdel(winsid()) + +stacksize('max') +sz=stacksize(); + +n=7; //For the expansion up to power of n +g=50; //For test of primes up to g + +function X = pascal(g) //Pascal´s triangle + X(1,1)=1; //Zeroth power + X(2,1)=1; //First power + X(2,2)=1; + for q=3:1:g+1 //From second power use this loop + X(q,1)=1; + X(q,q)=1; + for p=2:1:q-1 + X(q,p)=X(q-1,p-1)+X(q-1,p); + end + end +endfunction + +Z=pascal(g); //Generate Pascal's triangle up to g + +Q(0+1)="(x-1)^0 = 1"; //For nicer display +Q(1+1)="(x-1)^1 = x^1-1"; //For nicer display + +disp(Q(1)) +disp(Q(2)) + +function cf=coef(Z,q,p) //Return coeffiecents for nicer display of expansion without "ones" + if Z(q,p)==1 then + cf=""; + else + cf=string(Z(q,p)); + end +endfunction + +for q=3:n+1 //Generate and display the expansions + Q(q)=strcat(["(x-1)^",string(q-1)," = "]); + sing=""; //Sign of coeff. + for p=1:q-1 //Number of coefficients equals power minus 1 + Q(q)=strcat([Q(q),sing,coef(Z,q,p),"x^",string(q-p)]); + if sing=="-" then sing="+"; else sing="-"; end + end + Q(q)=strcat([Q(q),sing,string(1)]); + disp(Q(q)) + clear Q +end + +function prime=prime(Z,g) + prime="true"; + for p=2:g + if abs(floor(Z(g+1,p)/g)-Z(g+1,p)/g)>0 then + prime="false"; + break; + end + end +endfunction + +R="2"; //For nicer display +for r=3:g + if prime(Z,r)=="true" then + R=strcat([R, ", ",string(r)]); + end +end +disp(R) diff --git a/Task/AKS-test-for-primes/Seed7/aks-test-for-primes.seed7 b/Task/AKS-test-for-primes/Seed7/aks-test-for-primes.seed7 new file mode 100644 index 0000000000..f240c4f87b --- /dev/null +++ b/Task/AKS-test-for-primes/Seed7/aks-test-for-primes.seed7 @@ -0,0 +1,60 @@ +$ include "seed7_05.s7i"; + +const func array integer: expand_x_1 (in integer: p) is func + result + var array integer: ex is [] (1); + local + var integer: i is 0; + begin + for i range 0 to p - 1 do + ex := [] (ex[1] * -(p - i) div (i + 1)) & ex; + end for; + end func; + +const func boolean: aks_test (in integer: p) is func + result + var boolean: aks_test is FALSE; + local + var array integer: ex is 0 times 0; + var integer: idx is 0; + begin + if p >= 2 then + ex := expand_x_1(p); + ex[1] +:= 1; + for idx range 1 to pred(length(ex)) until ex[idx] rem p <> 0 do + noop; + end for; + aks_test := idx = length(ex); + end if; + end func; + +const proc: main is func + local + var integer: p is 0; + var integer: n is 0; + var integer: e is 0; + begin + writeln("# p: (x-1)^p for small p"); + for p range 0 to 11 do + write(p lpad 3 <& ": "); + for n key e range expand_x_1(p) do + write(" "); + if n >= 0 then + write("+"); + end if; + write(n); + if e > 1 then + write("x^" <& pred(e)); + end if; + end for; + writeln; + end for; + writeln; + writeln("# small primes using the aks test"); + for p range 0 to 61 do + if aks_test(p) then + write(p <& " "); + end if; + end for; + writeln; + end func; diff --git a/Task/AKS-test-for-primes/Tcl/aks-test-for-primes.tcl b/Task/AKS-test-for-primes/Tcl/aks-test-for-primes.tcl new file mode 100644 index 0000000000..4ac73142a7 --- /dev/null +++ b/Task/AKS-test-for-primes/Tcl/aks-test-for-primes.tcl @@ -0,0 +1,51 @@ +proc coeffs {p {signs 1}} { + set clist 1 + for {set i 0} {$i < $p} {incr i} { + set clist [lmap x [list 0 {*}$clist] y [list {*}$clist 0] { + expr {$x + $y} + }] + } + if {$signs} { + set s -1 + set clist [lmap c $clist {expr {[set s [expr {-$s}]] * $c}}] + } + return $clist +} +proc aksprime {p} { + if {$p < 2} { + return false + } + foreach c [coeffs $p 0] { + if {$c == 1} continue + if {$c % $p} { + return false + } + } + return true +} + +for {set i 0} {$i <= 7} {incr i} { + puts -nonewline "(x-1)^$i =" + set j $i + foreach c [coeffs $i] { + puts -nonewline [format " %+dx^%d" $c $j] + incr j -1 + } + puts "" +} + +set sub35primes {} +for {set i 1} {$i < 35} {incr i} { + if {[aksprime $i]} { + lappend sub35primes $i + } +} +puts "primes under 35: [join $sub35primes ,]" + +set sub50primes {} +for {set i 1} {$i < 50} {incr i} { + if {[aksprime $i]} { + lappend sub50primes $i + } +} +puts "primes under 50: [join $sub50primes ,]" diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION b/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION new file mode 100644 index 0000000000..ae3b02930b --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION @@ -0,0 +1,17 @@ +These define three classifications of positive integers based on their [[Proper divisors|proper divisors]]. + +Let P(n) be the sum of the proper divisors of n, where the proper divisors of n are all positive divisors of n other than n itself. +* if P(n) < n then n is classed as '''deficient''' ([https://oeis.org/A005100 OEIS A005100]). +* if P(n) == n then n is classed as '''perfect''' ([https://oeis.org/A000396 OEIS A000396]). +* if P(n) > n then n is classed as '''abundant''' ([https://oeis.org/A005101 OEIS A005101]). + +Example: 6 has proper divisors 1, 2, and 3. 1 + 2 + 3 = 6 so 6 is classed as a perfect number. + +;Task: +Calculate how many of the integers 1 to 20,000 inclusive are in each of the three classes and show the result here. + +;Cf. +* [[Aliquot sequence classifications]]. (The whole series from which this task is a subset). +* [[Proper divisors]] +* [[Amicable pairs]] +* [http://www.pleacher.com/mp/mlessons/algebra/mystic.html Numbers and Mysticism] diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/AutoHotkey/abundant,-deficient-and-perfect-number-classifications.ahk b/Task/Abundant,-deficient-and-perfect-number-classifications/AutoHotkey/abundant,-deficient-and-perfect-number-classifications.ahk new file mode 100644 index 0000000000..fcd4952d9a --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/AutoHotkey/abundant,-deficient-and-perfect-number-classifications.ahk @@ -0,0 +1,52 @@ +Loop +{ + m := A_index + ; getting factors===================== + loop % floor(sqrt(m)) + { + if ( mod(m, A_index) == "0" ) + { + if ( A_index ** 2 == m ) + { + list .= A_index . ":" + sum := sum + A_index + continue + } + if ( A_index != 1 ) + { + list .= A_index . ":" . m//A_index . ":" + sum := sum + A_index + m//A_index + } + if ( A_index == "1" ) + { + list .= A_index . ":" + sum := sum + A_index + } + } + } + ; Factors obtained above=============== + if ( sum == m ) && ( sum != 1 ) + { + result := "perfect" + perfect++ + } + if ( sum > m ) + { + result := "Abundant" + Abundant++ + } + if ( sum < m ) or ( m == "1" ) + { + result := "Deficient" + Deficient++ + } + if ( m == 20000 ) + { + MsgBox % "number: " . m . "`nFactors:`n" . list . "`nSum of Factors: " . Sum . "`nResult: " . result . "`n_______________________`nTotals up to: " . m . "`nPerfect: " . perfect . "`nAbundant: " . Abundant . "`nDeficient: " . Deficient + ExitApp + } + list := "" + sum := 0 +} + +esc::ExitApp diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c b/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c new file mode 100644 index 0000000000..869c90661e --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c @@ -0,0 +1,41 @@ +#include +#define d 0 +#define p 1 +#define a 2 +int main(){ + int sum_pd=0,i,j; + int try_max=0; + //1 is deficient by default and can add it deficient list + int count_list[3]={1,0,0}; + for(i=2;i<=20000;i++){ + //Set maximum to check for proper division + try_max=i/2; + //1 is in all proper division number + sum_pd=1; + for(j=2;ji){ + count_list[a]++; + continue; + } + count_list[p]++; + } + printf("\nThere are %d deficient,",count_list[d]); + printf(" %d perfect,",count_list[p]); + printf(" %d abundant numbers between 1 and 20000.\n",count_list[a]); +return 0; +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/D/abundant,-deficient-and-perfect-number-classifications.d b/Task/Abundant,-deficient-and-perfect-number-classifications/D/abundant,-deficient-and-perfect-number-classifications.d new file mode 100644 index 0000000000..b472bca318 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/D/abundant,-deficient-and-perfect-number-classifications.d @@ -0,0 +1,18 @@ +void main() /*@safe*/ { + import std.stdio, std.algorithm, std.range; + + static immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => + iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); + + enum Class { deficient, perfect, abundant } + + static Class classify(in uint n) pure nothrow @safe /*@nogc*/ { + immutable p = properDivs(n).sum; + with (Class) + return (p < n) ? deficient : ((p == n) ? perfect : abundant); + } + + enum rangeMax = 20_000; + //iota(1, 1 + rangeMax).map!classify.hashGroup.writeln; + iota(1, 1 + rangeMax).map!classify.array.sort().group.writeln; +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs b/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs new file mode 100644 index 0000000000..070060495b --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs @@ -0,0 +1,13 @@ +divisors :: (Integral a) => a -> [a] +divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] + +classOf :: (Integral a) => a -> Ordering +classOf n = compare (sum $ divisors n) n + +main :: IO () +main = do + let classes = map classOf [1 .. 20000 :: Int] + printRes w c = putStrLn $ w ++ (show . length $ filter (== c) classes) + printRes "deficient: " LT + printRes "perfect: " EQ + printRes "abundant: " GT diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-1.j b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-1.j new file mode 100644 index 0000000000..064c369417 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-1.j @@ -0,0 +1,2 @@ +factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ +properDivisors=: factors -. ] diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-2.j b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-2.j new file mode 100644 index 0000000000..f143869212 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-2.j @@ -0,0 +1,2 @@ + (- +/@properDivisors&>) 1+i.10 +1 1 2 1 4 0 6 1 5 2 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-3.j b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-3.j new file mode 100644 index 0000000000..b81e086dea --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-3.j @@ -0,0 +1,2 @@ + *(- +/@properDivisors&>) 1+i.30 +1 1 1 1 1 0 1 1 1 1 1 _1 1 1 1 1 1 _1 1 _1 1 1 1 _1 1 1 1 0 1 _1 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-4.j b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-4.j new file mode 100644 index 0000000000..361ff39705 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-4.j @@ -0,0 +1,2 @@ + #/.~ *(- +/@properDivisors&>) 1+i.20000 +15043 4 4953 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-5.j b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-5.j new file mode 100644 index 0000000000..1d6007de9b --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/J/abundant,-deficient-and-perfect-number-classifications-5.j @@ -0,0 +1,2 @@ + ~. *(- +/@properDivisors&>) 1+i.20000 +1 0 _1 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Mathematica/abundant,-deficient-and-perfect-number-classifications.math b/Task/Abundant,-deficient-and-perfect-number-classifications/Mathematica/abundant,-deficient-and-perfect-number-classifications.math new file mode 100644 index 0000000000..7daa1f089e --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Mathematica/abundant,-deficient-and-perfect-number-classifications.math @@ -0,0 +1,7 @@ +classify[n_Integer] := Sign[Total[Most@Divisors@n] - n] + +StringJoin[ + Flatten[Tally[ + Table[classify[n], {n, 20000}]] /. {-1 -> "deficient: ", + 0 -> " perfect: ", 1 -> " abundant: "}] /. + n_Integer :> ToString[n]] diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PL-I/abundant,-deficient-and-perfect-number-classifications.pli b/Task/Abundant,-deficient-and-perfect-number-classifications/PL-I/abundant,-deficient-and-perfect-number-classifications.pli new file mode 100644 index 0000000000..8408ef9a10 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PL-I/abundant,-deficient-and-perfect-number-classifications.pli @@ -0,0 +1,56 @@ +*process source xref; + apd: Proc Options(main); + p9a=time(); + Dcl (p9a,p9b) Pic'(9)9'; + Dcl cnt(3) Bin Fixed(31) Init((3)0); + Dcl x Bin Fixed(31); + Dcl pd(300) Bin Fixed(31); + Dcl sumpd Bin Fixed(31); + Dcl npd Bin Fixed(31); + Do x=1 To 20000; + Call proper_divisors(x,pd,npd); + sumpd=sum(pd,npd); + Select; + When(x1 Then Do; + If mod(n,2)=1 Then /* odd number */ + delta=2; + Else /* even number */ + delta=1; + Do d=1 To n/2 By delta; + If mod(n,d)=0 Then Do; + npd+=1; + pd(npd)=d; + End; + End; + End; + End; + + sum: Proc(pd,npd) Returns(Bin Fixed(31)); + Dcl (pd(300),npd) Bin Fixed(31); + Dcl sum Bin Fixed(31) Init(0); + Dcl i Bin Fixed(31); + Do i=1 To npd; + sum+=pd(i); + End; + Return(sum); + End; + + End; diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Pascal/abundant,-deficient-and-perfect-number-classifications.pascal b/Task/Abundant,-deficient-and-perfect-number-classifications/Pascal/abundant,-deficient-and-perfect-number-classifications.pascal new file mode 100644 index 0000000000..0bc967dad3 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Pascal/abundant,-deficient-and-perfect-number-classifications.pascal @@ -0,0 +1,11 @@ +type + tdpa = array[0..2] of LongWord; // 0 = deficient,1= perfect,2 = abundant +var + .. + DpaCnt : tdpa; +.. +in function Check + // SumOfProperDivs + s := DivSumField[i]-i; + //in Pascal boolean true == 1/false == 0 + inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]); diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Perl-6/abundant,-deficient-and-perfect-number-classifications.pl6 b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl-6/abundant,-deficient-and-perfect-number-classifications.pl6 new file mode 100644 index 0000000000..dfd1f3a358 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl-6/abundant,-deficient-and-perfect-number-classifications.pl6 @@ -0,0 +1,8 @@ +sub propdivsum (\x) { + [+] (1 if x > 1), gather for 2 .. x.sqrt.floor -> \d { + my \y = x div d; + if y * d == x { take d; take y unless y == d } + } +} + +say bag map { propdivsum($_) <=> $_ }, 1..20000 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-1.pl b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-1.pl new file mode 100644 index 0000000000..90d9289a70 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-1.pl @@ -0,0 +1,2 @@ +use ntheory qw/divisor_sum/; +say join " ", map { divisor_sum($_)-$_ <=> $_ } 1..30; diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-2.pl b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-2.pl new file mode 100644 index 0000000000..5eae5bf393 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Perl/abundant,-deficient-and-perfect-number-classifications-2.pl @@ -0,0 +1,4 @@ +use ntheory qw/divisor_sum/; +my %h; +$h{divisor_sum($_)-$_ <=> $_}++ for 1..20000; +say "Perfect: $h{0} Deficient: $h{-1} Abundant: $h{1}"; diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py new file mode 100644 index 0000000000..fef62aaa57 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py @@ -0,0 +1,15 @@ +>>> from proper_divisors import proper_divs +>>> from collections import Counter +>>> +>>> rangemax = 20000 +>>> +>>> def pdsum(n): +... return sum(proper_divs(n)) +... +>>> def classify(n, p): +... return 'perfect' if n == p else 'abundant' if p > n else 'deficient' +... +>>> classes = Counter(classify(n, pdsum(n)) for n in range(1, 1 + rangemax)) +>>> classes.most_common() +[('deficient', 15043), ('abundant', 4953), ('perfect', 4)] +>>> diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py new file mode 100644 index 0000000000..bf3832ad49 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py @@ -0,0 +1,26 @@ +#lang racket +(require "proper-divisors.rkt") +(define SCOPE 20000) + +(define P + (let ((P-v (vector))) + (λ (n) + (set! P-v (fold-divisors P-v n 0 +)) + (vector-ref P-v n)))) + +(define-values + (a d p) + (for/fold ((a 0) (d 0) (p 0)) + ((n (in-range SCOPE 0 -1))) ; doing this backwards initialises the memo + (match (- (P n) n) + [0 (values a d (add1 p))] ; perfect + [(? negative?) (values a (add1 d) p)] ; deficient + [(? positive?) (values (add1 a) d p)]))) ; abundant + +(printf #< n] += 1} +puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}" diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Scala/abundant,-deficient-and-perfect-number-classifications.scala b/Task/Abundant,-deficient-and-perfect-number-classifications/Scala/abundant,-deficient-and-perfect-number-classifications.scala new file mode 100644 index 0000000000..bb0b6fb49f --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Scala/abundant,-deficient-and-perfect-number-classifications.scala @@ -0,0 +1,6 @@ +def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) +def classifier(i: Int) = properDivisors(i).sum compare i +val groups = (1 to 20000).groupBy( classifier ) +println("Deficient: " + groups(-1).length) +println("Abundant: " + groups(1).length) +println("Perfect: " + groups(0).length + " (" + groups(0).mkString(",") + ")") diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/VBScript/abundant,-deficient-and-perfect-number-classifications.vb b/Task/Abundant,-deficient-and-perfect-number-classifications/VBScript/abundant,-deficient-and-perfect-number-classifications.vb new file mode 100644 index 0000000000..17ddc48cbf --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/VBScript/abundant,-deficient-and-perfect-number-classifications.vb @@ -0,0 +1,23 @@ +Deficient = 0 +Perfect = 0 +Abundant = 0 +For i = 1 To 20000 + sum = 0 + For n = 1 To 20000 + If n < i Then + If i Mod n = 0 Then + sum = sum + n + End If + End If + Next + If sum < i Then + Deficient = Deficient + 1 + ElseIf sum = i Then + Perfect = Perfect + 1 + ElseIf sum > i Then + Abundant = Abundant + 1 + End If +Next +WScript.Echo "Deficient = " & Deficient & vbCrLf &_ + "Perfect = " & Perfect & vbCrLf &_ + "Abundant = " & Abundant diff --git a/Task/Aliquot-sequence-classifications/00DESCRIPTION b/Task/Aliquot-sequence-classifications/00DESCRIPTION new file mode 100644 index 0000000000..9b9729b67a --- /dev/null +++ b/Task/Aliquot-sequence-classifications/00DESCRIPTION @@ -0,0 +1,29 @@ +An [[wp:Aliquot sequence|aliquot sequence]] of a positive integer K is defined recursively as the first member +being K and subsequent members being the sum of the [[Proper divisors]] of the previous term. + +:* If the terms eventually reach 0 then the series for K is said to '''terminate'''. + +:
There are several classifications for non termination: +:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''. +:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''. +:* If the N'th term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''. +:
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... +:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''. +:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''. + +:
And finally: +:* Some K form aliquot sequences that are not known to be either terminating or periodic. these K are to be called '''non-terminating'''.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140737488355328. + + +;Task: +# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. +# Use it to display the classification and sequences of the numbers one to ten inclusive. +# Use it to show the classification and sequences of the following integers, in order: +:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. + +Show all output on this page. + +;Cf. +* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). +* [[Proper divisors]] +* [[Amicable pairs]] diff --git a/Task/Aliquot-sequence-classifications/D/aliquot-sequence-classifications.d b/Task/Aliquot-sequence-classifications/D/aliquot-sequence-classifications.d new file mode 100644 index 0000000000..3a915675d2 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/D/aliquot-sequence-classifications.d @@ -0,0 +1,51 @@ +import std.stdio, std.range, std.algorithm, std.typecons, std.conv; + +auto properDivisors(in ulong n) pure nothrow @safe /*@nogc*/ { + return iota(1UL, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); +} + +enum pDivsSum = (in ulong n) pure nothrow @safe /*@nogc*/ => + n.properDivisors.sum; + +auto aliquot(in ulong n, + in size_t maxLen=16, + in ulong maxTerm=2UL^^47) pure nothrow @safe { + if (n == 0) + return tuple("Terminating", [0UL]); + ulong[] s = [n]; + size_t sLen = 1; + ulong newN = n; + + while (sLen <= maxLen && newN < maxTerm) { + newN = s.back.pDivsSum; + if (s.canFind(newN)) { + if (s[0] == newN) { + if (sLen == 1) { + return tuple("Perfect", s); + } else if (sLen == 2) { + return tuple("Amicable", s); + } else + return tuple(text("Sociable of length ", sLen), s); + } else if (s.back == newN) { + return tuple("Aspiring", s); + } else + return tuple(text("Cyclic back to ", newN), s); + } else if (newN == 0) { + return tuple("Terminating", s ~ 0); + } else { + s ~= newN; + sLen++; + } + } + + return tuple("Non-terminating", s); +} + +void main() { + foreach (immutable n; 1 .. 11) + writefln("%s: %s", n.aliquot[]); + writeln; + foreach (immutable n; [11, 12, 28, 496, 220, 1184, 12496, 1264460, + 790, 909, 562, 1064, 1488]) + writefln("%s: %s", n.aliquot[]); +} diff --git a/Task/Aliquot-sequence-classifications/Haskell/aliquot-sequence-classifications.hs b/Task/Aliquot-sequence-classifications/Haskell/aliquot-sequence-classifications.hs new file mode 100644 index 0000000000..944e015706 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Haskell/aliquot-sequence-classifications.hs @@ -0,0 +1,41 @@ +divisors :: (Integral a) => a -> [a] +divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] + +data Class + = Terminating + | Perfect + | Amicable + | Sociable + | Aspiring + | Cyclic + | Nonterminating + deriving (Show) + +aliquot :: (Integral a) => a -> [a] +aliquot 0 = [0] +aliquot n = n : (aliquot $ sum $ divisors n) + +classify :: (Num a, Eq a) => [a] -> Class +classify [] = Nonterminating +classify [0] = Terminating +classify [_] = Nonterminating +classify [a,b] + | a == b = Perfect + | b == 0 = Terminating + | otherwise = Nonterminating +classify x@(a:b:c:_) + | a == b = Perfect + | a == c = Amicable + | a `elem` (drop 1 x) = Sociable + | otherwise = + case classify (drop 1 x) of + Perfect -> Aspiring + Amicable -> Cyclic + Sociable -> Cyclic + d -> d + +main :: IO () +main = do + let cls n = let ali = take 16 $ aliquot n in (classify ali, ali) + mapM_ (print . cls) $ [1..10] ++ + [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] diff --git a/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-1.j b/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-1.j new file mode 100644 index 0000000000..89f9521754 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-1.j @@ -0,0 +1,5 @@ +proper_divisors =: [: */&> [: }: [: , [: { [: <@:({. ^ i.@:>:@:{:)";: [: |: 2 p: x: +aliquot =: ([: +/ proper_divisors) ::0: +rc_aliquot_sequence =: aliquot^:(i.16)&> +rc_classify =: [: {. ([;.1' invalid terminate non-terminating perfect amicable sociable aspiring cyclic') #~ (16 ~: #) , (6 > {:) , (([: +./ (2^47x)&<) +. (16 = #@:~.)) , (1 = #@:~.) , ((8&= , 1&<)@:{.@:(#/.~)) , ([: =/ _2&{.) , 1: +rc_display_aliquot_sequence =: (":,~' ',~rc_classify)@:rc_aliquot_sequence diff --git a/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-2.j b/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-2.j new file mode 100644 index 0000000000..4a9dda699c --- /dev/null +++ b/Task/Aliquot-sequence-classifications/J/aliquot-sequence-classifications-2.j @@ -0,0 +1,27 @@ + rc_display_aliquot_sequence&> >: i.10 + terminate 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 3 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 4 3 1 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 5 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + perfect 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 + terminate 7 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 8 7 1 0 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 9 4 3 1 0 0 0 0 0 0 0 0 0 0 0 0 + terminate 10 8 7 1 0 0 0 0 0 0 0 0 0 0 0 0 + + rc_display_aliquot_sequence&>11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080x + terminate 11 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... + terminate 12 16 15 9 4 3 1 0 0 0 0 0 0 0 0 0 ... + perfect 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 ... + perfect 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 496 ... + amicable 220 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 ... + amicable 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 ... + sociable 12496 14288 15472 14536 14264 12496 14288 15472 14536 14264 12496 14288 15472 14536 14264 12496 ... + sociable 1264460 1547860 1727636 1305184 1264460 1547860 1727636 1305184 1264460 1547860 1727636 1305184 1264460 1547860 1727636 1305184 ... + aspiring 790 650 652 496 496 496 496 496 496 496 496 496 496 496 496 496 ... + aspiring 909 417 143 25 6 6 6 6 6 6 6 6 6 6 6 6 ... + cyclic 562 284 220 284 220 284 220 284 220 284 220 284 220 284 220 284 ... + cyclic 1064 1336 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 1184 1210 ... + non-terminating 1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 ... + non-terminating 15355717786080 44534663601120 144940087464480 471714103310688 1130798979186912 2688948041357088 6050151708497568 13613157922639968 35513546724070632 74727605255142168 162658586225561832 353930992506879768 642678347124409032 112510261154846... diff --git a/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 b/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 new file mode 100644 index 0000000000..98f75eaf93 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 @@ -0,0 +1,34 @@ +sub propdivsum (\x) { + [+] x > 1, gather for 2 .. x.sqrt.floor -> \d { + my \y = x div d; + if y * d == x { take d; take y unless y == d } + } +} + +multi quality (0,1) { 'perfect ' } +multi quality (0,2) { 'amicable' } +multi quality (0,$n) { "sociable-$n" } +multi quality ($,1) { 'aspiring' } +multi quality ($,$n) { "cyclic-$n" } + +sub aliquotidian ($x) { + my %seen; + my @seq := $x, &propdivsum ... *; + for 0..16 -> $to { + my $this = @seq[$to] or return "$x terminating [@seq[^$to]]"; + last if $this > 140737488355328; + if %seen{$this}:exists { + my $from = %seen{$this}; + return "$x &quality($from, $to-$from) [@seq[^$to]]"; + } + %seen{$this} = $to; + } + "$x non-terminating"; + +} + +aliquotidian($_).say for + 1..10, + 11, 12, 28, 496, 220, 1184, 12496, 1264460, + 790, 909, 562, 1064, 1488, + 15355717786080; diff --git a/Task/Aliquot-sequence-classifications/Perl/aliquot-sequence-classifications.pl b/Task/Aliquot-sequence-classifications/Perl/aliquot-sequence-classifications.pl new file mode 100644 index 0000000000..6897c41ff7 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Perl/aliquot-sequence-classifications.pl @@ -0,0 +1,36 @@ +use ntheory qw/divisor_sum/; + +sub aliquot { + my($n, $maxterms, $maxn) = @_; + $maxterms = 16 unless defined $maxterms; + $maxn = 2**47 unless defined $maxn; + + my %terms = ($n => 1); + my @allterms = ($n); + for my $term (2 .. $maxterms) { + $n = divisor_sum($n)-$n; + # push onto allterms here if we want the cyclic term to display + last if $n > $maxn; + return ("terminates",@allterms, 0) if $n == 0; + if (defined $terms{$n}) { + return ("perfect",@allterms) if $term == 2 && $terms{$n} == 1; + return ("amicible",@allterms) if $term == 3 && $terms{$n} == 1; + return ("sociable-".($term-1),@allterms) if $term > 3 && $terms{$n} == 1; + return ("aspiring",@allterms) if $terms{$n} == $term-1; + return ("cyclic-".($term-$terms{$n}),@allterms) if $terms{$n} < $term-1; + } + $terms{$n} = $term; + push @allterms, $n; + } + ("non-term",@allterms); +} + +for my $n (1..10) { + my($class, @seq) = aliquot($n); + printf "%14d %10s [@seq]\n", $n, $class; +} +print "\n"; +for my $n (qw/11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080/) { + my($class, @seq) = aliquot($n); + printf "%14d %10s [@seq]\n", $n, $class; +} diff --git a/Task/Aliquot-sequence-classifications/Python/aliquot-sequence-classifications.py b/Task/Aliquot-sequence-classifications/Python/aliquot-sequence-classifications.py new file mode 100644 index 0000000000..027640469a --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Python/aliquot-sequence-classifications.py @@ -0,0 +1,41 @@ +from proper_divisors import proper_divs +from functools import lru_cache + + +@lru_cache() +def pdsum(n): + return sum(proper_divs(n)) + + +def aliquot(n, maxlen=16, maxterm=2**47): + if n == 0: + return 'terminating', [0] + s, slen, new = [n], 1, n + while slen <= maxlen and new < maxterm: + new = pdsum(s[-1]) + if new in s: + if s[0] == new: + if slen == 1: + return 'perfect', s + elif slen == 2: + return 'amicable', s + else: + return 'sociable of length %i' % slen, s + elif s[-1] == new: + return 'aspiring', s + else: + return 'cyclic back to %i' % new, s + elif new == 0: + return 'terminating', s + [0] + else: + s.append(new) + slen += 1 + else: + return 'non-terminating', s + +if __name__ == '__main__': + for n in range(1, 11): + print('%s: %r' % aliquot(n)) + print() + for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: + print('%s: %r' % aliquot(n)) diff --git a/Task/Aliquot-sequence-classifications/README b/Task/Aliquot-sequence-classifications/README new file mode 100644 index 0000000000..07a02fc175 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Aliquot_sequence_classifications diff --git a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx new file mode 100644 index 0000000000..ae16429c73 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx @@ -0,0 +1,62 @@ +/*REXX pgm classifies various positive integers for aliquot sequences. */ +parse arg low high L /*get optional arguments*/ +high=word(high low 10,1); low=word(low 1,1) /*get the LOW and HIGH. */ +if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 +big=2**47; NTlimit=16+1 /*limit: non-terminating*/ +numeric digits max(9, 1+length(big)) /*be able to handle // */ +@.=.; @.0=0; @.1=0 /*proper divisor sums. */ +say center('numbers from ' low " to " high, 79, "═") + + do n=low to high /*process probably some low nums.*/ + call classify_aliquot n /*call subroutine to classify it.*/ + end /*n*/ /* [↑] process a range of ints.*/ +say +say center('first numbers for each classification', 79, "═") +b.=0 /* [↓] ensure one of each class.*/ + do q=1 until b.sociable \== 0 /*only one that has to be counted*/ + call classify_aliquot -q /*the minus sign indicates ¬tell.*/ + b._=b._+1; if b._==1 then call show_class q,$ /*show 1st found.*/ + end /*q*/ /* [↑] until all classes found. */ +say +say center('classifications for specific numbers', 79, "═") + + do i=1 for words(L) /*L is a list of "special numbers*/ + call classify_aliquot word(L,i) /*call subroutine to classify it.*/ + end /*i*/ /* [↑] process a list of numbers*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CLASSIFY_ALIQUOT subroutine─────────*/ +classify_aliquot: parse arg a 1 aa; a=abs(a) /*get what # to be used.*/ +if @.a\==. then s=@.a /*Was number been summed before? */ + else s=SPdivs(a) /*No, then do it the hard way. */ +@.a=s; $=s /*define sum of the proper DIVs. */ +what='terminating' /*assume this classification kind*/ +c.=0; c.s=1 /*clear all cyclic seqs, set 1st.*/ +if $==a then what='perfect' /*check for "perfect" number. */ + else do t=1 while s\==0 /*loop until sum isn't 0 or >big.*/ + m=word($, words($)) /*obtain the last number in seq. */ + if @.m==. then s=SPdivs(m) /*if ¬defined, then sum Pdivs.*/ + else s=@.m /*use the previously found number*/ + if m==s & m\==0 then do; what='aspiring' ; leave; end + if word($,2)==a then do; what='amicable' ; leave; end + $=$ s /*append a sum to number sequence*/ + if s==a & t>3 then do; what='sociable' ; leave; end + if c.s & m\==0 then do; what='cyclic' ; leave; end + c.s=1 /*assign another possible cyclic.*/ + /* [↓] Rosetta Code's limit: >16*/ + if t>NTlimit then do; what='non-terminating'; leave; end + if s>big then do; what='NON-TERMINATING'; leave; end + end /*t*/ /* [↑] only permit within reason*/ +if aa>0 then call show_class a,$ /*only display if A is positive.*/ +return +/*──────────────────────────────────SHOW_CLASS subroutine───────────────*/ +show_class: say right(arg(1),digits()) 'is' center(what,15) arg(2); return +/*──────────────────────────────────SPDIVS subroutine───────────────────*/ +SPdivs: procedure expose @.; parse arg x; if x<2 then return 0; odd=x//2 +s=1 /* [↓] use only EVEN|ODD integers*/ + do j=2+odd by 1+odd while j*j n SCOPE) + (apply + (drop-right (divisors n) 1))] + [else + (set! P-v (fold-divisors P-v n 0 +)) + (vector-ref P-v n)])))) + +;; initialise P-v +(void (P SCOPE)) + +(define (aliquot-sequence-class K) + ;; note that seq is reversed as a list, since we're consing + (define (inr-asc seq) + (match seq + [(list 0 _ ...) + (values "terminating" seq)] + [(list (== K) (== K) _ ...) + (values "perfect" seq)] + [(list n n _ ...) + (values (format "aspiring to ~a" n) seq)] + [(list (== K) ami (== K) _ ...) + (values (format "amicable with ~a" ami) seq)] + [(list (== K) cycle ... (== K)) + (values (format "sociable length ~a" (add1 (length cycle))) seq)] + [(list n cycle ... n _ ...) + (values (format "cyclic on ~a length ~a" n (add1 (length cycle))) seq)] + [(list X _ ...) + #:when (> X 140737488355328) + (values "non-terminating big number" seq)] + [(list seq ...) + #:when (> (length seq) 16) + (values "non-terminating long sequence" seq)] + [(list seq1 seq ...) (inr-asc (list* (P seq1) seq1 seq))])) +(inr-asc (list K))) + +(define (report-aliquot-sequence-class n) + (define-values (c s) (aliquot-sequence-class n)) + (printf "~a:\t~a\t~a~%" n c (reverse s))) + +(for ((i (in-range 1 10))) + (report-aliquot-sequence-class i)) +(newline) + +(for ((i (in-list '(11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080)))) + (report-aliquot-sequence-class i)) diff --git a/Task/Aliquot-sequence-classifications/Ruby/aliquot-sequence-classifications.rb b/Task/Aliquot-sequence-classifications/Ruby/aliquot-sequence-classifications.rb new file mode 100644 index 0000000000..25f001ae72 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Ruby/aliquot-sequence-classifications.rb @@ -0,0 +1,29 @@ +def aliquot(n, maxlen=16, maxterm=2**47) + return "terminating", [0] if n == 0 + s = [] + while (s << n).size <= maxlen and n < maxterm + n = n.proper_divisors.inject(0, :+) + if s.include?(n) + case n + when s[0] + case s.size + when 1 then return "perfect", s + when 2 then return "amicable", s + else return "sociable of length #{s.size}", s + end + when s[-1] then return "aspiring", s + else return "cyclic back to #{n}", s + end + elsif n == 0 then return "terminating", s << 0 + end + end + return "non-terminating", s +end + +for n in 1..10 + puts "%20s: %p" % aliquot(n) +end +puts +for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080] + puts "%20s: %p" % aliquot(n) +end diff --git a/Task/Aliquot-sequence-classifications/Scala/aliquot-sequence-classifications.scala b/Task/Aliquot-sequence-classifications/Scala/aliquot-sequence-classifications.scala new file mode 100644 index 0000000000..edbb871cb8 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Scala/aliquot-sequence-classifications.scala @@ -0,0 +1,20 @@ +def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = { + val sum = properDivisors(n).sum + if (sum == 0) ("terminate", list ::: List(sum)) + else if (step >= 16 || sum > 140737488355328L) ("non-term", list) + else { + list.indexOf(sum) match { + case -1 => createAliquotSeq(sum, step + 1, list ::: List(sum)) + case 0 => if (step == 0) ("perfect", list ::: List(sum)) + else if (step == 1) ("amicable", list ::: List(sum)) + else ("sociable-" + (step + 1), list ::: List(sum)) + case index => if (step == index) ("aspiring", list ::: List(sum)) + else ("cyclic-" + (step - index + 1), list ::: List(sum)) + } + } +} +val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, + 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080L) +val result = numbers.map(i => createAliquotSeq(i, 0, List(i))) + +result foreach { v => println(f"${v._2.head}%14d ${v._1}%10s [${v._2 mkString " "}]" ) } diff --git a/Task/Almost-prime/00DESCRIPTION b/Task/Almost-prime/00DESCRIPTION new file mode 100644 index 0000000000..b48de6f50a --- /dev/null +++ b/Task/Almost-prime/00DESCRIPTION @@ -0,0 +1,8 @@ +A [[wp:Almost prime|k-Almost-prime]] is a natural number n that is the product of k (possibly identical) primes. +So, for example, 1-almost-primes, where k=1, are the prime numbers themselves; 2-almost-primes are the [[Semiprime|semiprimes]]. + +The task is to write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for 1 <= K <= 5. + +;Cf. +* [[Semiprime]] +* [[:Category:Prime Numbers]] diff --git a/Task/Almost-prime/00META.yaml b/Task/Almost-prime/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Almost-prime/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Almost-prime/Ada/almost-prime.ada b/Task/Almost-prime/Ada/almost-prime.ada new file mode 100644 index 0000000000..0284c35f41 --- /dev/null +++ b/Task/Almost-prime/Ada/almost-prime.ada @@ -0,0 +1,25 @@ +with Prime_Numbers, Ada.Text_IO; + +procedure Test_Kth_Prime is + + package Integer_Numbers is new + Prime_Numbers (Natural, 0, 1, 2); + use Integer_Numbers; + + Out_Length: constant Positive := 10; -- 10 k-th almost primes + N: Positive; -- the "current number" to be checked + +begin + for K in 1 .. 5 loop + Ada.Text_IO.Put("K =" & Integer'Image(K) &": "); + N := 2; + for I in 1 .. Out_Length loop + while Decompose(N)'Length /= K loop + N := N + 1; + end loop; -- now N is Kth almost prime; + Ada.Text_IO.Put(Integer'Image(Integer(N))); + N := N + 1; + end loop; + Ada.Text_IO.New_Line; + end loop; +end Test_Kth_Prime; diff --git a/Task/Almost-prime/AutoHotkey/almost-prime.ahk b/Task/Almost-prime/AutoHotkey/almost-prime.ahk new file mode 100644 index 0000000000..659ecf318e --- /dev/null +++ b/Task/Almost-prime/AutoHotkey/almost-prime.ahk @@ -0,0 +1,27 @@ +kprime(n,k) { + p:=2, f:=0 + while( (f1) == k +} + +k:=1, results:="" +while( k<=5 ) { + i:=2, c:=0, results:=results "k =" k ":" + while( c<10 ) { + if (kprime(i,k)) { + results:=results " " i + c++ + } + i++ + } + results:=results "`n" + k++ +} + +MsgBox % results diff --git a/Task/Almost-prime/C-sharp/almost-prime.cs b/Task/Almost-prime/C-sharp/almost-prime.cs new file mode 100644 index 0000000000..ec8a76bbc4 --- /dev/null +++ b/Task/Almost-prime/C-sharp/almost-prime.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace AlmostPrime +{ + class Program + { + static void Main(string[] args) + { + foreach (int k in Enumerable.Range(1, 5)) + { + KPrime kprime = new KPrime() { K = k }; + Console.WriteLine("k = {0}: {1}", + k, string.Join(" ", kprime.GetFirstN(10))); + } + } + } + + class KPrime + { + public int K { get; set; } + + public bool IsKPrime(int number) + { + int primes = 0; + for (int p = 2; p * p <= number && primes < K; ++p) + { + while (number % p == 0 && primes < K) + { + number /= p; + ++primes; + } + } + if (number > 1) + { + ++primes; + } + return primes == K; + } + + public List GetFirstN(int n) + { + List result = new List(); + for (int number = 2; result.Count < n; ++number) + { + if (IsKPrime(number)) + { + result.Add(number); + } + } + return result; + } + } +} diff --git a/Task/Almost-prime/C/almost-prime.c b/Task/Almost-prime/C/almost-prime.c new file mode 100644 index 0000000000..1f2080aa73 --- /dev/null +++ b/Task/Almost-prime/C/almost-prime.c @@ -0,0 +1,30 @@ +#include + +int kprime(int n, int k) +{ + int p, f = 0; + for (p = 2; f < k && p*p <= n; p++) + while (0 == n % p) + n /= p, f++; + + return f + (n > 1) == k; +} + +int main(void) +{ + int i, c, k; + + for (k = 1; k <= 5; k++) { + printf("k = %d:", k); + + for (i = 2, c = 0; c < 10; i++) + if (kprime(i, k)) { + printf(" %d", i); + c++; + } + + putchar('\n'); + } + + return 0; +} diff --git a/Task/Almost-prime/Common-Lisp/almost-prime.lisp b/Task/Almost-prime/Common-Lisp/almost-prime.lisp new file mode 100644 index 0000000000..a97daf5f72 --- /dev/null +++ b/Task/Almost-prime/Common-Lisp/almost-prime.lisp @@ -0,0 +1,13 @@ +(defun start () + (loop for k from 1 to 5 + do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k)))) + +(defun collect-k-almost-prime (k &optional (d 2) (lst nil)) + (cond ((= (length lst) 10) (reverse lst)) + ((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst))) + (t (collect-k-almost-prime k (+ d 1) lst)))) + +(defun ?-primality (n &optional (d 2) (c 0)) + (cond ((> d (isqrt n)) (+ c 1)) + ((zerop (rem n d)) (?-primality (/ n d) d (+ c 1))) + (t (?-primality n (+ d 1) c)))) diff --git a/Task/Almost-prime/D/almost-prime.d b/Task/Almost-prime/D/almost-prime.d new file mode 100644 index 0000000000..c9016d426c --- /dev/null +++ b/Task/Almost-prime/D/almost-prime.d @@ -0,0 +1,36 @@ +import std.stdio, std.algorithm, std.traits; + +Unqual!T[] decompose(T)(in T number) pure nothrow +in { + assert(number > 1); +} body { + typeof(return) result; + Unqual!T n = number; + + for (Unqual!T i = 2; n % i == 0; n /= i) + result ~= i; + for (Unqual!T i = 3; n >= i * i; i += 2) + for (; n % i == 0; n /= i) + result ~= i; + + if (n != 1) + result ~= n; + return result; +} + +void main() { + enum outLength = 10; // 10 k-th almost primes. + + foreach (immutable k; 1 .. 6) { + writef("K = %d: ", k); + auto n = 2; // The "current number" to be checked. + foreach (immutable i; 1 .. outLength + 1) { + while (n.decompose.length != k) + n++; + // Now n is K-th almost prime. + write(n, " "); + n++; + } + writeln; + } +} diff --git a/Task/Almost-prime/Go/almost-prime.go b/Task/Almost-prime/Go/almost-prime.go new file mode 100644 index 0000000000..6565b5f17a --- /dev/null +++ b/Task/Almost-prime/Go/almost-prime.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +func kPrime(n, k int) bool { + nf := 0 + for i := 2; i <= n; i++ { + for n%i == 0 { + if nf == k { + return false + } + nf++ + n /= i + } + } + return nf == k +} + +func gen(k, n int) []int { + r := make([]int, n) + n = 2 + for i := range r { + for !kPrime(n, k) { + n++ + } + r[i] = n + n++ + } + return r +} + +func main() { + for k := 1; k <= 5; k++ { + fmt.Println(k, gen(k, 10)) + } +} diff --git a/Task/Almost-prime/Haskell/almost-prime.hs b/Task/Almost-prime/Haskell/almost-prime.hs new file mode 100644 index 0000000000..037341c890 --- /dev/null +++ b/Task/Almost-prime/Haskell/almost-prime.hs @@ -0,0 +1,18 @@ +isPrime :: Integral a => a -> Bool +isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)] + +primes :: [Integer] +primes = filter isPrime [2..] + +isKPrime :: (Num a, Eq a) => a -> Integer -> Bool +isKPrime 1 n = isPrime n +isKPrime k n = any (isKPrime (k - 1)) sprimes + where + sprimes = map fst $ filter ((0 ==) . snd) $ map (divMod n) $ takeWhile (< n) primes + +kPrimes :: (Num a, Eq a) => a -> [Integer] +kPrimes k = filter (isKPrime k) [2..] + +main :: IO () +main = flip mapM_ [1..5] $ \k -> + putStrLn $ "k = " ++ show k ++ ": " ++ (unwords $ map show (take 10 $ kPrimes k)) diff --git a/Task/Almost-prime/Icon/almost-prime.icon b/Task/Almost-prime/Icon/almost-prime.icon new file mode 100644 index 0000000000..297458b93a --- /dev/null +++ b/Task/Almost-prime/Icon/almost-prime.icon @@ -0,0 +1,10 @@ +link "factors" + +procedure main() + every writes(k := 1 to 5,": ") do + every writes(right(genKap(k),5)\10|"\n") +end + +procedure genKap(k) + suspend (k = *factors(n := seq(q)), n) +end diff --git a/Task/Almost-prime/J/almost-prime.j b/Task/Almost-prime/J/almost-prime.j new file mode 100644 index 0000000000..9a21975536 --- /dev/null +++ b/Task/Almost-prime/J/almost-prime.j @@ -0,0 +1,6 @@ + (10 {. [:~.[:/:~[:,*/~)^:(i.5)~p:i.10 + 2 3 5 7 11 13 17 19 23 29 + 4 6 9 10 14 15 21 22 25 26 + 8 12 18 20 27 28 30 42 44 45 +16 24 36 40 54 56 60 81 84 88 +32 48 72 80 108 112 120 162 168 176 diff --git a/Task/Almost-prime/Julia/almost-prime.julia b/Task/Almost-prime/Julia/almost-prime.julia new file mode 100644 index 0000000000..08e662e387 --- /dev/null +++ b/Task/Almost-prime/Julia/almost-prime.julia @@ -0,0 +1,10 @@ +isalmostprime(n, k) = sum(values(factor(n))) == k +function almostprimes(N, k) # return first N almost-k primes + P = Array(Int, N) + i = 0; n = 2 + while i < N + if isalmostprime(n, k); P[i += 1] = n; end + n += 1 + end + return P +end diff --git a/Task/Almost-prime/Mathematica/almost-prime.math b/Task/Almost-prime/Mathematica/almost-prime.math new file mode 100644 index 0000000000..67420e9ca7 --- /dev/null +++ b/Task/Almost-prime/Mathematica/almost-prime.math @@ -0,0 +1,14 @@ +kprimes[k_,n_] := + (* generates a list of the n smallest k-almost-primes *) + Module[{firstnprimes, runningkprimes = {}}, + firstnprimes = Prime[Range[n]]; + runningkprimes = firstnprimes; + Do[ + runningkprimes = + Outer[Times, firstnprimes , runningkprimes ] // Flatten // Union // Take[#, n] & ; + (* only keep lowest n numbers in our running list *) + , {i, 1, k - 1}]; + runningkprimes + ] +(* now to create table with n=10 and k ranging from 1 to 5 *) +Table[Flatten[{"k = " <> ToString[i] <> ": ", kprimes[i, 10]}], {i,1,5}] // TableForm diff --git a/Task/Almost-prime/Objeck/almost-prime.objeck b/Task/Almost-prime/Objeck/almost-prime.objeck new file mode 100644 index 0000000000..6ca52d43a6 --- /dev/null +++ b/Task/Almost-prime/Objeck/almost-prime.objeck @@ -0,0 +1,27 @@ +class Kth_Prime { + function : native : kPrime(n : Int, k : Int) ~ Bool { + f := 0; + for (p := 2; f < k & p*p <= n; p+=1;) { + while (0 = n % p) { + n /= p; f+=1; + }; + }; + + return f + ((n > 1) ? 1 : 0) = k; + } + + function : Main(args : String[]) ~ Nil { + for (k := 1; k <= 5; k+=1;) { + "k = {$k}:"->Print(); + + c := 0; + for (i := 2; c < 10; i+=1;) { + if (kPrime(i, k)) { + " {$i}"->Print(); + c+=1; + }; + }; + '\n'->Print(); + }; + } +} diff --git a/Task/Almost-prime/PARI-GP/almost-prime.pari b/Task/Almost-prime/PARI-GP/almost-prime.pari new file mode 100644 index 0000000000..05444b7223 --- /dev/null +++ b/Task/Almost-prime/PARI-GP/almost-prime.pari @@ -0,0 +1,2 @@ +almost(k)=my(n); for(i=1,10,while(bigomega(n++)!=k,); print1(n", ")); +for(k=1,5,almost(k);print) diff --git a/Task/Almost-prime/Pascal/almost-prime.pascal b/Task/Almost-prime/Pascal/almost-prime.pascal new file mode 100644 index 0000000000..8d7ded27ce --- /dev/null +++ b/Task/Almost-prime/Pascal/almost-prime.pascal @@ -0,0 +1,26 @@ +program AlmostPrime; +{$IFDEF FPC} + {$Mode Delphi} +{$ENDIF} +uses + primtrial; +var + i,K,cnt : longWord; +BEGIN + K := 1; + repeat + cnt := 0; + i := 2; + write('K=',K:2,':'); + repeat + if isAlmostPrime(i,K) then + Begin + write(i:6,' '); + inc(cnt); + end; + inc(i); + until cnt = 9; + writeln; + inc(k); + until k > 10; +END. diff --git a/Task/Almost-prime/Perl-6/almost-prime-1.pl6 b/Task/Almost-prime/Perl-6/almost-prime-1.pl6 new file mode 100644 index 0000000000..19356e9e56 --- /dev/null +++ b/Task/Almost-prime/Perl-6/almost-prime-1.pl6 @@ -0,0 +1,11 @@ +sub is-k-almost-prime($n is copy, $k) returns Bool { + loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) { + $n /= $p, $f++ while $n %% $p; + } + $f + ($n > 1) == $k; +} + +for 1 .. 5 -> $k { + say .[^10] + given grep { is-k-almost-prime($_, $k) }, 2 .. * +} diff --git a/Task/Almost-prime/Perl-6/almost-prime-2.pl6 b/Task/Almost-prime/Perl-6/almost-prime-2.pl6 new file mode 100644 index 0000000000..56165db9a0 --- /dev/null +++ b/Task/Almost-prime/Perl-6/almost-prime-2.pl6 @@ -0,0 +1,5 @@ +constant factory = 0..* Z=> (0, 0, map { +factors($_) }, 2..*); + +sub almost($n) { map *.key, grep *.value == $n, factory } + +say almost($_)[^10] for 1..5; diff --git a/Task/Almost-prime/Perl/almost-prime-1.pl b/Task/Almost-prime/Perl/almost-prime-1.pl new file mode 100644 index 0000000000..7e2266dbe6 --- /dev/null +++ b/Task/Almost-prime/Perl/almost-prime-1.pl @@ -0,0 +1,7 @@ +use ntheory qw/factor/; +sub almost { + my($k,$n) = @_; + my $i = 1; + map { $i++ while scalar factor($i) != $k; $i++ } 1..$n; +} +say "$_ : ", join(" ", almost($_,10)) for 1..5; diff --git a/Task/Almost-prime/Perl/almost-prime-2.pl b/Task/Almost-prime/Perl/almost-prime-2.pl new file mode 100644 index 0000000000..fb4ba27e91 --- /dev/null +++ b/Task/Almost-prime/Perl/almost-prime-2.pl @@ -0,0 +1,64 @@ +use strict; +use warnings; + +sub k_almost_prime; + +for my $k ( 1 .. 5 ) { + my $almost = 0; + print join(", ", map { + 1 until k_almost_prime ++$almost, $k; + "$almost"; + } 1 .. 10), "\n"; +} + +sub nth_prime; + +sub k_almost_prime { + my ($n, $k) = @_; + return if $n <= 1 or $k < 1; + my $which_prime = 0; + for my $count ( 1 .. $k ) { + while( $n % nth_prime $which_prime ) { + ++$which_prime; + } + $n /= nth_prime $which_prime; + return if $n == 1 and $count != $k; + } + ($n == 1) ? 1 : (); +} + +BEGIN { + # This is loosely based on one of the python solutions + # to the RC Sieve of Eratosthenes task. + my @primes = (2, 3, 5, 7); + my $p_iter = 1; + my $p = $primes[$p_iter]; + my $q = $p*$p; + my %sieve; + my $candidate = $primes[-1] + 2; + sub nth_prime { + my $n = shift; + return if $n < 0; + OUTER: while( $#primes < $n ) { + while( my $s = delete $sieve{$candidate} ) { + my $next = $s + $candidate; + $next += $s while exists $sieve{$next}; + $sieve{$next} = $s; + $candidate += 2; + } + while( $candidate < $q ) { + push @primes, $candidate; + $candidate += 2; + next OUTER if exists $sieve{$candidate}; + } + my $twop = 2 * $p; + my $next = $q + $twop; + $next += $twop while exists $sieve{$next}; + $sieve{$next} = $twop; + $p = $primes[++$p_iter]; + $q = $p * $p; + $candidate += 2; + } + return $primes[$n]; + } +} diff --git a/Task/Almost-prime/PicoLisp/almost-prime.l b/Task/Almost-prime/PicoLisp/almost-prime.l new file mode 100644 index 0000000000..53a8534b86 --- /dev/null +++ b/Task/Almost-prime/PicoLisp/almost-prime.l @@ -0,0 +1,27 @@ +(de factor (N) + (make + (let + (D 2 + L (1 2 2 . (4 2 4 2 4 6 2 6 .)) + M (sqrt N) ) + (while (>= M D) + (if (=0 (% N D)) + (setq M + (sqrt (setq N (/ N (link D)))) ) + (inc 'D (pop 'L)) ) ) + (link N) ) ) ) + +(de almost (N) + (let (X 2 Y 0) + (make + (loop + (when (and (nth (factor X) N) (not (cdr @))) + (link X) + (inc 'Y) ) + (T (= 10 Y) 'done) + (inc 'X) ) ) ) ) + +(for I 5 + (println I '-> (almost I) ) ) + +(bye) diff --git a/Task/Almost-prime/Prolog/almost-prime-1.pro b/Task/Almost-prime/Prolog/almost-prime-1.pro new file mode 100644 index 0000000000..4df0b0a648 --- /dev/null +++ b/Task/Almost-prime/Prolog/almost-prime-1.pro @@ -0,0 +1,20 @@ +% almostPrime(K, +Take, List) succeeds if List can be unified with the +% first Take K-almost-primes. +% Notice that K need not be specified. +% To avoid having to cache or recompute the first Take primes, we define +% almostPrime/3 in terms of almostPrime/4 as follows: +% +almostPrime(K, Take, List) :- + % Compute the list of the first Take primes: + nPrimes(Take, Primes), + almostPrime(K, Take, Primes, List). + +almostPrime(1, Take, Primes, Primes). + +almostPrime(K, Take, Primes, List) :- + generate(2, K), % generate K >= 2 + K1 is K - 1, + almostPrime(K1, Take, Primes, L), + multiplylist( Primes, L, Long), + sort(Long, Sorted), % uniquifies + take(Take, Sorted, List). diff --git a/Task/Almost-prime/Prolog/almost-prime-2.pro b/Task/Almost-prime/Prolog/almost-prime-2.pro new file mode 100644 index 0000000000..c2a85acb52 --- /dev/null +++ b/Task/Almost-prime/Prolog/almost-prime-2.pro @@ -0,0 +1,40 @@ +nPrimes( M, Primes) :- nPrimes( [2], M, Primes). + +nPrimes( Accumulator, I, Primes) :- + next_prime(Accumulator, Prime), + append(Accumulator, [Prime], Next), + length(Next, N), + ( N = I -> Primes = Next; nPrimes( Next, I, Primes)). + +% next_prime(+Primes, NextPrime) succeeds if NextPrime is the next +% prime after a list, Primes, of consecutive primes starting at 2. +next_prime([2], 3). +next_prime([2|Primes], P) :- + last(Primes, PP), + P2 is PP + 2, + generate(P2, N), + 1 is N mod 2, % odd + Max is floor(sqrt(N+1)), % round-off paranoia + forall( (member(Prime, [2|Primes]), + (Prime =< Max -> true + ; (!, fail))), N mod Prime > 0 ), + !, + P = N. + +% multiply( +A, +List, Answer ) +multiply( A, [], [] ). +multiply( A, [X|Xs], [AX|As] ) :- + AX is A * X, + multiply(A, Xs, As). + +% multiplylist( L1, L2, List ) succeeds if List is the concatenation of X * L2 +% for successive elements X of L1. +multiplylist( [], B, [] ). +multiplylist( [A|As], B, List ) :- + multiply(A, B, L1), + multiplylist(As, B, L2), + append(L1, L2, List). + +take(N, List, Head) :- + length(Head, N), + append(Head,X,List). diff --git a/Task/Almost-prime/Prolog/almost-prime-3.pro b/Task/Almost-prime/Prolog/almost-prime-3.pro new file mode 100644 index 0000000000..eb2f3f6acc --- /dev/null +++ b/Task/Almost-prime/Prolog/almost-prime-3.pro @@ -0,0 +1,28 @@ +%%%%% compatibility section %%%%% + +:- if(current_prolog_flag(dialect, yap)). +generate(Min, I) :- between(Min, inf, I). + +append([],L,L). +append([X|Xs], L, [X|Ls]) :- append(Xs,L,Ls). + +:- endif. + +:- if(current_prolog_flag(dialect, swi)). +generate(Min, I) :- between(Min, inf, I). +:- endif. + +:- if(current_prolog_flag(dialect, yap)). +append([],L,L). +append([X|Xs], L, [X|Ls]) :- append(Xs,L,Ls). + +last([X], X). +last([_|Xs],X) :- last(Xs,X). + +:- endif. + +:- if(current_prolog_flag(dialect, gprolog)). +generate(Min, I) :- + current_prolog_flag(max_integer, Max), + between(Min, Max, I). +:- endif. diff --git a/Task/Almost-prime/Python/almost-prime.py b/Task/Almost-prime/Python/almost-prime.py new file mode 100644 index 0000000000..317ae1e381 --- /dev/null +++ b/Task/Almost-prime/Python/almost-prime.py @@ -0,0 +1,19 @@ +from prime_decomposition import decompose +from itertools import islice, count +try: + from functools import reduce +except: + pass + + +def almostprime(n, k=2): + d = decompose(n) + try: + terms = [next(d) for i in range(k)] + return reduce(int.__mul__, terms, 1) == n + except: + return False + +if __name__ == '__main__': + for k in range(1,6): + print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10)))) diff --git a/Task/Almost-prime/README b/Task/Almost-prime/README new file mode 100644 index 0000000000..1189a43b83 --- /dev/null +++ b/Task/Almost-prime/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Almost_prime diff --git a/Task/Almost-prime/REXX/almost-prime-1.rexx b/Task/Almost-prime/REXX/almost-prime-1.rexx new file mode 100644 index 0000000000..90f5629f0e --- /dev/null +++ b/Task/Almost-prime/REXX/almost-prime-1.rexx @@ -0,0 +1,33 @@ +/*REXX program displays the N numbers of the first K k-almost primes*/ +parse arg N K . /*get the arguments from the C.L.*/ +if N=='' then N=10 /*No N? Then use the default.*/ +if K=='' then K=5 /* " K? " " " " */ + /* [↓] display one line per K.*/ + do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/ + #=1; if #==N then leave /*# k-almost primes; 'nuff found?*/ + sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/ + do j=fir+fir+1 until #==N /*process an almost-prime N times*/ + if #factr(j)\==m then iterate /*not the correct k-almost prime?*/ + #=#+1 /*bump the k-almost prime counter*/ + $=$ j /*append k-almost prime to list. */ + end /*j*/ /* [↑] gen N k-almost primes.*/ + say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/ + end /*m*/ /* [↑] display a line for each K*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────#FACTR subroutine───────────────────*/ +#factr: procedure;parse arg x 1 z; f=0 /*defines X and Z to the arg.*/ +if x<2 then return 0 /*invalid number? Then return 0.*/ + do j=2 to 5; if j\==4 then call .#factr; end /*fast factoring.*/ +j=5 /*start were we left off (J=5). */ + do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/ + if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ + if j>z then leave /*number reduced to a wee number?*/ + call .#factr /*go add other factors to count. */ + end /*y*/ /* [↑] find all factors in X. */ +return max(f,1) /*if prime (f==0), then return 1.*/ +/*──────────────────────────────────.#FACTR subroutine──────────────────*/ +.#factr: do f=f+1 while z//j==0 /*keep dividing until we can't. */ + z=z%j /*perform an (%) integer divide.*/ + end /*while*/ /* [↑] whittle down the Z num.*/ +f=f-1 /*adjust the count of factors. */ +return diff --git a/Task/Almost-prime/REXX/almost-prime-2.rexx b/Task/Almost-prime/REXX/almost-prime-2.rexx new file mode 100644 index 0000000000..1673079e3f --- /dev/null +++ b/Task/Almost-prime/REXX/almost-prime-2.rexx @@ -0,0 +1,35 @@ +/*REXX program displays the N numbers of the first K k-almost primes*/ +parse arg N K . /*get the arguments from the C.L.*/ +if N=='' then N=10 /*No N? Then use the default.*/ +if K=='' then K=5 /* " K? " " " " */ + /* [↓] display one line per K.*/ + do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/ + #=1; if #==N then leave /*# k-almost primes; 'nuff found?*/ + sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/ + do j=fir+fir+1 until #==N /*process an almost-prime N times*/ + if #factL(j,m)\==m then iterate /*not the correct k-almost prime?*/ + #=#+1 /*bump the k-almost prime counter*/ + $=$ j /*append k-almost prime to list. */ + end /*j*/ /* [↑] gen N k-almost primes.*/ + say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/ + end /*m*/ /* [↑] display a line for each K*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────#FACTL subroutine───────────────────*/ +#factL: procedure; parse arg x 1 z,L /*defines X and Z to the arg.*/ +f=0; if x<2 then return 0 /*invalid number? Then return 0.*/ + do j=2 to 5; if j\==4 then call .#factL; end /*fast factoring.*/ +if f>L then return f /*#factors > L ? Then too many.*/ +j=5 /*start were we left off (J=5). */ + do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/ + if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ + if j>z then leave /*number reduced to a wee number?*/ + call .#factL /*go add other factors to count. */ + if f>L then return f /*#factors > L ? Then too many.*/ + end /*y*/ /* [↑] find all factors in X. */ +return max(f,1) /*if prime (f==0), then return 1.*/ +/*──────────────────────────────────.#FACTL subroutine──────────────────*/ +.#factL: do f=f+1 while z//j==0 /*keep dividing until we can't. */ + z=z%j /*perform an (%) integer divide.*/ + end /*while*/ /* [↑] whittle down the Z num.*/ +f=f-1 /*adjust the count of factors. */ +return diff --git a/Task/Almost-prime/Racket/almost-prime.rkt b/Task/Almost-prime/Racket/almost-prime.rkt new file mode 100644 index 0000000000..a2e5a4c9d5 --- /dev/null +++ b/Task/Almost-prime/Racket/almost-prime.rkt @@ -0,0 +1,25 @@ +#lang racket +(require (only-in math/number-theory factorize)) + +(define ((k-almost-prime? k) n) + (= k (for/sum ((f (factorize n))) (cadr f)))) + +(define KAP-table-values + (for/list ((k (in-range 1 (add1 5)))) + (define kap? (k-almost-prime? k)) + (for/list ((j (in-range 10)) (i (sequence-filter kap? (in-naturals 1)))) + i))) + +(define (format-table t) + (define longest-number-length + (add1 (order-of-magnitude (argmax order-of-magnitude (cons (length t) (apply append t)))))) + (define (fmt-val v) (~a v #:width longest-number-length #:align 'right)) + (string-join + (for/list ((r t) (k (in-naturals 1))) + (string-append + (format "║ k = ~a║ " (fmt-val k)) + (string-join (for/list ((c r)) (fmt-val c)) "| ") + "║")) + "\n")) + +(displayln (format-table KAP-table-values)) diff --git a/Task/Almost-prime/Ruby/almost-prime-1.rb b/Task/Almost-prime/Ruby/almost-prime-1.rb new file mode 100644 index 0000000000..0e578dd9ff --- /dev/null +++ b/Task/Almost-prime/Ruby/almost-prime-1.rb @@ -0,0 +1,12 @@ +require 'prime' + +def almost_primes(k=2) + return to_enum(:almost_primes, k) unless block_given? + n = 0 + loop do + n += 1 + yield n if n.prime_division.map( &:last ).inject( &:+ ) == k + end +end + +(1..5).each{|k| puts almost_primes(k).take(10).join(", ")} diff --git a/Task/Almost-prime/Ruby/almost-prime-2.rb b/Task/Almost-prime/Ruby/almost-prime-2.rb new file mode 100644 index 0000000000..2c79cd8424 --- /dev/null +++ b/Task/Almost-prime/Ruby/almost-prime-2.rb @@ -0,0 +1,4 @@ +require 'prime' + +p ar = pr = Prime.take(10) +4.times{p ar = ar.product(pr).map{|(a,b)| a*b}.uniq.sort.take(10)} diff --git a/Task/Almost-prime/Rust/almost-prime.rust b/Task/Almost-prime/Rust/almost-prime.rust new file mode 100644 index 0000000000..4ff84b9ee4 --- /dev/null +++ b/Task/Almost-prime/Rust/almost-prime.rust @@ -0,0 +1,39 @@ +fn is_kprime(n: usize, k: usize) -> bool { + let mut primes = 0us; + let mut f = 2us; + let mut rem = n; + while primes < k && rem > 1{ + while (rem % f) == 0 && rem > 1{ + rem /= f; + primes += 1; + } + f += 1; + } + rem == 1 && primes == k +} + +struct KPrimeGen { + k: usize, + n: usize, +} + +impl Iterator for KPrimeGen { + type Item = usize; + fn next(&mut self) -> Option { + self.n += 1; + while !is_kprime(self.n, self.k) { + self.n += 1; + } + Some(self.n) + } +} + +fn kprime_generator(k: usize) -> KPrimeGen { + KPrimeGen {k: k, n: 1} +} + +fn main() { + for k in 1us..6 { + println!("{}: {:?}", k, kprime_generator(k).take(10).collect::>()); + } +} diff --git a/Task/Almost-prime/Scala/almost-prime.scala b/Task/Almost-prime/Scala/almost-prime.scala new file mode 100644 index 0000000000..0a0fed609c --- /dev/null +++ b/Task/Almost-prime/Scala/almost-prime.scala @@ -0,0 +1,16 @@ +def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match { + case (n, k, _) if n == 1 => k == 0 + case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d) + case (_, _, _) => isKPrime(n, k, d + 1) +} + +def kPrimeStream(k: Int): Stream[Int] = { + def loop(n: Int): Stream[Int] = + if (isKPrime(n, k)) n #:: loop(n+ 1) + else loop(n + 1) + loop(2) +} + +for (k <- 1 to 5) { + println( s"$k: [${ kPrimeStream(k).take(10) mkString " " }]" ) +} diff --git a/Task/Almost-prime/Tcl/almost-prime.tcl b/Task/Almost-prime/Tcl/almost-prime.tcl new file mode 100644 index 0000000000..fd540fea86 --- /dev/null +++ b/Task/Almost-prime/Tcl/almost-prime.tcl @@ -0,0 +1,31 @@ +package require Tcl 8.6 +package require math::numtheory + +proc firstNprimes n { + for {set result {};set i 2} {[llength $result] < $n} {incr i} { + if {[::math::numtheory::isprime $i]} { + lappend result $i + } + } + return $result +} + +proc firstN_KalmostPrimes {n k} { + set p [firstNprimes $n] + set i [lrepeat $k 0] + set c {} + + while true { + dict set c [::tcl::mathop::* {*}[lmap j $i {lindex $p $j}]] "" + for {set x 0} {$x < $k} {incr x} { + lset i $x [set xx [expr {([lindex $i $x] + 1) % $n}]] + if {$xx} break + } + if {$x == $k} break + } + return [lrange [lsort -integer [dict keys $c]] 0 [expr {$n - 1}]] +} + +for {set K 1} {$K <= 5} {incr K} { + puts "$K => [firstN_KalmostPrimes 10 $K]" +} diff --git a/Task/Amb/00DESCRIPTION b/Task/Amb/00DESCRIPTION new file mode 100644 index 0000000000..dd5c12be1f --- /dev/null +++ b/Task/Amb/00DESCRIPTION @@ -0,0 +1,17 @@ +Define and give an example of the Amb operator. + +The Amb operator takes some number of expressions (or values if that's simpler in the language) and nondeterministically yields the one or fails if given no parameter, amb returns the value that doesn't lead to failure. + +The example is using amb to choose four words from the following strings: + +set 1: "the" "that" "a" + +set 2: "frog" "elephant" "thing" + +set 3: "walked" "treaded" "grows" + +set 4: "slowly" "quickly" + +It is a failure if the last character of word 1 is not equal to the first character +of word 2, and similarly with word 2 and word 3, as well as word 3 and word 4. +(the only successful sentence is "that thing grows slowly"). diff --git a/Task/Amb/ALGOL-68/amb.alg b/Task/Amb/ALGOL-68/amb.alg new file mode 100644 index 0000000000..a0d2f5dcc0 --- /dev/null +++ b/Task/Amb/ALGOL-68/amb.alg @@ -0,0 +1,38 @@ +MODE PAGE = FLEX[0]STRING; +MODE YIELDPAGE = PROC(PAGE)VOID; +MODE ITERPAGE = PROC(YIELDPAGE)VOID; + +OP INITITERPAGE = (PAGE self)ITERPAGE: + (YIELDPAGE yield)VOID: # scope violation # + FOR i TO UPB self DO + yield(self[i]) + OD; + +OP + = (ITERPAGE for strings, PAGE b)ITERPAGE: + (YIELDPAGE yield)VOID: # scope violation # + for strings((PAGE amb)VOID:( + [UPB amb + 1]STRING joined; + joined[:UPB amb] := amb; + STRING last string := amb[UPB amb]; + CHAR last char := last string[UPB last string]; + FOR i TO UPB b DO + IF last char = b[i][1] THEN + joined[UPB joined] := b[i]; + yield(joined) + FI + OD + )); + +OP + = (PAGE a, PAGE b)ITERPAGE: INITITERPAGE a + b; + +ITERPAGE gen amb := + PAGE("the", "that", "a") + + PAGE("frog", "elephant", "thing") + + PAGE("walked", "treaded", "grows") + + PAGE("slowly", "quickly"); + +PAGE sep; +#FOR PAGE amb IN # gen amb( # ) DO # +## (PAGE amb)VOID: + print((amb[1]+" "+amb[2]+" "+amb[3]+" "+amb[4], new line)) +#OD# ) diff --git a/Task/Amb/Ada/amb.ada b/Task/Amb/Ada/amb.ada new file mode 100644 index 0000000000..35a5c0f474 --- /dev/null +++ b/Task/Amb/Ada/amb.ada @@ -0,0 +1,70 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Amb is + type Alternatives is array (Positive range <>) of Unbounded_String; + + type Amb (Count : Positive) is record + This : Positive := 1; + Left : access Amb; + List : Alternatives (1..Count); + end record; + + function Image (L : Amb) return String is + begin + return To_String (L.List (L.This)); + end Image; + + function "/" (L, R : String) return Amb is + Result : Amb (2); + begin + Append (Result.List (1), L); + Append (Result.List (2), R); + return Result; + end "/"; + + function "/" (L : Amb; R : String) return Amb is + Result : Amb (L.Count + 1); + begin + Result.List (1..L.Count) := L.List ; + Append (Result.List (Result.Count), R); + return Result; + end "/"; + + function "=" (L, R : Amb) return Boolean is + Left : Unbounded_String renames L.List (L.This); + begin + return Element (Left, Length (Left)) = Element (R.List (R.This), 1); + end "="; + + procedure Failure (L : in out Amb) is + begin + loop + if L.This < L.Count then + L.This := L.This + 1; + else + L.This := 1; + Failure (L.Left.all); + end if; + exit when L.Left = null or else L.Left.all = L; + end loop; + end Failure; + + procedure Join (L : access Amb; R : in out Amb) is + begin + R.Left := L; + while L.all /= R loop + Failure (R); + end loop; + end Join; + + W_1 : aliased Amb := "the" / "that" / "a"; + W_2 : aliased Amb := "frog" / "elephant" / "thing"; + W_3 : aliased Amb := "walked" / "treaded" / "grows"; + W_4 : aliased Amb := "slowly" / "quickly"; +begin + Join (W_1'Access, W_2); + Join (W_2'Access, W_3); + Join (W_3'Access, W_4); + Put_Line (Image (W_1) & ' ' & Image (W_2) & ' ' & Image (W_3) & ' ' & Image (W_4)); +end Test_Amb; diff --git a/Task/Amb/AutoHotkey/amb.ahk b/Task/Amb/AutoHotkey/amb.ahk new file mode 100644 index 0000000000..fb03a7fa9a --- /dev/null +++ b/Task/Amb/AutoHotkey/amb.ahk @@ -0,0 +1,16 @@ +set1 := "the that a" +set2 := "frog elephant thing" +set3 := "walked treaded grows" +set4 := "slowly quickly" + +MsgBox % amb( "", set1, set2, set3, set4 ) +; this takes a total of 17 iterations to complete + +amb( char = "", set1 = "", set2 = "", set3 = "", set4 = "" ) +{ ; original call to amb must leave char param blank + Loop, Parse, set1, %A_Space% + If (char = (idxchar := SubStr(A_LoopField, 1, 1)) && set2 = "" + || (char = idxchar || char = "") && ((retval:= amb(SubStr(A_LoopField, 0, 1), set2, set3, set4)) != "")) + Return A_LoopField " " retval + Return "" +} diff --git a/Task/Amb/Bracmat/amb.bracmat b/Task/Amb/Bracmat/amb.bracmat new file mode 100644 index 0000000000..9c81b825c2 --- /dev/null +++ b/Task/Amb/Bracmat/amb.bracmat @@ -0,0 +1,23 @@ +( ( Amb + = first last list words word solution + . !arg:(?first.?list) + & ( !list: + | !list:(.?words) ?list + & !words + : ? + %( @(?word:!first ? @?last) + & Amb$(!last.!list):?solution + & !word !solution:?solution + ) + ? + & !solution + ) + ) +& Amb + $ ( + . (.the that a) + (.frog elephant thing) + (.walked treaded grows) + (.slowly quickly) + ) +) diff --git a/Task/Amb/C-sharp/amb-1.cs b/Task/Amb/C-sharp/amb-1.cs new file mode 100644 index 0000000000..2e90a45f7c --- /dev/null +++ b/Task/Amb/C-sharp/amb-1.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; + +public class Amb : IDisposable +{ + List streams = new List(); + List assertsOrActions = new List(); + volatile bool stopped = false; + + public IAmbValue DefineValues(params T[] values) + { + return DefineValueSet(values); + } + + public IAmbValue DefineValueSet(IEnumerable values) + { + ValueSet stream = new ValueSet(); + stream.Enumerable = values; + streams.Add(stream); + return stream; + } + + public Amb Assert(Func function) + { + assertsOrActions.Add(new AmbAssert() + { + Level = streams.Count, + IsValidFunction = function + }); + return this; + } + + public Amb Perform(Action action) + { + assertsOrActions.Add(new AmbAction() + { + Level = streams.Count, + Action = action + }); + return this; + } + + public void Stop() + { + stopped = true; + } + + public void Dispose() + { + RunLevel(0, 0); + if (!stopped) + { + throw new AmbException(); + } + } + + void RunLevel(int level, int actionIndex) + { + while (actionIndex < assertsOrActions.Count && assertsOrActions[actionIndex].Level <= level) + { + if (!assertsOrActions[actionIndex].Invoke() || stopped) + return; + actionIndex++; + } + if (level < streams.Count) + { + using (IValueSetIterator iterator = streams[level].CreateIterator()) + { + while (iterator.MoveNext()) + { + RunLevel(level + 1, actionIndex); + } + } + } + } + + interface IValueSet + { + IValueSetIterator CreateIterator(); + } + + interface IValueSetIterator : IDisposable + { + bool MoveNext(); + } + + interface IAssertOrAction + { + int Level { get; } + bool Invoke(); + } + + class AmbAssert : IAssertOrAction + { + internal int Level; + internal Func IsValidFunction; + + int IAssertOrAction.Level { get { return Level; } } + + bool IAssertOrAction.Invoke() + { + return IsValidFunction(); + } + } + + class AmbAction : IAssertOrAction + { + internal int Level; + internal Action Action; + + int IAssertOrAction.Level { get { return Level; } } + + bool IAssertOrAction.Invoke() + { + Action(); return true; + } + } + + class ValueSet : IValueSet, IAmbValue, IValueSetIterator + { + internal IEnumerable Enumerable; + private IEnumerator enumerator; + + public T Value { get { return enumerator.Current; } } + + public IValueSetIterator CreateIterator() + { + enumerator = Enumerable.GetEnumerator(); + return this; + } + + public bool MoveNext() + { + return enumerator.MoveNext(); + } + + public void Dispose() + { + enumerator.Dispose(); + } + } +} + +public interface IAmbValue +{ + T Value { get; } +} + +public class AmbException : Exception +{ + public AmbException() : base("AMB is angry") { } +} diff --git a/Task/Amb/C-sharp/amb-2.cs b/Task/Amb/C-sharp/amb-2.cs new file mode 100644 index 0000000000..3d6de52aa3 --- /dev/null +++ b/Task/Amb/C-sharp/amb-2.cs @@ -0,0 +1,30 @@ + // original problem + using (Amb amb = new Amb()) + { + var set1 = amb.DefineValues("the", "that", "a"); + var set2 = amb.DefineValues("frog", "elephant", "thing"); + var set3 = amb.DefineValues("walked", "treaded", "grows"); + var set4 = amb.DefineValues("slowly", "quickly"); + + amb.Assert(() => IsJoinable(set1.Value, set2.Value)); + amb.Assert(() => IsJoinable(set2.Value, set3.Value)); + amb.Assert(() => IsJoinable(set3.Value, set4.Value)); + + amb.Perform(() => + { + System.Console.WriteLine("{0} {1} {2} {3}", set1.Value, set2.Value, set3.Value, set4.Value); + amb.Stop(); + }); + } + // problem from http://www.randomhacks.net/articles/2005/10/11/amb-operator + using (Amb amb = new Amb()) + { + IAmbValue x = amb.DefineValues(1, 2, 3); + IAmbValue y = amb.DefineValues(4, 5, 6); + amb.Assert(() => x.Value * y.Value == 8); + amb.Perform(() => + { + System.Console.WriteLine("{0} {1}", x.Value, y.Value); + amb.Stop(); + }); + } diff --git a/Task/Amb/C/amb.c b/Task/Amb/C/amb.c new file mode 100644 index 0000000000..614f870840 --- /dev/null +++ b/Task/Amb/C/amb.c @@ -0,0 +1,41 @@ +typedef const char * amb_t; + +amb_t amb(size_t argc, ...) +{ + amb_t *choices; + va_list ap; + int i; + + if(argc) { + choices = malloc(argc*sizeof(amb_t)); + va_start(ap, argc); + i = 0; + do { choices[i] = va_arg(ap, amb_t); } while(++i < argc); + va_end(ap); + + i = 0; + do { TRY(choices[i]); } while(++i < argc); + free(choices); + } + + FAIL; +} + +int joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; } + +int _main() { + const char *w1,*w2,*w3,*w4; + + w1 = amb(3, "the", "that", "a"); + w2 = amb(3, "frog", "elephant", "thing"); + w3 = amb(3, "walked", "treaded", "grows"); + w4 = amb(2, "slowly", "quickly"); + + if(!joins(w1, w2)) amb(0); + if(!joins(w2, w3)) amb(0); + if(!joins(w3, w4)) amb(0); + + printf("%s %s %s %s\n", w1, w2, w3, w4); + + return EXIT_SUCCESS; +} diff --git a/Task/Amb/Clojure/amb.clj b/Task/Amb/Clojure/amb.clj new file mode 100644 index 0000000000..81a3e62620 --- /dev/null +++ b/Task/Amb/Clojure/amb.clj @@ -0,0 +1,12 @@ +(ns amb + (:use clojure.contrib.monads)) + +(defn amb [wss] + (let [valid-word (fn [w1 w2] + (if (and w1 (= (last w1) (first w2))) + (str w1 " " w2)))] + (filter #(reduce valid-word %) + (with-monad sequence-m (m-seq wss))))) + +amb> (amb '(("the" "that" "a") ("frog" "elephant" "thing") ("walked" "treaded" "grows") ("slowly" "quickly"))) +(("that" "thing" "grows" "slowly")) diff --git a/Task/Amb/Common-Lisp/amb-1.lisp b/Task/Amb/Common-Lisp/amb-1.lisp new file mode 100644 index 0000000000..d132cb65bb --- /dev/null +++ b/Task/Amb/Common-Lisp/amb-1.lisp @@ -0,0 +1,35 @@ +(define-condition amb-failure () () + (:report "No amb alternative succeeded.")) + +(defun invoke-ambiguously (function thunks) + "Call function with successive values produced by successive +functions in thunks until some invocation of function does not signal +an amb-failure." + (do ((thunks thunks (rest thunks))) + ((endp thunks) (error 'amb-failure)) + (let ((argument (funcall (first thunks)))) + (handler-case (return (funcall function argument)) + (amb-failure ()))))) + +(defmacro amblet1 ((var form) &body body) + "If form is of the form (amb {form}*) then amblet1 is a convenient +syntax for invoke-ambiguously, by which body is evaluated with var +bound the results of each form until some evaluation of body does not +signal an amb-failure. For any other form, amblet binds var the result +of form, and evaluates body." + (if (and (listp form) (eq (first form) 'amb)) + `(invoke-ambiguously + #'(lambda (,var) ,@body) + (list ,@(loop for amb-form in (rest form) + collecting `#'(lambda () ,amb-form)))) + `(let ((,var ,form)) + ,@body))) + +(defmacro amblet (bindings &body body) + "Like let, except that if an init-form is of the form (amb {form}*), +then the corresponding var is bound with amblet1." + (if (endp bindings) + `(progn ,@body) + `(amblet1 ,(first bindings) + (amblet ,(rest bindings) + ,@body)))) diff --git a/Task/Amb/Common-Lisp/amb-2.lisp b/Task/Amb/Common-Lisp/amb-2.lisp new file mode 100644 index 0000000000..b47d182081 --- /dev/null +++ b/Task/Amb/Common-Lisp/amb-2.lisp @@ -0,0 +1,50 @@ +(defparameter *amb-ops* nil) +(defparameter *amb-hist* nil) + +(setf *random-state* (make-random-state t)) +(defun shuffle (items) + (loop for i from 0 with r = items with l = (length r) while (< i l) do + (rotatef (elt r i) (elt r (+ i (random (- l i))))) + finally (return r))) + +;;; (assert '(mess in, mess out)) +(defmacro amb (a &rest rest) + (let ((f (first rest)) + (rest (rest rest))) + (if (not f) + `(let ((items (shuffle ,a))) + (let ((y (car (last *amb-hist*))) + (o (car (last *amb-ops*)))) + (loop for x in items do + (if (or (not *amb-ops*) + (funcall o y x)) + (return (append *amb-hist* (list x)))) + (elt items (random (length items)))))) + + `(let ((items (shuffle ,a))) + (let ((y (car (last *amb-hist*))) + (o (car (last *amb-ops*)))) + (loop for x in items do + (if (or (not *amb-ops*) + (funcall o y x)) + (let ((*amb-hist* (append *amb-hist* (list x))) + (*amb-ops* (append *amb-ops* (list ,f)))) + (let ((r ,@rest)) + (if r (return r))))))))))) + +;; test cases +(defun joins (a b) + (char= (char a (1- (length a))) (char b 0))) + +(defun w34() + (amb '("walked" "treaded" "grows") #'joins + (amb '("slowly" "quickly")))) + +(print + (amb '("the" "that" "a") #'joins + (amb '("frog" "elephant" "thing") #'joins + (w34)))) + +(print (amb '(1 2 5) #'< + (amb '(2 3 4) #'= + (amb '(3 4 5))))) ; 1 4 4, 2 3 3, etc diff --git a/Task/Amb/D/amb.d b/Task/Amb/D/amb.d new file mode 100644 index 0000000000..cc589071d0 --- /dev/null +++ b/Task/Amb/D/amb.d @@ -0,0 +1,47 @@ +import std.stdio, std.array; + +/** This amb function takes a comparison function and +the possibilities that need to be checked.*/ +//string[] amb(in bool function(in string, in string) pure comp, +const(string)[] amb(in bool function(in string, in string) pure comp, + in string[][] options, + in string prev = null) pure { + if (options.empty) + return null; + + foreach (immutable opt; options.front) { + // If this is the base call, prev is null and we need to + // continue. + if (!prev.empty && !comp(prev, opt)) + continue; + + // Take care of the case where we have no options left. + if (options.length == 1) + return [opt]; + + // Traverse into the tree. + const res = amb(comp, options[1 .. $], opt); + + // If it was a failure, try the next one. + if (!res.empty) + return opt ~ res; // We have a match! + } + + return null; // No matches. +} + +void main() { + immutable sets = [["the", "that", "a"], + ["frog", "elephant", "thing"], + ["walked", "treaded", "grows"], + ["slowly", "quickly"]]; + + // Pass in the comparator and the available sets. + // (The comparator is not nothrow because of UTF.) + const result = amb((s, t) => s.back == t.front, sets); + + if (result.empty) + writeln("No matches found!"); + else + writefln("%-(%s %)", result); +} diff --git a/Task/Amb/E/amb-1.e b/Task/Amb/E/amb-1.e new file mode 100644 index 0000000000..7a1ed1e159 --- /dev/null +++ b/Task/Amb/E/amb-1.e @@ -0,0 +1,81 @@ +pragma.enable("accumulator") + +def [amb, unamb] := { # block hides internals + + def Choice := Tuple[any, Map] + + def [ambS, ambU] := ("amb") + var counter := 0 # Used just for printing ambs + + /** Check whether two sets of decisions are consistent */ + def consistent(decA, decB) { + def overlap := decA.domain() & decB.domain() + for ambObj in overlap { + if (decA[ambObj] != decB[ambObj]) { return false } + } + return true + } + + /** From an amb object, extract the possible choices */ + def getChoices(obj, decisions) :List[Choice] { + if (decisions.maps(obj)) { + return [[decisions[obj], decisions]] + } else if (ambU.amplify(obj) =~ [[choices, _]]) { + return accum [] for [chosen, dec] ? (consistent(decisions, dec)) in choices { _ + getChoices(chosen, (decisions | dec).with(obj, chosen)) } + } else { + return [[obj, decisions]] + } + } + + /** Construct an amb object with remembered decisions */ + def ambDec(choices :List[Choice]) { + def serial := (counter += 1) + def ambObj { + to __printOn(out) { + out.print(" v in decisions { + out.print(";", ambU.amplify(k)[0][1], "=", v) + } + } + out.print(">") + } + to __optSealedDispatch(brand) { + if (brand == ambS.getBrand()) { + return ambS.seal([choices, serial]) + } + } + match [verb, args] { + var results := [] + for [rec, rdec] in getChoices(ambObj, [].asMap()) { + def expandArgs(dec, prefix, choosing) { + switch (choosing) { + match [] { results with= [E.call(rec, verb, prefix), dec] } + match [argAmb] + moreArgs { + for [arg, adec] in getChoices(argAmb, dec) { + expandArgs(adec, prefix.with(arg), moreArgs) + } + } + } + } + expandArgs(rdec, [], args) + } + ambDec(results) + } + } + return ambObj + } + + /** Construct an amb object with no remembered decisions. (public interface) */ + def amb(choices) { + return ambDec(accum [] for c in choices { _.with([c, [].asMap()]) }) + } + + /** Get the possible results from an amb object, discarding decision info. (public interface) */ + def unamb(ambObj) { + return accum [] for [c,_] in getChoices(ambObj, [].asMap()) { _.with(c) } + } + + [amb, unamb] +} diff --git a/Task/Amb/E/amb-2.e b/Task/Amb/E/amb-2.e new file mode 100644 index 0000000000..3bb8cd08e2 --- /dev/null +++ b/Task/Amb/E/amb-2.e @@ -0,0 +1,18 @@ +def join(a, b) { + # This must not use the builtin if, since it coerces to boolean rather than passing messages. + # false.pick(x, y) returns y and true.pick(x, y) returns x; we protect the amb([]) from causing + # unconditional failure by putting both options in functions. + # <=> is the comparison operator that happens to be message-based. + return (a.last() <=> b[0]).pick(fn { + a + " " + b + }, fn { + amb([]) + })() +} + +def w1 := amb(["the", "that", "a" ]) +def w2 := amb(["frog", "elephant", "thing" ]) +def w3 := amb(["walked", "treaded", "grows" ]) +def w4 := amb(["slowly", "quickly" ]) + +unamb(join(join(join(w1, w2), w3), w4)) diff --git a/Task/Amb/Ela/amb-1.ela b/Task/Amb/Ela/amb-1.ela new file mode 100644 index 0000000000..c6974d25cc --- /dev/null +++ b/Task/Amb/Ela/amb-1.ela @@ -0,0 +1,15 @@ +open list core + +amb xs = x where + (Some x) = & join xs "" + join (x::xs) = amb' x (join xs) + join [] = \_ -> Some "" + eq' [] x = true + eq' w x = last w == head x + amb' [] _ _ = None + amb' (x::xs) n w + | eq' w x = + match n x with + Some v = Some (x ++ " " ++ v) + _ = amb' xs n w + | else = amb' xs n w diff --git a/Task/Amb/Ela/amb-2.ela b/Task/Amb/Ela/amb-2.ela new file mode 100644 index 0000000000..0448b6446e --- /dev/null +++ b/Task/Amb/Ela/amb-2.ela @@ -0,0 +1,6 @@ +amb [ + ["the","that","a"] + ,["frog","elephant","thing"] + ,["walked","treaded","grows"] + ,["slowly","quickly"] + ] diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena new file mode 100644 index 0000000000..6c94cd7cb5 --- /dev/null +++ b/Task/Amb/Elena/amb.elena @@ -0,0 +1,125 @@ +#define system. +#define extensions. +#define extensions'routines. + +// --- Joinable -- + +#symbol joinable = (:aFormer:aLater) + [ (aFormer @ (aFormer length - 1)) == (aLater @ 0) ]. + +// --- Activatora --- + +#class(role)Activator2 +{ + #method eval : anArray + [ + ^ self eval:(anArray@0):(anArray@1). + ] +} + +#class(role)Activator3 +{ + #method eval : anArray + [ + ^ self eval:(anArray@0):(anArray@1):(anArray@2). + ] +} + +#class(role)Activator4 +{ + #method eval : anArray + [ + ^ self eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3). + ] +} + +#class(role)Activator5 +{ + #method eval : anArray + [ + ^ self eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3):(anArray@4). + ] +} + +// --- AmbValueCollection --- + +#class AmbValueCollection +{ + #field theCombinator. + #field theRole. + + #constructor new : aSet1 : aSet2 + [ + theRole := Activator2. + theCombinator := CombinatorWithRepetition new:(aSet1,aSet2). + ] + + #constructor new : aSet1 : aSet2 : aSet3 + [ + theRole := Activator3. + theCombinator := CombinatorWithRepetition new:(aSet1,aSet2,aSet3). + ] + + #constructor new : aSet1 : aSet2 : aSet3 : aSet4 + [ + theRole := Activator4. + theCombinator := CombinatorWithRepetition new:(aSet1,aSet2,aSet3,aSet4). + ] + + #constructor new : aSet1 : aSet2 : aSet3 : aSet4 : aSet5 + [ + theRole := Activator5. + theCombinator := CombinatorWithRepetition new:(aSet1,aSet2,aSet3,aSet4,aSet5). + ] + + #method seek : aCondition + [ + theCombinator reset. + + control while:[ theCombinator next ] &do: + [ + aCondition~theRole eval:(theCombinator get) ? + [ #break nil. ]. + ]. + ] + + #method do : aFunction + [ + #var aResult := theCombinator get. + nil != aResult + ? [ aFunction~theRole eval:aResult. ] + ! [ #throw InvalidArgumentException new. ]. + ] +} + +// --- ambOperator --- + +#symbol ambOperator = +{ + for : aSet1 : aSet2 + = AmbValueCollection new:aSet1:aSet2. + + for : aSet1 : aSet2 : aSet3 + = AmbValueCollection new:aSet1:aSet2:aSet3. + + for : aSet1 : aSet2 : aSet3 : aSet4 + = AmbValueCollection new:aSet1:aSet2:aSet3:aSet4. + + for : aSet1 : aSet2 : aSet3 : aSet4 : aSet5 + = AmbValueCollection new:aSet1:aSet2:aSet3:aSet4:aSet5. +}. + +// --- Program --- + +#symbol program = +[ + ambOperator for:(1,2,4):(4,5,6) seek: (:a:b) [ a * b == 8 ] do: (:a:b) + [ consoleEx writeLine: a : " * " : b : " = 8" ] + | if &InvalidArgumentError: e [ consoleEx writeLine:"AMB is angry". ]. + + ambOperator + for:("the","that","a"):("frog", "elephant", "thing"):("walked", "treaded", "grows"):("slowly", "quickly") + seek: (:a:b:c:d) [ (joinable:a:b) and:(joinable:b:c) and:(joinable:c:d) ] + do: (:a:b:c:d) [ consoleEx writeLine:a:" ":b:" ":c:" ":d. ] + | if &InvalidArgumentError: e [ consoleEx writeLine:"AMB is angry". ]. +]. diff --git a/Task/Amb/Factor/amb.factor b/Task/Amb/Factor/amb.factor new file mode 100644 index 0000000000..1de802fcbc --- /dev/null +++ b/Task/Amb/Factor/amb.factor @@ -0,0 +1,20 @@ +USING: backtrack continuations kernel prettyprint sequences ; +IN: amb + +CONSTANT: words { + { "the" "that" "a" } + { "frog" "elephant" "thing" } + { "walked" "treaded" "grows" } + { "slowly" "quickly" } +} + +: letters-match? ( str1 str2 -- ? ) [ last ] [ first ] bi* = ; + +: sentence-match? ( seq -- ? ) dup rest [ letters-match? ] 2all? ; + +: select ( seq -- seq' ) [ amb-lazy ] map ; + +: search ( -- ) + words select dup sentence-match? [ " " join ] [ fail ] if . ; + +MAIN: search diff --git a/Task/Amb/Go/amb-1.go b/Task/Amb/Go/amb-1.go new file mode 100644 index 0000000000..29599d532b --- /dev/null +++ b/Task/Amb/Go/amb-1.go @@ -0,0 +1,49 @@ +package main + +import ( + "fmt" + "sync" +) + +func ambStrings(ss []string) chan []string { + c := make(chan []string) + go func() { + for _, s := range ss { + c <- []string{s} + } + close(c) + }() + return c +} + +func ambChain(ss []string, cIn chan []string) chan []string { + cOut := make(chan []string) + go func() { + var w sync.WaitGroup + for chain := range cIn { + w.Add(1) + go func(chain []string) { + for s1 := range ambStrings(ss) { + if s1[0][len(s1[0])-1] == chain[0][0] { + cOut <- append(s1, chain...) + } + } + w.Done() + }(chain) + } + w.Wait() + close(cOut) + }() + return cOut +} + +func main() { + s1 := []string{"the", "that", "a"} + s2 := []string{"frog", "elephant", "thing"} + s3 := []string{"walked", "treaded", "grows"} + s4 := []string{"slowly", "quickly"} + c := ambChain(s1, ambChain(s2, ambChain(s3, ambStrings(s4)))) + for s := range c { + fmt.Println(s) + } +} diff --git a/Task/Amb/Go/amb-2.go b/Task/Amb/Go/amb-2.go new file mode 100644 index 0000000000..80e5a32d8a --- /dev/null +++ b/Task/Amb/Go/amb-2.go @@ -0,0 +1,39 @@ +package main +import "fmt" + +func amb(wordsets [][]string, res []string) bool { + if len(wordsets) == 0 { + return true + } + + var s string + + l := len(res) + if l > 0 { s = res[l - 1] } + + res = res[0:len(res) + 1] + + for _, res[l] = range(wordsets[0]) { + if l > 0 && s[len(s) - 1] != res[l][0] { continue } + + if amb(wordsets[1:len(wordsets)], res) { + return true + } + } + + return false +} + +func main() { + wordset := [][]string { { "the", "that", "a" }, + { "frog", "elephant", "thing" }, + { "walked", "treaded", "grows" }, + { "slowly", "quickly" } } + res := make([]string, len(wordset)) + + if amb(wordset, res[0:0]) { + fmt.Println(res) + } else { + fmt.Println("No amb found") + } +} diff --git a/Task/Amb/Haskell/amb.hs b/Task/Amb/Haskell/amb.hs new file mode 100644 index 0000000000..ee620710f3 --- /dev/null +++ b/Task/Amb/Haskell/amb.hs @@ -0,0 +1,15 @@ +import Control.Monad + +amb = id + +joins left right = last left == head right + +example = do + w1 <- amb ["the", "that", "a"] + w2 <- amb ["frog", "elephant", "thing"] + w3 <- amb ["walked", "treaded", "grows"] + w4 <- amb ["slowly", "quickly"] + unless (joins w1 w2) (amb []) + unless (joins w2 w3) (amb []) + unless (joins w3 w4) (amb []) + return (unwords [w1, w2, w3, w4]) diff --git a/Task/Amb/Haxe/amb.haxe b/Task/Amb/Haxe/amb.haxe new file mode 100644 index 0000000000..96a6ab598b --- /dev/null +++ b/Task/Amb/Haxe/amb.haxe @@ -0,0 +1,73 @@ +class RosettaDemo +{ + static var setA = ['the', 'that', 'a']; + static var setB = ['frog', 'elephant', 'thing']; + static var setC = ['walked', 'treaded', 'grows']; + static var setD = ['slowly', 'quickly']; + + static public function main() + { + Sys.print(ambParse([ setA, setB, setC, setD ]).toString()); + } + + static function ambParse(sets : Array>) + { + var ambData : Dynamic = amb(sets); + + for (data in 0...ambData.length) + { + var tmpData = parseIt(ambData[data]); + var tmpArray = tmpData.split(' '); + tmpArray.pop(); + if (tmpArray.length == sets.length) + { + return tmpData; + } + } + + return ''; + } + + static function amb(startingWith : String = '', sets : Array>) : Dynamic + { + if (sets.length == 0 || sets[0].length == 0) return; + + var match : Dynamic = []; + for (reference in sets[0]) + { + if (startingWith == '' || startingWith == reference.charAt(0)) + { + var lastChar = reference.charAt(reference.length-1); + if (Std.is(amb(lastChar, sets.slice(1)), Array)) + { + match.push([ reference, amb(lastChar, sets.slice(1))]); + } + else + { + match.push([ reference ]); + } + } + } + return match; + } + + static function parseIt(data : Dynamic) + { + var retData = ''; + if (Std.is(data, Array)) + { + for (elements in 0...data.length) + { + if (Std.is(data[elements], Array)) + { + retData = retData + parseIt(data[elements]); + } + else + { + retData = retData + data[elements] + ' '; + } + } + } + return retData; + } +} diff --git a/Task/Amb/Icon/amb.icon b/Task/Amb/Icon/amb.icon new file mode 100644 index 0000000000..313cb47a00 --- /dev/null +++ b/Task/Amb/Icon/amb.icon @@ -0,0 +1,18 @@ +procedure main() + s1 := ["the","that","a"] + s2 := ["frog","elephant","thing"] + s3 := ["walked","treaded","grows"] + s4 := ["slowly","quickly"] + + write(amb(!s1,!s2,!s3,!s4)) +end + +procedure amb(exprs[]) + s := "" + every e := !exprs do { + if \c ~== e[1] then fail + c := e[-1] + s ||:= e || " " + } + return s +end diff --git a/Task/Amb/J/amb-1.j b/Task/Amb/J/amb-1.j new file mode 100644 index 0000000000..e29a0283bf --- /dev/null +++ b/Task/Amb/J/amb-1.j @@ -0,0 +1,5 @@ + amb=. ([ , ' ' , ])&>/&.>@:((({:@:[ = {.@:])&>/&> # ])@:,@:({@(,&<))) + >@(amb&.>/) ('the';'that';'a');('frog';'elephant';'thing');('walked';'treaded';'grows');(<'slowly';'quickly') ++-----------------------+ +|that thing grows slowly| ++-----------------------+ diff --git a/Task/Amb/J/amb-2.j b/Task/Amb/J/amb-2.j new file mode 100644 index 0000000000..115740d4a9 --- /dev/null +++ b/Task/Amb/J/amb-2.j @@ -0,0 +1,4 @@ + ('the';'that';'a') amb ('frog';'elephant';'thing') amb ('walked';'treaded';'grows') amb ('slowly';'quickly') ++-----------------------+ +|that thing grows slowly| ++-----------------------+ diff --git a/Task/Amb/J/amb-3.j b/Task/Amb/J/amb-3.j new file mode 100644 index 0000000000..acbad858aa --- /dev/null +++ b/Task/Amb/J/amb-3.j @@ -0,0 +1,10 @@ + NB. Dynamic programming method... + + o=. @: NB. Composing verbs + success=. {:o[ = {.o] NB. Is the last letter of the left word equal to the first of the right? + join=. [ , ' ' , ] NB. Joining the left and right words + cp=. {@(,&<) NB. Cartesian product + + amb=. join&>/&.> o ((success&>/ &> # ]) o , o cp)f. + amb NB. Showing the point-free code... +([ , ' ' , ])&>/&.>@:((({:@:[ = {.@:])&>/&> # ])@:,@:({@(,&<))) diff --git a/Task/Amb/JavaScript/amb.js b/Task/Amb/JavaScript/amb.js new file mode 100644 index 0000000000..8cc231ee81 --- /dev/null +++ b/Task/Amb/JavaScript/amb.js @@ -0,0 +1,53 @@ +function ambRun(func) { + var choices = []; + var index; + + function amb(values) { + if (values.length == 0) { + fail(); + } + if (index == choices.length) { + choices.push({i: 0, + count: values.length}); + } + var choice = choices[index++]; + return values[choice.i]; + } + + function fail() { throw fail; } + + while (true) { + try { + index = 0; + return func(amb, fail); + } catch (e) { + if (e != fail) { + throw e; + } + var choice; + while ((choice = choices.pop()) && ++choice.i == choice.count) {} + if (choice == undefined) { + return undefined; + } + choices.push(choice); + } + } +} + +ambRun(function(amb, fail) { + function linked(s1, s2) { + return s1.slice(-1) == s2.slice(0, 1); + } + + var w1 = amb(["the", "that", "a"]); + var w2 = amb(["frog", "elephant", "thing"]); + if (!linked(w1, w2)) fail(); + + var w3 = amb(["walked", "treaded", "grows"]); + if (!linked(w2, w3)) fail(); + + var w4 = amb(["slowly", "quickly"]); + if (!linked(w3, w4)) fail(); + + return [w1, w2, w3, w4].join(' '); +}); // "that thing grows slowly" diff --git a/Task/Amb/Lua/amb-1.lua b/Task/Amb/Lua/amb-1.lua new file mode 100644 index 0000000000..be14fa39c1 --- /dev/null +++ b/Task/Amb/Lua/amb-1.lua @@ -0,0 +1,21 @@ +function amb (set) + local workset = {} + if (#set == 0) or (type(set) ~= 'table') then return end + if #set == 1 then return set end + if #set > 2 then + local first = table.remove(set,1) + set = amb(set) + for i,v in next,first do + for j,u in next,set do + if v:byte(#v) == u[1]:byte(1) then table.insert(workset, {v,unpack(u)}) end + end + end + return workset + end + for i,v in next,set[1] do + for j,u in next,set[2] do + if v:byte(#v) == u:byte(1) then table.insert(workset,{v,u}) end + end + end + return workset +end diff --git a/Task/Amb/Lua/amb-2.lua b/Task/Amb/Lua/amb-2.lua new file mode 100644 index 0000000000..2eb2ec36a6 --- /dev/null +++ b/Task/Amb/Lua/amb-2.lua @@ -0,0 +1,8 @@ +result = amb({{'the','that','a'},{'frog','elephant','thing'},{'walked','treaded','grows'},{'slowly','quickly'}}) +for i,v in next,result do + io.write (i,':\t') + for j,u in next,v do + io.write (u,' ') + end + io.write ('\n') +end diff --git a/Task/Amb/Mathematica/amb-1.math b/Task/Amb/Mathematica/amb-1.math new file mode 100644 index 0000000000..fdc821a3a0 --- /dev/null +++ b/Task/Amb/Mathematica/amb-1.math @@ -0,0 +1,3 @@ + CheckValid[i_List]:=If[Length[i]<=1,True,And@@(StringTake[#[[1]],-1]==StringTake[#[[2]],1]&/@Partition[i,2,1])] + sets={{"the","that","a"},{"frog","elephant","thing"},{"walked","treaded","grows"},{"slowly","quickly"}}; + Select[Tuples[sets],CheckValid] diff --git a/Task/Amb/Mathematica/amb-2.math b/Task/Amb/Mathematica/amb-2.math new file mode 100644 index 0000000000..b5b723c2b1 --- /dev/null +++ b/Task/Amb/Mathematica/amb-2.math @@ -0,0 +1 @@ +{{"that", "thing", "grows", "slowly"}} diff --git a/Task/Amb/Mathematica/amb-3.math b/Task/Amb/Mathematica/amb-3.math new file mode 100644 index 0000000000..8ed7cf413e --- /dev/null +++ b/Task/Amb/Mathematica/amb-3.math @@ -0,0 +1 @@ +CheckValid2[i_List] := StringFreeQ[StringJoin[Riffle[i, ","]], a_ ~~ "," ~~ b_ /; a =!= b] diff --git a/Task/Amb/Mercury/amb-1.mercury b/Task/Amb/Mercury/amb-1.mercury new file mode 100644 index 0000000000..60c9132fb4 --- /dev/null +++ b/Task/Amb/Mercury/amb-1.mercury @@ -0,0 +1,25 @@ +:- module amb. +:- interface. +:- import_module io. +:- pred main(io::di, io::uo) is cc_multi. +:- implementation. +:- import_module list, string, char, int. + +main(!IO) :- + ( solution(S) -> io.write_string(S, !IO), io.nl(!IO) + ; io.write_string("No solutions found :-(\n", !IO) ). + +:- pred solution(string::out) is nondet. +solution(S) :- + member(A, ["the", "that", "a"]), + member(N, ["frog", "elephant", "thing"]), + member(V, ["walked", "treaded", "grows"]), + member(E, ["slowly", "quickly"]), + S = join_list(" ", [A, N, V, E]), + rule1(A, N), rule1(N, V), rule1(V, E). + +:- pred rule1(string::in, string::in) is semidet. +rule1(A, B) :- last_char(A) = C, first_char(B, C, _). + +:- func last_char(string::in) = (char::out) is semidet. +last_char(S) = C :- index(S, length(S) - 1, C). diff --git a/Task/Amb/Mercury/amb-2.mercury b/Task/Amb/Mercury/amb-2.mercury new file mode 100644 index 0000000000..c700761e35 --- /dev/null +++ b/Task/Amb/Mercury/amb-2.mercury @@ -0,0 +1,6 @@ +:- pred noun(string). +:- mode noun(out) is multi. % provide any one noun. +:- mode noun(in) is semidet. % fail if given string isn't a known noun. +noun("frog"). +noun("elephant"). +noun("thing"). diff --git a/Task/Amb/NetRexx/amb.netrexx b/Task/Amb/NetRexx/amb.netrexx new file mode 100644 index 0000000000..ca4c51334e --- /dev/null +++ b/Task/Amb/NetRexx/amb.netrexx @@ -0,0 +1,71 @@ + /* REXX ************************************************************** + * 25.08.2013 Walter Pachl derived from REXX version 2 + *********************************************************************/ + w='' + l=0 + mm=0 + mkset(1,'the that a if',w,mm,l) + mkset(2,'frog elephant thing',w,mm,l) + mkset(3,'walked treaded grows trots',w,mm,l) + mkset(4,'slowly quickly',w,mm,l) + show(w,mm,l) + + Loop i=1 to 3 /* loop over sets */ + k=i+1 /* the following set */ + Loop ii=1 To 10 /* loop over elements in set k*/ + If w[i,ii].words=i Then Do /* a sentence part found */ + Loop jj=1 To 10 /* loop over following words */ + If w[i,ii].right(1)=w[k,jj].left(1) Then Do /* fitting */ + ns=w[i,ii]' 'w[k,jj] /* build new sentence (part) */ + If ns.words=k Then /* 'complete' part */ + add(w,k,ns) /* add to set k */ + End + End + End + End + End + Say 'Results:' + Loop jj=1 To 10 /* show the results */ + If w[4,jj].words=4 Then + Say '-->' w[4,jj] + End + + method add(w,k,s) public static + /********************************************************************* + * add a fitting sentence (part) s to set w[k,*] + *********************************************************************/ + Loop i=1 To 10 While w[k,i]>'' /* look for an empty slot */ + End + w[k,i]=s /* add the sentence (part) */ + Return + + method mkset(n,arg,smp,mm,l) public static + /********************************************************************* + * create set smp[n,*] from data in arg + * mm[0] maximum number of elements in any set + * l[n] maximum word length in set n + *********************************************************************/ + loop i = 1 to arg.words + smp[n,i] = arg.word(i) + If smp[n,i].length>l[n] Then + l[n]=smp[n,i].length + end + if i-1>mm[0] Then Do + mm[0]=i-1 + End + return + + method show(w,mm,l) public static + /********************************************************************* + * show the input + *********************************************************************/ + Say 'Input:' + Loop j=1 To mm[0] /* output lines */ + ol='' + Loop i=1 To 4 + ol=ol w[i,j].left(l[i]) + End + Say ol.strip + End; + say '' + Return diff --git a/Task/Amb/OCaml/amb-1.ocaml b/Task/Amb/OCaml/amb-1.ocaml new file mode 100644 index 0000000000..1e80256083 --- /dev/null +++ b/Task/Amb/OCaml/amb-1.ocaml @@ -0,0 +1,36 @@ +let set_1 = ["the"; "that"; "a"] +let set_2 = ["frog"; "elephant"; "thing"] +let set_3 = ["walked"; "treaded"; "grows"] +let set_4 = ["slowly"; "quickly"] + +let combs ll = + let rec aux acc = function + | [] -> (List.map List.rev acc) + | hd::tl -> + let acc = + List.fold_left + (fun _ac l -> + List.fold_left (fun _ac v -> (v::l)::_ac) _ac hd + ) [] acc + in + aux acc tl + in + aux [[]] ll + +let last s = s.[pred(String.length s)] +let joined a b = (last a = b.[0]) + +let rec test = function + | a::b::tl -> (joined a b) && (test (b::tl)) + | _ -> true + +let print_set set = + List.iter (Printf.printf " %s") set; + print_newline(); +;; + +let () = + let sets = combs [set_1; set_2; set_3; set_4] in + let sets = List.filter test sets in + List.iter print_set sets; +;; diff --git a/Task/Amb/OCaml/amb-2.ocaml b/Task/Amb/OCaml/amb-2.ocaml new file mode 100644 index 0000000000..2f792d447f --- /dev/null +++ b/Task/Amb/OCaml/amb-2.ocaml @@ -0,0 +1,51 @@ +let set_1 = [| "the"; "that"; "a" |] +let set_2 = [| "frog"; "elephant"; "thing" |] +let set_3 = [| "walked"; "treaded"; "grows" |] +let set_4 = [| "slowly"; "quickly" |] + +let comb_search p aa = + let nx = Array.make (Array.length aa) 0 in + let lx = Array.map Array.length aa in + let la = Array.length aa in + let rec loop() = + let res = Array.mapi (fun i j -> aa.(i).(j)) nx in + if p res then (res) + else + ( nx.(0) <- nx.(0) + 1; + if nx.(0) < lx.(0) + then loop() + else + ( nx.(0) <- 0; + let rec roll n = + if n >= la then raise Not_found + else + ( nx.(n) <- nx.(n) + 1; + if nx.(n) >= lx.(n) + then ( nx.(n) <- 0; roll (n+1) ) + else loop() + ) + in + roll 1 + ) + ) + in + loop() + +let last s = s.[pred(String.length s)] +let joined a b = (last a = b.[0]) + +let rec test = function + | a::b::tl -> (joined a b) && (test (b::tl)) + | _ -> true + +let test r = test(Array.to_list r) + +let print_set set = + Array.iter (Printf.printf " %s") set; + print_newline(); +;; + +let () = + let result = comb_search test [| set_1; set_2; set_3; set_4 |] in + print_set result; +;; diff --git a/Task/Amb/OpenEdge-Progress/amb.openedge b/Task/Amb/OpenEdge-Progress/amb.openedge new file mode 100644 index 0000000000..7f2802be52 --- /dev/null +++ b/Task/Amb/OpenEdge-Progress/amb.openedge @@ -0,0 +1,36 @@ +DEF VAR cset AS CHAR EXTENT 4 INIT [ + "the,that,a", + "frog,elephant,thing", + "walked,treaded,grows", + "slowly,quickly" +]. + +FUNCTION getAmb RETURNS CHARACTER ( + i_cwords AS CHAR, + i_iset AS INT +): + + DEF VAR cresult AS CHAR. + DEF VAR ii AS INT. + DEF VAR cword AS CHAR. + + DO ii = 1 TO NUM-ENTRIES( cset [ i_iset ] ) WHILE NUM-ENTRIES( cresult, " " ) < EXTENT( cset ): + + cword = ENTRY( ii, cset[ i_iset ] ). + IF i_cwords = "" OR + SUBSTRING( i_cwords, LENGTH( i_cwords ), 1 ) = SUBSTRING( cword, 1, 1 ) + THEN DO: + IF i_iset = EXTENT ( cset ) THEN + cresult = i_cwords + " " + cword. + ELSE + cresult = getAmb( i_cwords + " " + cword, i_iset + 1 ). + END. + + END. + + RETURN cresult. + +END FUNCTION. /* getAmb */ + + +MESSAGE getAmb( "", 1 ) VIEW-AS ALERT-BOX. diff --git a/Task/Amb/Oz/amb.oz b/Task/Amb/Oz/amb.oz new file mode 100644 index 0000000000..aa96eef8c5 --- /dev/null +++ b/Task/Amb/Oz/amb.oz @@ -0,0 +1,27 @@ +declare + + fun {Amb Xs} + case Xs of nil then fail + [] [X] then X + [] X|Xr then + choice X + [] {Amb Xr} + end + end + end + + fun {Example} + W1 = {Amb ["the" "that" "a"]} + W2 = {Amb ["frog" "elephant" "thing"]} + W3 = {Amb ["walked" "treaded" "grows"]} + W4 = {Amb ["slowly" "quickly"]} + in + {List.last W1 W2.1} + {List.last W2 W3.1} + {List.last W3 W4.1} + W1#" "#W2#" "#W3#" "#W4 + end + +in + + {ForAll {SearchAll Example} System.showInfo} diff --git a/Task/Amb/PARI-GP/amb.pari b/Task/Amb/PARI-GP/amb.pari new file mode 100644 index 0000000000..45af9983a1 --- /dev/null +++ b/Task/Amb/PARI-GP/amb.pari @@ -0,0 +1,16 @@ +Amb(V)={ + amb(vector(#V,i,vector(#V[i],j,Vec(V[i][j]))),[]) +}; +amb(V,s)={ + if (#V == 0, return(concat(s))); + my(v=V[1],U=vecextract(V,2^#V-2),t,final=if(#s,s[#s])); + if(#s, s = concat(s,[" "])); + for(i=1,#v, + if ((#s == 0 | final == v[i][1]), + t = amb(U, concat(s, v[i])); + if (t, return(t)) + ) + ); + 0 +}; +Amb([["the","that","a"],["frog","elephant","thing"],["walked","treaded","grows"],["slowly","quickly"]]) diff --git a/Task/Amb/PL-I/amb.pli b/Task/Amb/PL-I/amb.pli new file mode 100644 index 0000000000..3d572cc848 --- /dev/null +++ b/Task/Amb/PL-I/amb.pli @@ -0,0 +1,86 @@ +*process or(!) source attributes xref; + amb: Proc Options(main); + /********************************************************************* + * 25.08.2013 Walter Pachl + *********************************************************************/ + Dcl w(4,10) Char(40) Var + Init('the','that','a','if',(6)(1)' ', + 'frog','elephant','thing',(7)(1)' ', + 'walked','treaded','grows','trots',(6)(1)' ', + 'slowly','quickly',(8)(1)' '); + Dcl ns Char(40) Var; + Dcl (i,k,j,ii,jj,m,n) Bin Fixed(31); + n=hbound(w,1); /* number of sets */ + m=hbound(w,2); /* max number of words in set */ + Call show; /* show the input */ + Do i=1 To n-1; /* loop over sets */ + k=i+1; /* the following set */ + Do ii=1 To m; /* loop over elements in set k*/ + If words(w(i,ii))=i Then Do; /* a sentence part found */ + Do jj=1 To m; /* loop over following words */ + If right(w(i,ii),1)=left(w(k,jj),1) Then Do; /* fitting */ + ns=w(i,ii)!!' '!!w(k,jj); /* build new sentence (part) */ + If words(ns)=k Then /* 'complete' part */ + Call add(k,ns); /* add to set k */ + End; + End; + End; + End; + Do jj=1 To m; /* show the results */ + If words(w(4,jj))=4 Then + put edit('--> ',w(4,jj))(Skip,a,a); + End; + + add: Proc(ni,s); + /********************************************************************* + * add a sentence (part) to set ni + *********************************************************************/ + Dcl (i,ni) Bin Fixed(31); + Dcl s Char(40) Var; + Do i=1 To m While(w(ni,i)>''); /* look for an empty slot */ + End; + w(ni,i)=s; /* add the sentence (part) */ + End; + + words: Proc(s) Returns(Bin Fixed(31)); + /********************************************************************* + * return the number of blank separated words in s + *********************************************************************/ + Dcl s Char(40) Var; + Dcl nw Bin Fixed(31) Init(0); + Dcl i Bin Fixed(31) Init(1); + If s>'' Then Do; + nw=1; + Do i=1 To length(s); + If substr(s,i,1)=' ' Then + nw+=1; + End; + End; + Return(nw); + End; + + show: Proc; + /********************************************************************* + * show the input sets + *********************************************************************/ + Dcl (i,j,mm) Bin Fixed(31) Init(0); + Dcl l(4) Bin Fixed(31) Init((4)0); + Do i=1 To n; + Do j=1 To m; + If w(i,j)>'' Then Do; + mm=max(mm,j); /* max number of words in any set */ + l(i)=max(l(i),length(w(i,j))); /* max word length in set i */ + End; + End; + End; + Put Edit('Input:')(Skip,a); + Do j=1 To mm; /* output lines */ + Put Skip; + Do i=1 To n; + Put Edit(w(i,j),' ')(a(l(i)),a); + End; + End; + Put Skip; + End; + + End; diff --git a/Task/Amb/Perl-6/amb-1.pl6 b/Task/Amb/Perl-6/amb-1.pl6 new file mode 100644 index 0000000000..d62d77b93d --- /dev/null +++ b/Task/Amb/Perl-6/amb-1.pl6 @@ -0,0 +1,18 @@ +sub infix: ($a,$b) { + next unless try $a.substr(*-1,1) eq $b.substr(0,1); + "$a $b"; +} + +multi dethunk(Callable $x) { try take $x() } +multi dethunk( Any $x) { take $x } + +sub amb (*@c) { gather @c».&dethunk } + +say first *, do + amb(, { die 'oops'}) Xlf + amb('frog',{'elephant'},'thing') Xlf + amb() Xlf + amb { die 'poison dart' }, + {'slowly'}, + {'quickly'}, + { die 'fire' }; diff --git a/Task/Amb/Perl-6/amb-2.pl6 b/Task/Amb/Perl-6/amb-2.pl6 new file mode 100644 index 0000000000..d5d5695a94 --- /dev/null +++ b/Task/Amb/Perl-6/amb-2.pl6 @@ -0,0 +1,18 @@ +sub amb($var,*@a) { + "[{ + @a.pick(*).map: {"||\{ $var = '$_' }"} + }]"; +} + +'' ~~ m/ + :my ($a,$b,$c,$d); + <{ amb '$a', }> + <{ amb '$b', }> + + <{ amb '$c', }> + + <{ amb '$d', }> + + { say "$a $b $c $d" } + +/; diff --git a/Task/Amb/Perl/amb-1.pl b/Task/Amb/Perl/amb-1.pl new file mode 100644 index 0000000000..7dca79558a --- /dev/null +++ b/Task/Amb/Perl/amb-1.pl @@ -0,0 +1,35 @@ +use strict; +use warnings; + +use constant EXIT_FAILURE => 1; +use constant EXIT_SUCCESS => 0; + +sub amb { + exit(EXIT_FAILURE) if !@_; + for my $word (@_) { + my $pid = fork; + die $! unless defined $pid; + return $word if !$pid; + my $wpid = waitpid $pid, 0; + die $! unless $wpid == $pid; + exit(EXIT_SUCCESS) if $? == EXIT_SUCCESS; + } + exit(EXIT_FAILURE); +} + +sub joined { + my ($join_a, $join_b) = @_; + substr($join_a, -1) eq substr($join_b, 0, 1); +} + +my $w1 = amb(qw(the that a)); +my $w2 = amb(qw(frog elephant thing)); +my $w3 = amb(qw(walked treaded grows)); +my $w4 = amb(qw(slowly quickly)); + +amb() unless joined $w1, $w2; +amb() unless joined $w2, $w3; +amb() unless joined $w3, $w4; + +print "$w1 $w2 $w3 $w4\n"; +exit(EXIT_SUCCESS); diff --git a/Task/Amb/Perl/amb-2.pl b/Task/Amb/Perl/amb-2.pl new file mode 100644 index 0000000000..1323079790 --- /dev/null +++ b/Task/Amb/Perl/amb-2.pl @@ -0,0 +1,40 @@ +use strict; +use warnings; + +sub amb { + if( @_ == 0 ) { + no warnings 'exiting'; + next AMB; + } + my $code = pop; + my @words = @_; + my @index = (0) x @words; + AMB: while( 1 ) { + my @w = map $words[$_][$index[$_]], 0 .. $#_; + return $code->( @w ); + } continue { + my $i = 0; + while( ++$index[$i] == @{$words[$i]} ) { + $index[$i] = 0; + return if ++$i == @index; + } + } +} + +my @w1 = qw(the that a); +my @w2 = qw(frog elephant thing); +my @w3 = qw(walked treaded grows); +my @w4 = qw(slowly quickly); + +sub joined { + my ($join_a, $join_b) = @_; + substr($join_a, -1) eq substr($join_b, 0, 1); +} + +amb( \(@w1, @w2, @w3, @w4), sub { + my ($w1, $w2, $w3, $w4) = @_; + amb() unless joined($w1, $w2); + amb() unless joined($w2, $w3); + amb() unless joined($w3, $w4); + print "$w1 $w2 $w3 $w4\n"; +}); diff --git a/Task/Amb/PicoLisp/amb.l b/Task/Amb/PicoLisp/amb.l new file mode 100644 index 0000000000..be418db426 --- /dev/null +++ b/Task/Amb/PicoLisp/amb.l @@ -0,0 +1,18 @@ +(be amb (@E @Lst) + (lst @E @Lst) ) + +(be joins (@Left @Right) + (^ @T (last (chop (-> @Left)))) + (^ @R (car (chop (-> @Right)))) + (or + ((equal @T @R)) + ((amb @ NIL)) ) ) # Explicitly using amb fail as required + +(be ambExample ((@Word1 @Word2 @Word3 @Word4)) + (amb @Word1 ("the" "that" "a")) + (amb @Word2 ("frog" "elephant" "thing")) + (amb @Word3 ("walked" "treaded" "grows")) + (amb @Word4 ("slowly" "quickly")) + (joins @Word1 @Word2) + (joins @Word2 @Word3) + (joins @Word3 @Word4) ) diff --git a/Task/Amb/Prolog/amb.pro b/Task/Amb/Prolog/amb.pro new file mode 100644 index 0000000000..09f80f9c85 --- /dev/null +++ b/Task/Amb/Prolog/amb.pro @@ -0,0 +1,17 @@ +amb(E, [E|_]). +amb(E, [_|ES]) :- amb(E, ES). + +joins(Left, Right) :- + append(_, [T], Left), + append([R], _, Right), + ( T \= R -> amb(_, []) % (explicitly using amb fail as required) + ; true ). + +amb_example([Word1, Word2, Word3, Word4]) :- + amb(Word1, ["the","that","a"]), + amb(Word2, ["frog","elephant","thing"]), + amb(Word3, ["walked","treaded","grows"]), + amb(Word4, ["slowly","quickly"]), + joins(Word1, Word2), + joins(Word2, Word3), + joins(Word3, Word4). diff --git a/Task/Amb/PureBasic/amb.purebasic b/Task/Amb/PureBasic/amb.purebasic new file mode 100644 index 0000000000..26a054230e --- /dev/null +++ b/Task/Amb/PureBasic/amb.purebasic @@ -0,0 +1,44 @@ +Procedure Words_Ok(String1.s, String2.s) + If Mid(String1,Len(String1),1)=Mid(String2,1,1) + ProcedureReturn #True + EndIf + ProcedureReturn #False +EndProcedure + +Procedure.s Amb(Array A.s(1), Array B.s(1), Array C.s(1), Array D.s(1)) + Protected a, b, c, d + For a=0 To ArraySize(A()) + For b=0 To ArraySize(B()) + For c=0 To ArraySize(C()) + For d=0 To ArraySize(D()) + If Words_Ok(A(a),B(b)) And Words_Ok(B(b),C(c)) And Words_Ok(C(c),D(d)) + ProcedureReturn A(a)+" "+B(b)+" "+C(c)+" "+D(d) + EndIf + Next + Next + Next + Next + ProcedureReturn "" ; Empty string, e.g. fail +EndProcedure + +If OpenConsole() + Define Text.s + Dim Set1.s(2) + Dim Set2.s(2) + Dim Set3.s(2) + Dim Set4.s(1) + + Set1(0)="the": set1(1)="that": set1(2)="a" + Set2(0)="frog": set2(1)="elephant": set2(2)="thing" + Set3(0)="walked": set3(1)="treaded": set3(2)="grows" + Set4(0)="slowly": set4(1)="quickly" + + text=Amb(set1(),set2(),Set3(),set4()) + If Text<>"" + PrintN("Correct sentence would be,"+#CRLF$+Text) + Else + PrintN("Failed to fine a correct sentence.") + EndIf + PrintN(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() + CloseConsole() +EndIf diff --git a/Task/Amb/Python/amb.py b/Task/Amb/Python/amb.py new file mode 100644 index 0000000000..485ff38852 --- /dev/null +++ b/Task/Amb/Python/amb.py @@ -0,0 +1,100 @@ +import itertools as _itertools + +class Amb(object): + def __init__(self): + self._names2values = {} # set of values for each global name + self._func = None # Boolean constraint function + self._valueiterator = None # itertools.product of names values + self._funcargnames = None # Constraint parameter names + + def __call__(self, arg=None): + if hasattr(arg, '__code__'): + ## + ## Called with a constraint function. + ## + globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals + # Names used in constraint + argv = arg.__code__.co_varnames[:arg.__code__.co_argcount] + for name in argv: + if name not in self._names2values: + assert name in globls, \ + "Global name %s not found in function globals" % name + self._names2values[name] = globls[name] + # Gather the range of values of all names used in the constraint + valuesets = [self._names2values[name] for name in argv] + self._valueiterator = _itertools.product(*valuesets) + self._func = arg + self._funcargnames = argv + return self + elif arg is not None: + ## + ## Assume called with an iterable set of values + ## + arg = frozenset(arg) + return arg + else: + ## + ## blank call tries to return next solution + ## + return self._nextinsearch() + + def _nextinsearch(self): + arg = self._func + globls = arg.__globals__ + argv = self._funcargnames + found = False + for values in self._valueiterator: + if arg(*values): + # Set globals. + found = True + for n, v in zip(argv, values): + globls[n] = v + break + if not found: raise StopIteration + return values + + def __iter__(self): + return self + + def __next__(self): + return self() + next = __next__ # Python 2 + +if __name__ == '__main__': + if True: + amb = Amb() + + print("\nSmall Pythagorean triples problem:") + x = amb(range(1,11)) + y = amb(range(1,11)) + z = amb(range(1,11)) + + for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ): + print ('%s %s %s' % (x, y, z)) + + + if True: + amb = Amb() + + print("\nRosetta Code Amb problem:") + w1 = amb(["the", "that", "a"]) + w2 = amb(["frog", "elephant", "thing"]) + w3 = amb(["walked", "treaded", "grows"]) + w4 = amb(["slowly", "quickly"]) + + for _dummy in amb( lambda w1, w2, w3, w4: \ + w1[-1] == w2[0] and \ + w2[-1] == w3[0] and \ + w3[-1] == w4[0] ): + print ('%s %s %s %s' % (w1, w2, w3, w4)) + + if True: + amb = Amb() + + print("\nAmb problem from " + "http://www.randomhacks.net/articles/2005/10/11/amb-operator:") + x = amb([1, 2, 3]) + y = amb([4, 5, 6]) + + for _dummy in amb( lambda x, y: x * y != 8 ): + print ('%s %s' % (x, y)) diff --git a/Task/Amb/R/amb-1.r b/Task/Amb/R/amb-1.r new file mode 100644 index 0000000000..2b2a86bb40 --- /dev/null +++ b/Task/Amb/R/amb-1.r @@ -0,0 +1,23 @@ +checkSentence <- function(sentence){ +# Input: character vector +# Output: whether the sentence formed by the elements of the vector is valid + for (index in 1:(length(sentence)-1)){ + first.word <- sentence[index] + second.word <- sentence[index+1] + + last.letter <- substr(first.word, nchar(first.word), nchar(first.word)) + first.letter <- substr(second.word, 1, 1) + + if (last.letter != first.letter){ return(FALSE) } + } + return(TRUE) +} + +amb <- function(sets){ +# Input: list of character vectors containing all sets to consider +# Output: list of character vectors that are valid + all.paths <- apply(expand.grid(sets), 2, as.character) + all.paths.list <- split(all.paths, 1:nrow(all.paths)) + winners <- all.paths.list[sapply(all.paths.list, checkSentence)] + return(winners) +} diff --git a/Task/Amb/R/amb-2.r b/Task/Amb/R/amb-2.r new file mode 100644 index 0000000000..73616a1824 --- /dev/null +++ b/Task/Amb/R/amb-2.r @@ -0,0 +1,14 @@ +sentence1 <- c("that", "thing", "grows", "slowly") +sentence2 <- c("rosetta", "code", "is", "cool") +sentence <- list(sentence1, sentence2) +sapply(sentence, checkSentence) +[1] TRUE FALSE + +set1 <- c("the", "that", "a") +set2 <- c("frog", "elephant", "thing") +set3 <- c("walked", "treaded", "grows") +set4 <- c("slowly", "quickly") +sets <- list(set1, set2, set3, set4) +amb(sets) +$`26` +[1] "that" "thing" "grows" "slowly" diff --git a/Task/Amb/README b/Task/Amb/README new file mode 100644 index 0000000000..7316bfdebd --- /dev/null +++ b/Task/Amb/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Amb diff --git a/Task/Amb/REXX/amb-1.rexx b/Task/Amb/REXX/amb-1.rexx new file mode 100644 index 0000000000..0aa5fcdb4a --- /dev/null +++ b/Task/Amb/REXX/amb-1.rexx @@ -0,0 +1,22 @@ +/*REXX program demonstrates Amd operator, choosing a word from each set.*/ +@.= /*default value for any # of sets*/ +@.1 = "the that a" +@.2 = "frog elephant thing" +@.3 = "walked treaded grows" +@.4 = "slowly quickly" + do j=1 until @.j==''; end; @.0=j-1 /*set @.0 to the number of sets.*/ +call Amb 1 /*find combo of words that works.*/ +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────────AMB procedure────────────────────*/ +Amb: procedure expose @.; parse arg # _; arg . u; if #=='' then return +if #>@.0 then do; if u=='' then return /*return if no words are left. */ + w=word(u,1) /*use upper case version of word.*/ + do n=2 to words(u); c=word(u,n) + if left(c,1)\==right(w,1) then return; w=c + end /*n*/ + say strip(_) /* _ has an extra leading blank. */ + end + do k=1 for words(@.#) + call amb #+1 _ word(@.#,k) /*generate the next combination. */ + end /*k*/ +return diff --git a/Task/Amb/REXX/amb-2.rexx b/Task/Amb/REXX/amb-2.rexx new file mode 100644 index 0000000000..d2492ea0a5 --- /dev/null +++ b/Task/Amb/REXX/amb-2.rexx @@ -0,0 +1,85 @@ + /* REXX ************************************************************** + * 25.08.2013 Walter Pachl derived from PL/I + *********************************************************************/ + mm=0 + w.='' + l.=0 + Call mkset 1,'the that a if' + Call mkset 2,'frog elephant thing' + Call mkset 3,'walked treaded grows trots' + Call mkset 4,'slowly quickly' + + Call show + Do i=1 to 3 /* loop over sets */ + Call showm + k=i+1 /* the following set */ + Do ii=1 To 10 /* loop over elements in set k*/ + If words(w.i.ii)=i Then Do /* a sentence part found */ + Do jj=1 To 10 /* loop over following words */ + If right(w.i.ii,1)=left(w.k.jj,1) Then Do /* fitting */ + ns=w.i.ii' 'w.k.jj /* build new sentence (part) */ + If words(ns)=k Then /* 'complete' part */ + Call add k,ns /* add to set k */ + End + End + End + End + End + + Do jj=1 To 10 /* show the results */ + If words(w.4.jj)=4 Then + Say '-->' w.4.jj + End + Return + + add: Procedure Expose w. + /********************************************************************* + * add a sentence (part) to set ni + *********************************************************************/ + Parse Arg ni,s + Do i=1 To 10 While w.ni.i>'' /* look for an empty slot */ + End + w.ni.i=s /* add the sentence (part) */ + Return + + mkset: Procedure Expose w. mm l. + /********************************************************************* + * initialize the sets + *********************************************************************/ + Parse Arg i,wl + Do j=1 By 1 While wl<>'' + Parse Var wl w.i.j wl + l.i=max(l.i,length(w.i.j)) + End + mm=max(mm,j-1) + Return + +show: Procedure Expose w. mm l. + /********************************************************************* + * show the input + *********************************************************************/ + Say 'Input:' + Do j=1 To mm /* output lines */ + ol='' + Do i=1 To 4 + ol=ol left(w.i.j,l.i) + End + Say strip(ol) + End; + say '' + Return + +showm: Procedure Expose w. + /********************************************************************* + * show the sets' contents + *********************************************************************/ + dbg=0 + If dbg Then Do + Do i=1 To 4 + Do j=1 To 10 + If w.i.j>'' Then + Say i j w.i.j + End + End + End + Return diff --git a/Task/Amb/Racket/amb.rkt b/Task/Amb/Racket/amb.rkt new file mode 100644 index 0000000000..6d761c6dab --- /dev/null +++ b/Task/Amb/Racket/amb.rkt @@ -0,0 +1,30 @@ +#lang racket + +;; A quick `amb' implementation (same as in the Twelve Statements task) +(define failures null) + +(define (fail) + (if (pair? failures) ((first failures)) (error "no more choices!"))) + +(define (amb/thunks choices) + (let/cc k (set! failures (cons k failures))) + (if (pair? choices) + (let ([choice (first choices)]) (set! choices (rest choices)) (choice)) + (begin (set! failures (rest failures)) (fail)))) + +(define-syntax-rule (amb E ...) (amb/thunks (list (lambda () E) ...))) + +(define (assert condition) (unless condition (fail))) + +;; Problem solution + +(define (joins? left right) + (regexp-match? #px"(.)\0\\1" (~a left "\0" right))) + +(let ([result (list (amb "the" "that" "a") + (amb "frog" "elephant" "thing") + (amb "walked" "treaded" "grows") + (amb "slowly" "quickly"))]) + (for ([x result] [y (cdr result)]) (assert (joins? x y))) + result) +;; -> '("that" "thing" "grows" "slowly") diff --git a/Task/Amb/Ruby/amb.rb b/Task/Amb/Ruby/amb.rb new file mode 100644 index 0000000000..8b13f0bf76 --- /dev/null +++ b/Task/Amb/Ruby/amb.rb @@ -0,0 +1,47 @@ +class Amb + class ExhaustedError < RuntimeError; end + + def initialize + @fail = proc { fail ExhaustedError, "amb tree exhausted" } + end + + def choose(*choices) + prev_fail = @fail + callcc { |sk| + choices.each { |choice| + callcc { |fk| + @fail = proc { + @fail = prev_fail + fk.call(:fail) + } + if choice.respond_to? :call + sk.call(choice.call) + else + sk.call(choice) + end + } + } + @fail.call + } + end + + def failure + choose + end + + def assert(cond) + failure unless cond + end +end + +A = Amb.new +w1 = A.choose("the", "that", "a") +w2 = A.choose("frog", "elephant", "thing") +w3 = A.choose("walked", "treaded", "grows") +w4 = A.choose("slowly", "quickly") + +A.choose() unless w1[-1] == w2[0] +A.choose() unless w2[-1] == w3[0] +A.choose() unless w3[-1] == w4[0] + +puts w1, w2, w3, w4 diff --git a/Task/Amb/SETL/amb-1.setl b/Task/Amb/SETL/amb-1.setl new file mode 100644 index 0000000000..e0e263731f --- /dev/null +++ b/Task/Amb/SETL/amb-1.setl @@ -0,0 +1,15 @@ +program amb; + +sets := unstr('[{the that a} {frog elephant thing} {walked treaded grows} {slowly quickly}]'); + +words := [amb(words): words in sets]; +if exists lWord = words(i), rWord in {words(i+1)} | + lWord(#lWord) /= rWord(1) then + fail; +end if; + +proc amb(words); + return arb {word in words | ok}; +end proc; + +end program; diff --git a/Task/Amb/SETL/amb-2.setl b/Task/Amb/SETL/amb-2.setl new file mode 100644 index 0000000000..be137522ab --- /dev/null +++ b/Task/Amb/SETL/amb-2.setl @@ -0,0 +1,26 @@ +program amb; + +sets := unstr('[{the that a} {frog elephant thing} {walked treaded grows} {slowly quickly}]'); + +print(amb(sets)); + +proc amb(sets); + return amb1([], {}, sets); +end proc; + +proc amb1(prev, mbLast, sets); + if sets = [] then + return prev; + else + words fromb sets; + if exists word in words | + (forall last in mbLast | + last(#last) = word(1)) and + (exists sentence in {amb1(prev with word, {word}, sets)} | + true) then + return sentence; + end if; + end if; +end proc; + +end program; diff --git a/Task/Amb/Scala/amb.scala b/Task/Amb/Scala/amb.scala new file mode 100644 index 0000000000..04e95f4e51 --- /dev/null +++ b/Task/Amb/Scala/amb.scala @@ -0,0 +1,20 @@ +object Amb { + + def amb(wss: List[List[String]]): Option[String] = { + def _amb(ws: List[String], wss: List[List[String]]): Option[String] = wss match { + case Nil => ((Some(ws.head): Option[String]) /: ws.tail)((a, w) => a match { + case Some(x) => if (x.last == w.head) Some(x + " " + w) else None + case None => None + }) + case ws1 :: wss1 => ws1.flatMap(w => _amb(w :: ws, wss1)).headOption + } + _amb(Nil, wss.reverse) + } + + def main(args: Array[String]) { + println(amb(List(List("the", "that", "a"), + List("frog", "elephant", "thing"), + List("walked", "treaded", "grows"), + List("slowly", "quickly")))) + } +} diff --git a/Task/Amb/Scheme/amb.ss b/Task/Amb/Scheme/amb.ss new file mode 100644 index 0000000000..951db6f220 --- /dev/null +++ b/Task/Amb/Scheme/amb.ss @@ -0,0 +1,34 @@ +(define fail + (lambda () + (error "Amb tree exhausted"))) + +(define-syntax amb + (syntax-rules () + ((AMB) (FAIL)) ; Two shortcuts. + ((AMB expression) expression) + + ((AMB expression ...) + (LET ((FAIL-SAVE FAIL)) + ((CALL-WITH-CURRENT-CONTINUATION ; Capture a continuation to + (LAMBDA (K-SUCCESS) ; which we return possibles. + (CALL-WITH-CURRENT-CONTINUATION + (LAMBDA (K-FAILURE) ; K-FAILURE will try the next + (SET! FAIL K-FAILURE) ; possible expression. + (K-SUCCESS ; Note that the expression is + (LAMBDA () ; evaluated in tail position + expression)))) ; with respect to AMB. + ... + (SET! FAIL FAIL-SAVE) ; Finally, if this is reached, + FAIL-SAVE))))))) ; we restore the saved FAIL. + + +(let ((w-1 (amb "the" "that" "a")) + (w-2 (amb "frog" "elephant" "thing")) + (w-3 (amb "walked" "treaded" "grows")) + (w-4 (amb "slowly" "quickly"))) + (define (joins? left right) + (equal? (string-ref left (- (string-length left) 1)) (string-ref right 0))) + (if (joins? w-1 w-2) '() (amb)) + (if (joins? w-2 w-3) '() (amb)) + (if (joins? w-3 w-4) '() (amb)) + (list w-1 w-2 w-3 w-4)) diff --git a/Task/Amb/Seed7/amb.seed7 b/Task/Amb/Seed7/amb.seed7 new file mode 100644 index 0000000000..86855b3f5d --- /dev/null +++ b/Task/Amb/Seed7/amb.seed7 @@ -0,0 +1,51 @@ +$ include "seed7_05.s7i"; + +const type: setListType is array array string; + +const func array string: amb (in string: word1, in setListType: listOfSets) is func + result + var array string: ambResult is 0 times ""; + local + var string: word2 is ""; + begin + for word2 range listOfSets[1] do + if length(ambResult) = 0 and word1[length(word1) len 1] = word2[1 len 1] then + if length(listOfSets) = 1 then + ambResult := [] (word1) & [] (word2); + else + ambResult := amb(word2, listOfSets[2 ..]); + if length(ambResult) <> 0 then + ambResult := [] (word1) & ambResult; + end if; + end if; + end if; + end for; + end func; + +const func array string: amb (in setListType: listOfSets) is func + result + var array string: ambResult is 0 times ""; + local + var string: word1 is ""; + begin + for word1 range listOfSets[1] do + if length(ambResult) = 0 then + ambResult := amb(word1, listOfSets[2 ..]); + end if; + end for; + end func; + +const proc: main is func + local + var array string: ambResult is 0 times ""; + var string: word is ""; + begin + ambResult := amb([] ([] ("the", "that", "a"), + [] ("frog", "elephant", "thing"), + [] ("walked", "treaded", "grows"), + [] ("slowly", "quickly"))); + for word range ambResult do + write(word <& " "); + end for; + writeln; + end func; diff --git a/Task/Amb/TUSCRIPT/amb.tu b/Task/Amb/TUSCRIPT/amb.tu new file mode 100644 index 0000000000..a927256baf --- /dev/null +++ b/Task/Amb/TUSCRIPT/amb.tu @@ -0,0 +1,22 @@ +$$ MODE TUSCRIPT +set1="the'that'a" +set2="frog'elephant'thing" +set3="walked'treaded'grows" +set4="slowly'quickly" +LOOP w1=set1 + lastw1=EXTRACT (w1,-1,0) + LOOP w2=set2 + IF (w2.sw.$lastw1) THEN + lastw2=EXTRACT (w2,-1,0) + LOOP w3=set3 + IF (w3.sw.$lastw2) THEN + lastw3=EXTRACT (w3,-1,0) + LOOP w4=set4 + IF (w4.sw.$lastw3) sentence=JOIN (w1," ",w2,w3,w4) + ENDLOOP + ENDIF + ENDLOOP + ENDIF + ENDLOOP +ENDLOOP +PRINT sentence diff --git a/Task/Amb/TXR/amb-1.txr b/Task/Amb/TXR/amb-1.txr new file mode 100644 index 0000000000..67e21ef8d9 --- /dev/null +++ b/Task/Amb/TXR/amb-1.txr @@ -0,0 +1,24 @@ +@(define first_last (first last whole)) +@ (all) +@(skip :greedy)@{last 1} +@ (and) +@{first 1}@(skip) +@ (and) +@whole +@ (end) +@(end) +@(next "amb/set1") +@(skip) +@(first_last fi1 la1 w1) +@(next "amb/set2") +@(skip) +@(first_last la1 la2 w2) +@(next "amb/set3") +@(skip) +@(first_last la2 la3 w3) +@(next "amb/set4") +@(skip) +@(first_last la3 la4 w4) +@(output) +@w1 @w2 @w3 @w4 +@(end) diff --git a/Task/Amb/TXR/amb-2.txr b/Task/Amb/TXR/amb-2.txr new file mode 100644 index 0000000000..ce8aad703d --- /dev/null +++ b/Task/Amb/TXR/amb-2.txr @@ -0,0 +1,24 @@ +@(define first_last (first last whole)) +@ (all) +@(skip :greedy)@{last 1} +@ (and) +@{first 1}@(skip) +@ (and) +@whole +@ (end) +@(end) +@(next :list ("the" "that" "a")) +@(skip) +@(first_last fi1 la1 w1) +@(next :list ("frog" "elephant" "thing")) +@(skip) +@(first_last la1 la2 w2) +@(next :list ("walked" "treaded" "grows")) +@(skip) +@(first_last la2 la3 w3) +@(next :list ("slowly" "quickly")) +@(skip) +@(first_last la3 la4 w4) +@(output) +@w1 @w2 @w3 @w4 +@(end) diff --git a/Task/Amb/Tcl/amb-1.tcl b/Task/Amb/Tcl/amb-1.tcl new file mode 100644 index 0000000000..2ae771ca74 --- /dev/null +++ b/Task/Amb/Tcl/amb-1.tcl @@ -0,0 +1,24 @@ +set amb { + {the that a} + {frog elephant thing} + {walked treaded grows} + {slowly quickly} +} + +proc joins {a b} { + expr {[string index $a end] eq [string index $b 0]} +} + +foreach i [lindex $amb 0] { + foreach j [lindex $amb 1] { + if ![joins $i $j] continue + foreach k [lindex $amb 2] { + if ![joins $j $k] continue + foreach l [lindex $amb 3] { + if [joins $k $l] { + puts [list $i $j $k $l] + } + } + } + } +} diff --git a/Task/Amb/Tcl/amb-2.tcl b/Task/Amb/Tcl/amb-2.tcl new file mode 100644 index 0000000000..5866e28fcc --- /dev/null +++ b/Task/Amb/Tcl/amb-2.tcl @@ -0,0 +1,41 @@ +package require Tcl 8.6 +proc cp {args} { + coroutine cp.[incr ::cps] apply {{list args} { + yield [info coroutine] + foreach item $list { + if {[llength $args]} { + set c [cp {*}$args] + while 1 { yield [list $item {*}[$c]] } + } else { yield $item } + } + return -code break + }} {*}$args +} +proc amb {name filter args} { + coroutine $name apply {{filter args} { + set c [cp {*}$args] + yield [info coroutine] + while 1 { + set value [$c] + if {[{*}$filter $value]} { yield $value } + } + return -code break + }} $filter {*}$args +} + +proc joins {a b} { + expr {[string index $a end] eq [string index $b 0]} +} +proc joins* list { + foreach a [lrange $list 0 end-1] b [lrange $list 1 end] { + if {![joins $a $b]} {return 0} + } + return 1 +} + +amb words joins* \ + {the that a} \ + {frog elephant thing} \ + {walked treaded grows} \ + {slowly quickly} +while 1 { puts [words] } diff --git a/Task/Amb/VBScript/amb-1.vb b/Task/Amb/VBScript/amb-1.vb new file mode 100644 index 0000000000..a0329873e2 --- /dev/null +++ b/Task/Amb/VBScript/amb-1.vb @@ -0,0 +1,11 @@ +class ambiguous + dim sRule + + public property let rule( x ) + sRule = x + end property + + public default function amb(p1, p2) + amb = eval(sRule) + end function +end class diff --git a/Task/Amb/VBScript/amb-2.vb b/Task/Amb/VBScript/amb-2.vb new file mode 100644 index 0000000000..2fb0ec5398 --- /dev/null +++ b/Task/Amb/VBScript/amb-2.vb @@ -0,0 +1,17 @@ +dim amb +set amb = new ambiguous + +amb.rule = "right(p1,1)=left(p2,1)" + +dim w1, w2, w3, w4 +for each w1 in split("the that a", " ") + for each w2 in split("frog elephant thing", " ") + for each w3 in split("walked treaded grows", " ") + for each w4 in split("slowly quickly", " ") + if amb(w1, w2) and amb(w2, w3) and amb(w3, w4) then + wscript.echo w1, w2, w3, w4 + end if + next + next + next +next diff --git a/Task/Amicable-pairs/00DESCRIPTION b/Task/Amicable-pairs/00DESCRIPTION new file mode 100644 index 0000000000..c15152bac6 --- /dev/null +++ b/Task/Amicable-pairs/00DESCRIPTION @@ -0,0 +1,11 @@ +Two integers N and M are said to be [[wp:Amicable numbers|amicable pairs]] if N \neq M and the sum of the [[Proper divisors|proper divisors]] of N (\mathrm{sum}(\mathrm{propDivs}(N))) = M as well as \mathrm{sum}(\mathrm{propDivs}(M)) = N. + +For example 1184 and 1210 are an amicable pair (with proper divisors 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively). + +;Task: +Calculate and show here the Amicable pairs below 20,000; (there are eight). + +;Cf. +* [[Proper divisors]] +* [[Abundant, deficient and perfect number classifications]] +* [[Aliquot sequence classifications]] and its amicable ''classification''. diff --git a/Task/Amicable-pairs/AutoHotkey/amicable-pairs.ahk b/Task/Amicable-pairs/AutoHotkey/amicable-pairs.ahk new file mode 100644 index 0000000000..695ead2392 --- /dev/null +++ b/Task/Amicable-pairs/AutoHotkey/amicable-pairs.ahk @@ -0,0 +1,53 @@ +SetBatchLines -1 +Loop, 20000 +{ + m := A_index + + ; Getting factors + loop % floor(sqrt(m)) + { + if ( mod(m, A_index) = 0 ) + { + if ( A_index ** 2 == m ) + { + sum += A_index + continue + } else if ( A_index != 1 ) + { + sum += A_index + m//A_index + } else if ( A_index = 1 ) + { + sum += A_index + } + } + } ; Factors obtained + + ; Checking factors of sum + if ( sum > 1 ) + { + loop % floor(sqrt(sum)) + { + if ( mod(sum, A_index) = 0 ) + { + if ( A_index ** 2 == sum ) + { + sum2 += A_index + continue + } else if ( A_index != 1 ) + { + sum2 += A_index + sum//A_index + } else if ( A_index = 1 ) + { + sum2 += A_index + } + } + } + if ( m = sum2 ) && ( m != sum ) && ( m < sum ) + final .= m . ":" . sum . "`n" + } ; Checked + + sum := 0 + sum2 := 0 +} +MsgBox % final +ExitApp diff --git a/Task/Amicable-pairs/C/amicable-pairs.c b/Task/Amicable-pairs/C/amicable-pairs.c new file mode 100644 index 0000000000..ae528a648e --- /dev/null +++ b/Task/Amicable-pairs/C/amicable-pairs.c @@ -0,0 +1,41 @@ +#include +#include + +typedef unsigned int uint; + +int main(int argc, char **argv) +{ + uint top = atoi(argv[1]); + uint *divsum = malloc((top + 1) * sizeof(*divsum)); + uint pows[32] = {1, 0}; + + for (uint i = 0; i <= top; i++) divsum[i] = 1; + + // sieve + for (uint p = 2; p <= top; p++) { + if (divsum[p] > 1) continue; // p not prime + + uint x; // highest power of p we need + + // checking x <= top/y instead of x*y <= top to avoid overflow + for (x = 1; pows[x - 1] <= top/p; x++) + pows[x] = p*pows[x - 1]; + + for (uint n = p; n <= top; n += p) { + uint s; + for (uint i = s = 1; i < x && !(n%pows[i]); s += pows[i++]); + divsum[n] *= s; + } + } + + // subtract number itself from divisor sum ('proper') + for (uint i = 0; i <= top; i++) divsum[i] -= i; + + for (uint a = 1; a <= top; a++) { + uint b = divsum[a]; + if (b > a && b <= top && divsum[b] == a) + printf("%u %u\n", a, b); + } + + return 0; +} diff --git a/Task/Amicable-pairs/D/amicable-pairs.d b/Task/Amicable-pairs/D/amicable-pairs.d new file mode 100644 index 0000000000..ef66cb5ae0 --- /dev/null +++ b/Task/Amicable-pairs/D/amicable-pairs.d @@ -0,0 +1,14 @@ +void main() @safe /*@nogc*/ { + import std.stdio, std.algorithm, std.range, std.typecons, std.array; + + immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => + iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0); + + enum rangeMax = 20_000; + auto n2d = iota(1, rangeMax + 1).map!(n => properDivs(n).sum); + + foreach (immutable n, immutable divSum; n2d.enumerate(1)) + if (n < divSum && divSum <= rangeMax && n2d[divSum - 1] == n) + writefln("Amicable pair: %d and %d with proper divisors:\n %s\n %s", + n, divSum, properDivs(n), properDivs(divSum)); +} diff --git a/Task/Amicable-pairs/Haskell/amicable-pairs.hs b/Task/Amicable-pairs/Haskell/amicable-pairs.hs new file mode 100644 index 0000000000..01bbecbd19 --- /dev/null +++ b/Task/Amicable-pairs/Haskell/amicable-pairs.hs @@ -0,0 +1,10 @@ +divisors :: (Integral a) => a -> [a] +divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)] + +main :: IO () +main = do + let range = [1 .. 20000 :: Int] + divs = zip range $ map (sum . divisors) range + pairs = [(n, m) | (n, nd) <- divs, (m, md) <- divs, + n < m, nd == m, md == n] + print pairs diff --git a/Task/Amicable-pairs/J/amicable-pairs-1.j b/Task/Amicable-pairs/J/amicable-pairs-1.j new file mode 100644 index 0000000000..c131df8a6c --- /dev/null +++ b/Task/Amicable-pairs/J/amicable-pairs-1.j @@ -0,0 +1,2 @@ +factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ +properDivisors=: factors -. -.&1 diff --git a/Task/Amicable-pairs/J/amicable-pairs-2.j b/Task/Amicable-pairs/J/amicable-pairs-2.j new file mode 100644 index 0000000000..c21dc963a9 --- /dev/null +++ b/Task/Amicable-pairs/J/amicable-pairs-2.j @@ -0,0 +1,9 @@ + 1+0 20000 #:I.,() 1+i.20000 + 220 284 + 1184 1210 + 2620 2924 + 5020 5564 + 6232 6368 +10744 10856 +12285 14595 +17296 18416 diff --git a/Task/Amicable-pairs/Mathematica/amicable-pairs.math b/Task/Amicable-pairs/Mathematica/amicable-pairs.math new file mode 100644 index 0000000000..a6b280e60f --- /dev/null +++ b/Task/Amicable-pairs/Mathematica/amicable-pairs.math @@ -0,0 +1,5 @@ +amicableQ[n_] := + Module[{sum = Total[Most@Divisors@n]}, + sum != n && n == Total[Most@Divisors@sum]] + +Grid@Partition[Cases[Range[4, 20000], _?(amicableQ@# &)], 2] diff --git a/Task/Amicable-pairs/PARI-GP/amicable-pairs.pari b/Task/Amicable-pairs/PARI-GP/amicable-pairs.pari new file mode 100644 index 0000000000..723ed3b79e --- /dev/null +++ b/Task/Amicable-pairs/PARI-GP/amicable-pairs.pari @@ -0,0 +1 @@ +for(x=1,20000,my(y=sigma(x)-x); if(y>x && x == sigma(y)-y,print(x" "y))) diff --git a/Task/Amicable-pairs/PL-I/amicable-pairs.pli b/Task/Amicable-pairs/PL-I/amicable-pairs.pli new file mode 100644 index 0000000000..a50fcc3cd8 --- /dev/null +++ b/Task/Amicable-pairs/PL-I/amicable-pairs.pli @@ -0,0 +1,60 @@ +*process source xref; + ami: Proc Options(main); + p9a=time(); + Dcl (p9a,p9b,p9c) Pic'(9)9'; + Dcl sumpd(20000) Bin Fixed(31); + Dcl pd(300) Bin Fixed(31); + Dcl npd Bin Fixed(31); + Dcl (x,y) Bin Fixed(31); + + Do x=1 To 20000; + Call proper_divisors(x,pd,npd); + sumpd(x)=sum(pd,npd); + End; + p9b=time(); + Put Edit('sum(pd) computed in',(p9b-p9a)/1000,' seconds elapsed') + (Skip,col(7),a,f(6,3),a); + + Do x=1 To 20000; + Do y=x+1 To 20000; + If y=sumpd(x) & + x=sumpd(y) Then + Put Edit(x,y,' found after ',elapsed(),' seconds') + (Skip,2(f(6)),a,f(6,3),a); + End; + End; + Put Edit(elapsed(),' seconds total search time')(Skip,f(6,3),a); + + proper_divisors: Proc(n,pd,npd); + Dcl (n,pd(300),npd) Bin Fixed(31); + Dcl (d,delta) Bin Fixed(31); + npd=0; + If n>1 Then Do; + If mod(n,2)=1 Then /* odd number */ + delta=2; + Else /* even number */ + delta=1; + Do d=1 To n/2 By delta; + If mod(n,d)=0 Then Do; + npd+=1; + pd(npd)=d; + End; + End; + End; + End; + + sum: Proc(pd,npd) Returns(Bin Fixed(31)); + Dcl (pd(300),npd) Bin Fixed(31); + Dcl sum Bin Fixed(31) Init(0); + Dcl i Bin Fixed(31); + Do i=1 To npd; + sum+=pd(i); + End; + Return(sum); + End; + + elapsed: Proc Returns(Dec Fixed(6,3)); + p9c=time(); + Return((p9c-p9b)/1000); + End; + End; diff --git a/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal b/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal new file mode 100644 index 0000000000..a823986e1c --- /dev/null +++ b/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal @@ -0,0 +1,232 @@ +program AmicablePairs; +{$IFDEF FPC} + {$MODE DELPHI} + {$H+} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + sysutils; +const + MAX = 20000; +//MAX = 20*1000*1000; +type + tValue = LongWord; + tpValue = ^tValue; + tPower = array[0..31] of tValue; + tIndex = record + idxI, + idxS : Uint64; + end; + +var + Indices : array[0..511] of tIndex; + //primes up to 65536 enough until 2^32 + primes : array[0..6542] of tValue; + +procedure InitPrimes; +// sieve of erathosthenes without multiples of 2 +type + tSieve = array[0..(65536-1) div 2] of char; +var + ESieve : ^tSieve; + idx,i,j,p : LongINt; +Begin + new(ESieve); + fillchar(ESieve^[0],SizeOF(tSieve),#1); + primes[0] := 2; + idx := 1; + + //sieving + j := 1; + p := 2*j+1; + repeat + if Esieve^[j] = #1 then + begin + i := (2*j+2)*j;// i := (sqr(p) -1) div 2; + if i > High(tSieve) then + BREAK; + repeat + ESIeve^[i] := #0; + inc(i,p); + until i > High(tSieve); + end; + inc(j); + inc(p,2); + until j >High(tSieve); + + //collecting + For i := 1 to High(tSieve) do + IF Esieve^[i] = #1 then + Begin + primes[idx] := 2*i+1; + inc(idx); + IF idx>High(primes) then + BREAK; + end; + dispose(Esieve); +end; + +procedure Su_append(n,factor:tValue;var su:string); +var + q,p : tValue; +begin + p := 0; + repeat + q := n div factor; + IF q*factor<>n then + Break; + inc(p); + n := q; + until false; + IF p > 0 then + IF p= 1 then + su:= su+IntToStr(factor)+'*' + else + su:= su+IntToStr(factor)+'^'+IntToStr(p)+'*'; +end; + +procedure ProperDivs(n: Uint64); +//output of prime factorization +var + su : string; + primNo : tValue; + p:tValue; + +begin + str(n:8,su); + su:= su +' ['; + primNo := 0; + p := primes[0]; + repeat + Su_Append(n,p,su); + inc(primNo); + p := primes[primNo]; + until (p=0) OR (p*p >= n); + p := n; + Su_Append(n,p,su); + su[length(su)] := ']'; + writeln(su); +end; + +procedure AmPairOutput(cnt:tValue); +var + i : tValue; + r_max,r_min,r : double; +begin + r_max := 1.0; + r_min := 16.0; + For i := 0 to cnt-1 do + with Indices[i] do + begin + r := IdxS/IDxI; + writeln(i+1:4,IdxI:16,IDxS:16,' ratio ',r:10:7); + IF r < 1 then + begin + writeln(i); + readln; + halt; + end; + if r_max < r then + r_max := r + else + if r_min > r then + r_min := r; + IF cnt < 20 then + begin + ProperDivs(IdxI); + ProperDivs(IdxS); + end; + end; + writeln(' min ratio ',r_min:12:10); writeln(' max ratio ',r_max:12:10); +end; + +procedure SumOFProperDiv(n: tValue;var SumOfProperDivs:tValue); +// calculated by prime factorization +var + i,q, primNo, Prime,pot : tValue; + SumOfDivs: tValue; +begin + i := N; + SumOfDivs := 1; + primNo := 0; + Prime := Primes[0]; + q := i DIV Prime; + repeat + if q*Prime = i then + Begin + pot := 1; + repeat + i := q; + q := i div Prime; + Pot := Pot * Prime+1; + until q*Prime <> i; + SumOfDivs := SumOfDivs * pot; + end; + Inc(primNo); + Prime := Primes[primNo]; + q := i DIV Prime; + + {check if i already prime} + if Prime > q then + begin + prime := i; + q := 1; + end; + until i = 1; + SumOfProperDivs := SumOfDivs - N; +end; + +function Check:tValue; +const + //going backwards + DIV23 : array[0..5] of byte = + //== 5,4,3,2,1,0 + (1,0,0,0,1,0); + +var + i,s,k,n : tValue; + idx : nativeInt; +begin + n := 0; + idx := 3; + For i := 2 to MAX do + begin + //must be divisble by 2 or 3 ( n < High(tValue) < 1e14 ) + IF DIV23[idx] = 0 then + begin + SumOFProperDiv(i,s); + //only 24.7...% + IF s>i then + Begin + SumOFProperDiv(s,k); + IF k = i then + begin + With indices[n] do + begin + idxI := i; + idxS := s; + end; + inc(n); + end; + end; + end; + dec(idx); + IF idx < 0 then + idx := high(DIV23); + end; + result := n; +end; + +var + T2,T1: TDatetime; + APcnt: tValue; +begin + InitPrimes; + T1:= time; + APCnt:= Check; + T2:= time; + AmPairOutput(APCnt); + writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1)); + {$IFNDEF UNIX} readln;{$ENDIF} +end. diff --git a/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal b/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal new file mode 100644 index 0000000000..cf9651d404 --- /dev/null +++ b/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal @@ -0,0 +1,210 @@ +program AmicablePairs; +{find amicable pairs in a limited region 2..MAX +beware that >both< numbers must be smaller than MAX +there are 455 amicable pairs up to 524*1000*1000 +correct up to +#437 460122410 +} +//optimized for freepascal 2.6.4 32-Bit +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,peephole,cse,asmcse,regvar} + {$CODEALIGN loop=1,proc=8} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} + +uses + sysutils; +const +//MAX = 20000; +{$IFDEF UNIX} MAX = 524*1000*1000;{$ELSE}MAX = 499*1000*1000;{$ENDIF} +type + tValue = LongWord; + tpValue = ^tValue; + tPower = array[0..31] of tValue; + tIndex = record + idxI, + idxS : tValue; + end; + tdpa = array[0..2] of LongWord; +var + power : tPower; + PowerFac : tPower; + DivSumField : array[0..MAX] of tValue; + Indices : array[0..511] of tIndex; + DpaCnt : tdpa; + +procedure Init; +var + i : LongInt; +begin + DivSumField[0]:= 0; + For i := 1 to MAX do + DivSumField[i]:= 1; +end; + +procedure ProperDivs(n: tValue); +//Only for output, normally a factorication would do +var + su,so : string; + i,q : tValue; +begin + su:= '1'; + so:= ''; + i := 2; + while i*i <= n do + begin + q := n div i; + IF q*i -n = 0 then + begin + su:= su+','+IntToStr(i); + IF q <> i then + so:= ','+IntToStr(q)+so; + end; + inc(i); + end; + writeln(' [',su+so,']'); +end; + +procedure AmPairOutput(cnt:tValue); +var + i : tValue; + r : double; +begin + r := 1.0; + For i := 0 to cnt-1 do + with Indices[i] do + begin + writeln(i+1:4,IdxI:12,IDxS:12,' ratio ',IdxS/IDxI:10:7); + if r < IdxS/IDxI then + r := IdxS/IDxI; + IF cnt < 20 then + begin + ProperDivs(IdxI); + ProperDivs(IdxS); + end; + end; + writeln(' max ratio ',r:10:4); +end; + +function Check:tValue; +var + i,s,n : tValue; +begin + fillchar(DpaCnt,SizeOf(dpaCnt),#0); + n := 0; + For i := 1 to MAX do + begin + //s = sum of proper divs (I) == sum of divs (I) - I + s := DivSumField[i]-i; + IF (s <=MAX) AND (s>i) then + begin + IF DivSumField[s]-s = i then + begin + With indices[n] do + begin + idxI := i; + idxS := s; + end; + inc(n); + end; + end; + inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]); + end; + result := n; +end; + +Procedure CalcPotfactor(prim:tValue); +//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=1..k) prim^i +var + k: tValue; + Pot, //== prim^k + PFac : Int64; +begin + Pot := prim; + PFac := 1; + For k := 0 to High(PowerFac) do + begin + PFac := PFac+Pot; + IF (POT > MAX) then + BREAK; + PowerFac[k] := PFac; + Pot := Pot*prim; + end; +end; + +procedure InitPW(prim:tValue); +begin + fillchar(power,SizeOf(power),#0); + CalcPotfactor(prim); +end; + +function NextPotCnt(p: tValue):tValue;inline; +//return the first power <> 0 +//power == n to base prim +var + i : tValue; +begin + result := 0; + repeat + i := power[result]; + Inc(i); + IF i < p then + BREAK + else + begin + i := 0; + power[result] := 0; + inc(result); + end; + until false; + power[result] := i; +end; + +function Sieve(prim: tValue):tValue; +//simple version +var + actNumber : tValue; +begin + while prim <= MAX do + begin + InitPW(prim); + //actNumber = actual number = n*prim + //power == n to base prim + actNumber := prim; + while actNumber < MAX do + begin + DivSumField[actNumber] := DivSumField[actNumber] *PowerFac[NextPotCnt(prim)]; + inc(actNumber,prim); + end; + //next prime + repeat + inc(prim); + until (DivSumField[prim] = 1); + end; + result := prim; +end; + +var + T2,T1,T0: TDatetime; + APcnt: tValue; + +begin + T0:= time; + Init; + Sieve(2); + T1:= time; + APCnt := Check; + T2:= time; + AmPairOutput(APCnt); + writeln(DpaCnt[0]:10,' deficient'); + writeln(DpaCnt[1]:10,' perfect'); + writeln(DpaCnt[2]:10,' abundant'); + writeln(DpaCnt[2]/DpaCnt[0]:14:10,' ratio abundant/deficient '); + writeln('Time to calc sum of divs ',FormatDateTime('HH:NN:SS.ZZZ' ,T1-T0)); + writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1)); + {$IFNDEF UNIX} + readln; + {$ENDIF} +end. diff --git a/Task/Amicable-pairs/Perl-6/amicable-pairs.pl6 b/Task/Amicable-pairs/Perl-6/amicable-pairs.pl6 new file mode 100644 index 0000000000..c94e2e3045 --- /dev/null +++ b/Task/Amicable-pairs/Perl-6/amicable-pairs.pl6 @@ -0,0 +1,11 @@ +sub propdivsum (\x) { + [+] x > 1, gather for 2 .. x.sqrt.floor -> \d { + my \y = x div d; + if y * d == x { take d; take y unless y == d } + } +} + +for 1..20000 -> $i { + my $j = propdivsum($i); + say "$i $j" if $j > $i and $i == propdivsum($j); +} diff --git a/Task/Amicable-pairs/Perl/amicable-pairs.pl b/Task/Amicable-pairs/Perl/amicable-pairs.pl new file mode 100644 index 0000000000..42d0826260 --- /dev/null +++ b/Task/Amicable-pairs/Perl/amicable-pairs.pl @@ -0,0 +1,5 @@ +use ntheory qw/divisor_sum/; +for my $x (1..20000) { + my $y = divisor_sum($x)-$x; + say "$x $y" if $y > $x && $x == divisor_sum($y)-$y; +} diff --git a/Task/Amicable-pairs/Python/amicable-pairs.py b/Task/Amicable-pairs/Python/amicable-pairs.py new file mode 100644 index 0000000000..ebceb1739e --- /dev/null +++ b/Task/Amicable-pairs/Python/amicable-pairs.py @@ -0,0 +1,12 @@ +from proper_divisors import proper_divs + +def amicable(rangemax=20000): + n2divsum = {n: sum(proper_divs(n)) for n in range(1, rangemax + 1)} + for num, divsum in n2divsum.items(): + if num < divsum and divsum <= rangemax and n2divsum[divsum] == num: + yield num, divsum + +if __name__ == '__main__': + for num, divsum in amicable(): + print('Amicable pair: %i and %i With proper divisors:\n %r\n %r' + % (num, divsum, sorted(proper_divs(num)), sorted(proper_divs(divsum)))) diff --git a/Task/Amicable-pairs/README b/Task/Amicable-pairs/README new file mode 100644 index 0000000000..4028296b4b --- /dev/null +++ b/Task/Amicable-pairs/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Amicable_pairs diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-1.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-1.rexx new file mode 100644 index 0000000000..072eb00b03 --- /dev/null +++ b/Task/Amicable-pairs/REXX/amicable-pairs-1.rexx @@ -0,0 +1,39 @@ +Call time 'R' +Do x=1 To 20000 + pd=proper_divisors(x) + sumpd.x=sum(pd) + End +Say 'sum(pd) computed in' time('E') 'seconds' +Call time 'R' +Do x=1 To 20000 + /* If x//1000=0 Then Say x time() */ + Do y=x+1 To 20000 + If y=sumpd.x &, + x=sumpd.y Then + Say x y 'found after' time('E') 'seconds' + End + End +Say time('E') 'seconds total search time' +Exit + +proper_divisors: Procedure +Parse Arg n +Pd='' +If n=1 Then Return '' +If n//2=1 Then /* odd number */ + delta=2 +Else /* even number */ + delta=1 +Do d=1 To n%2 By delta + If n//d=0 Then + pd=pd d + End +Return space(pd) + +sum: Procedure +Parse Arg list +sum=0 +Do i=1 To words(list) + sum=sum+word(list,i) + End +Return sum diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx new file mode 100644 index 0000000000..a981b1f3b8 --- /dev/null +++ b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx @@ -0,0 +1,28 @@ +/*REXX program finds/displays all amicable pairs up to a given number.*/ +parse arg H .; if H=='' then H=20000 /*get optional arg (high limit).*/ +w=length(H) ; H.=H || . /*for columnar aligned output. */ +@.=0 + do k=1 for H; _=Pdivs(k); #=words(_) /*gen proper divs.*/ + do i=1 for #; @.k=@.k + word(_,i) /*gen Pdivs sums. */ + end /*i*/ /* [↑] sum the proper divisors.*/ + end /*k*/ /* [↑] process a range of ints.*/ +#=0 /*number of amicable pairs found.*/ + do m=220 for H-220+1 /*start search at lowest number. */ + do n=m+1 for H-m + if m==@.n then if n==@.m then do; #=#+1 /*bump the counter.*/ + say right(m,w) ' and ' right(n,w) " are amicable pairs." + end + end /*p*/ + end /*n*/ /*DO loop FORs: faster than TOs.*/ +say +say # 'amicable pairs found up to' H. /*display count of amicable pairs*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────PDIVS subroutine────────────────────*/ +Pdivs: procedure; parse arg x,b; odd=x//2 /* [↑] modified for amicable*/ +a=1 /* [↓] use only EVEN|ODD integers*/ + do j=2+odd by 1+odd while j*j n % i == 0) +val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap +val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1)) + +println( result mkString ", " ) diff --git a/Task/Amicable-pairs/Tcl/amicable-pairs.tcl b/Task/Amicable-pairs/Tcl/amicable-pairs.tcl new file mode 100644 index 0000000000..fb096e6eb4 --- /dev/null +++ b/Task/Amicable-pairs/Tcl/amicable-pairs.tcl @@ -0,0 +1,41 @@ +proc properDivisors {n} { + if {$n == 1} return + set divs 1 + set sum 1 + for {set i 2} {$i*$i <= $n} {incr i} { + if {!($n % $i)} { + lappend divs $i + incr sum $i + if {$i*$i < $n} { + lappend divs [set d [expr {$n / $i}]] + incr sum $d + } + } + } + return [list $sum $divs] +} + +proc amicablePairs {limit} { + set result {} + set sums [set divs {{}}] + for {set n 1} {$n < $limit} {incr n} { + lassign [properDivisors $n] sum d + lappend sums $sum + lappend divs [lsort -integer $d] + } + for {set n 1} {$n < $limit} {incr n} { + set nsum [lindex $sums $n] + for {set m 1} {$m < $n} {incr m} { + if {$n==[lindex $sums $m] && $m==$nsum} { + lappend result $m $n [lindex $divs $m] [lindex $divs $n] + } + } + } + return $result +} + +foreach {m n md nd} [amicablePairs 20000] { + puts "$m and $n are an amicable pair with these proper divisors" + puts "\t$m : $md" + puts "\t$n : $nd" +} diff --git a/Task/Amicable-pairs/VBScript/amicable-pairs.vb b/Task/Amicable-pairs/VBScript/amicable-pairs.vb new file mode 100644 index 0000000000..679a5f41ae --- /dev/null +++ b/Task/Amicable-pairs/VBScript/amicable-pairs.vb @@ -0,0 +1,36 @@ +start = Now +Set nlookup = CreateObject("Scripting.Dictionary") +Set uniquepair = CreateObject("Scripting.Dictionary") + +For i = 1 To 20000 + sum = 0 + For n = 1 To 20000 + If n < i Then + If i Mod n = 0 Then + sum = sum + n + End If + End If + Next + nlookup.Add i,sum +Next + +For j = 1 To 20000 + sum = 0 + For m = 1 To 20000 + If m < j Then + If j Mod m = 0 Then + sum = sum + m + End If + End If + Next + If nlookup.Exists(sum) And nlookup.Item(sum) = j And j <> sum _ + And uniquepair.Exists(sum) = False Then + uniquepair.Add j,sum + End If +Next + +For Each key In uniquepair.Keys + WScript.Echo key & ":" & uniquepair.Item(key) +Next + +WScript.Echo "Execution Time: " & DateDiff("s",Start,Now) & " seconds" diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/00DESCRIPTION b/Task/Append-a-record-to-the-end-of-a-text-file/00DESCRIPTION new file mode 100644 index 0000000000..34ab44e60d --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/00DESCRIPTION @@ -0,0 +1,58 @@ +Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. + +This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care ''must'' be taken to avoid concurrently overwriting the same record from another job. + +'''Task:''' +Given a two record sample for a mythical "passwd" file: +* Write these records out in the typical system format. +** Ideally these records will have named fields of various types. +* Close the file, then reopen the file for append. +** '''Append''' a new record to the file and close the file again. +** Take appropriate care to avoid concurrently overwrites from another job. +* Open the file and demonstrate the new record has indeed written to the end. + +{|class="wikitable" style="text-align: center; margin: 1em auto 1em auto;" +|+ Source record field types and contents. +|- +!account||password||UID||GID||fullname,office,extension,homephone,email||directory||shell +|- +!string||string||int||int||struct(string,string,string,string,string)||string||string +|- +|jsmith||x||1001||1000||Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org||/home/jsmith||/bin/bash +|- +|jdoe||x||1002||1000||Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org||/home/jdoe||/bin/bash +|} + +{|class="wikitable" style="text-align: center; margin: 1em auto 1em auto;" +|+ Record to be appended. +|- +!account||password||UID||GID||fullname,office,extension,homephone,email||directory||shell +|- +!string||string||int||int||struct(string,string,string,string,string)||string||string +|- +|xyz||x||1003||1000||X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org||/home/xyz||/bin/bash +|} + +'''Resulting file format:''' should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the [[wp:Gecos field|GECOS field]]. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. + +'''Expected output:''' +
+Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash
+
+ +'''Finally:''' Provide a summary of the language's "append record" capabilities in a table. eg. +{|class="wikitable" style="text-align: center; margin: 1em auto 1em auto;" +|+ Append Capabilities. +|- +!colspan=2| Data Representation +!rowspan=2| IO
Library +!rowspan=2| Append
Possible +!rowspan=2| Automatic
Append +!rowspan=2| Multi-tasking
Safe +|- +! In core || On disk +|- +| C struct || CSV text file || glibc/stdio || ☑ || ☑ || ☑ (Not all, eg NFS) +|} + +Alternatively: If the language's appends can not guarantee its writes will '''always''' append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends. diff --git a/Task/File-IO/00META.yaml b/Task/Append-a-record-to-the-end-of-a-text-file/00META.yaml similarity index 100% rename from Task/File-IO/00META.yaml rename to Task/Append-a-record-to-the-end-of-a-text-file/00META.yaml diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/C/append-a-record-to-the-end-of-a-text-file.c b/Task/Append-a-record-to-the-end-of-a-text-file/C/append-a-record-to-the-end-of-a-text-file.c new file mode 100644 index 0000000000..267b0d739b --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/C/append-a-record-to-the-end-of-a-text-file.c @@ -0,0 +1,53 @@ +#include +#include +/* note that UID & GID are of type "int" */ +typedef const char *STRING; +typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; +typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; + +#define GECOS_FMT "%s,%s,%s,%s,%s" +#define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" + +passwd_t passwd_list[]={ + {"jsmith", "x", 1001, 1000, /* UID and GID are type int */ + {"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, + "/home/jsmith", "/bin/bash"}, + {"jdoe", "x", 1002, 1000, + {"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, + "/home/jdoe", "/bin/bash"} +}; + +main(){ +/**************************** +* Create a passwd text file * +****************************/ + FILE *passwd_text=fopen("passwd.txt", "w"); + int rec_num; + for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) + fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); + fclose(passwd_text); + +/******************************** +* Load text ready for appending * +********************************/ + passwd_text=fopen("passwd.txt", "a+"); + char passwd_buf[BUFSIZ]; /* warning: fixed length */ + passwd_t new_rec = + {"xyz", "x", 1003, 1000, /* UID and GID are type int */ + {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, + "/home/xyz", "/bin/bash"}; + sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); +/* An atomic append without a file lock, + Note: wont work on some file systems, eg NFS */ + write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); + close(passwd_text); + +/*********************************************** +* Finally reopen and check record was appended * +***********************************************/ + passwd_text=fopen("passwd.txt", "r"); + while(!feof(passwd_text)) + fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); + if(strstr(passwd_buf, "xyz")) + printf("Appended record: %s\n", passwd_buf); +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Go/append-a-record-to-the-end-of-a-text-file.go b/Task/Append-a-record-to-the-end-of-a-text-file/Go/append-a-record-to-the-end-of-a-text-file.go new file mode 100644 index 0000000000..985ce3c3f0 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Go/append-a-record-to-the-end-of-a-text-file.go @@ -0,0 +1,101 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "os" +) + +type pw struct { + account, password string + uid, gid uint + gecos + directory, shell string +} + +type gecos struct { + fullname, office, extension, homephone, email string +} + +func (p *pw) encode(w io.Writer) (int, error) { + return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", + p.account, p.password, p.uid, p.gid, + p.fullname, p.office, p.extension, p.homephone, p.email, + p.directory, p.shell) +} + +// data cut and pasted from task description +var p2 = []pw{ + {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", + "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, + "/home/jsmith", "/bin/bash"}, + {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", + "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, + "/home/jsmith", "/bin/bash"}, +} + +var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", + "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, + "/home/xyz", "/bin/bash"} + +var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" + +const pfn = "mythical" + +func main() { + writeTwo() + appendOneMore() + checkResult() +} + +func writeTwo() { + // overwrites any existing file + f, err := os.Create(pfn) + if err != nil { + fmt.Println(err) + return + } + defer func() { + if cErr := f.Close(); cErr != nil && err == nil { + fmt.Println(cErr) + } + }() + for _, p := range p2 { + if _, err = p.encode(f); err != nil { + fmt.Println(err) + return + } + } +} + +func appendOneMore() { + // file must already exist + f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) + if err != nil { + fmt.Println(err) + return + } + if _, err := pa.encode(f); err != nil { + fmt.Println(err) + } + if cErr := f.Close(); cErr != nil && err == nil { + fmt.Println(cErr) + } +} + +func checkResult() { + // reads entire file then closes it + b, err := ioutil.ReadFile(pfn) + if err != nil { + fmt.Println(err) + return + } + if string(bytes.Split(b, []byte{'\n'})[2]) == expected { + fmt.Println("append okay") + } else { + fmt.Println("it didn't work") + } +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-1.groovy b/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-1.groovy new file mode 100644 index 0000000000..b58b5c9ce9 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-1.groovy @@ -0,0 +1,68 @@ +class PasswdRecord { + String account, password, directory, shell + int uid, gid + SourceRecord source + + private static final fs = ':' + private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell'] + private static final stringFields = ['account', 'password', 'directory', 'shell'] + private static final intFields = ['uid', 'gid'] + + PasswdRecord(String line = null) { + if (!line) return + def fields = line.split(fs) + if (fields.size() != fieldNames.size()) { + throw new IllegalArgumentException( + "Passwd record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") + } + (0.. + switch (fieldNames[i]) { + case stringFields: this[fieldNames[i]] = fields[i]; break + case intFields: this[fieldNames[i]] = fields[i] as Integer; break + default /* source */: this.source = new SourceRecord(fields[i]); break + } + } + } + + @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } +} + +class SourceRecord { + String fullname, office, extension, homephone, email + + private static final fs = ',' + private static final fieldNames = + ['fullname', 'office', 'extension', 'homephone', 'email'] + + SourceRecord(String line = null) { + if (!line) return + def fields = line.split(fs) + if (fields.size() != fieldNames.size()) { + throw new IllegalArgumentException( + "Source record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") + } + (0.. + this[fieldNames[i]] = fields[i] + } + } + + @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } +} + +def appendNewPasswdRecord = { + PasswdRecord pwr = new PasswdRecord().with { p -> + (account, password, uid, gid) = ['xyz', 'x', 1003, 1000] + source = new SourceRecord().with { s -> + (fullname, office, extension, homephone, email) = + ['X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'] + s + } + (directory, shell) = ['/home/xyz', '/bin/bash'] + p + }; + + new File('passwd.txt').withWriterAppend { w -> + w.append(pwr as String) + w.append('\r\n') + } +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-2.groovy b/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-2.groovy new file mode 100644 index 0000000000..e111381e2e --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Groovy/append-a-record-to-the-end-of-a-text-file-2.groovy @@ -0,0 +1,21 @@ +def checkPasswdFile = { it -> + File passwd = new File('passwd.txt') + assert passwd.exists() + + passwd.eachLine { line -> + def pw = new PasswdRecord(line) + assert pw && pw instanceof PasswdRecord + assert pw.source && pw.source instanceof SourceRecord + println pw + } + + println() +} + +println "File contents before new record added" +checkPasswdFile() + +appendNewPasswdRecord() + +println "File contents after new record added" +checkPasswdFile() diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-1.hs b/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-1.hs new file mode 100644 index 0000000000..0fecd80ad4 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-1.hs @@ -0,0 +1,29 @@ +{-# LANGUAGE RecordWildCards #-} + +import System.IO +import Data.List (intercalate) + +data Gecos = Gecos { fullname :: String + , office :: String + , extension :: String + , homephone :: String + , email :: String + } + +data Record = Record { account :: String + , password :: String + , uid :: Int + , gid :: Int + , directory :: String + , shell :: String + , gecos :: Gecos + } + +instance Show Gecos where + show (Gecos {..}) = intercalate "," [fullname, office, extension, homephone, email] + +instance Show Record where + show (Record {..}) = intercalate ":" [account, password, show uid, show gid, show gecos, directory, shell] + +addRecord :: String -> Record -> IO () +addRecord path r = appendFile path (show r) diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-2.hs b/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-2.hs new file mode 100644 index 0000000000..0aa9f55581 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Haskell/append-a-record-to-the-end-of-a-text-file-2.hs @@ -0,0 +1,14 @@ +t1 = Record "jsmith" "x" 1001 1000 "/home/jsmith" "/bin/bash" + (Gecos "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") + +t2 = Record "jdoe" "x" 1002 1000 "/home/jdoe" "/bin/bash" + (Gecos "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") + +t3 = Record "xyz" "x" 1003 1000 "/home/xyz" "/bin/bash" + (Gecos "X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") + +main = do + let path = "test.txt" + forM [t1,t2,t3] (addRecord path) + lastLine <- fmap (last . lines) (readFile path) + putStrLn lastLine diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Icon/append-a-record-to-the-end-of-a-text-file.icon b/Task/Append-a-record-to-the-end-of-a-text-file/Icon/append-a-record-to-the-end-of-a-text-file.icon new file mode 100644 index 0000000000..1939cdd27f --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Icon/append-a-record-to-the-end-of-a-text-file.icon @@ -0,0 +1,13 @@ +procedure main() + orig := [ + "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash", + "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" + ] + new := [ + "xyz:x:1003:1000:X:Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" + ] + fName := !open("mktemp","rp") + every (f := open(fName,"w")) | write(f,!orig) | close(f) + every (f := open(fName,"a")) | write(f,!new) | close(f) + every (f := open(fName,"r")) | write(!f) | close(f) +end diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/J/append-a-record-to-the-end-of-a-text-file.j b/Task/Append-a-record-to-the-end-of-a-text-file/J/append-a-record-to-the-end-of-a-text-file.j new file mode 100644 index 0000000000..3f59c57a6f --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/J/append-a-record-to-the-end-of-a-text-file.j @@ -0,0 +1,43 @@ +require'strings ~system/packages/misc/xenos.ijs' +record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0' + +passfields=: <;._1':username:password:gid:uid:gecos:home:shell' + +passrec=: LF,~ [: }.@;@ , ':';"0 (passfields i. {. ) { a:,~ {: + +R1=: passrec record'' + username: jsmith + password: x + gid: 1001 + uid: 1000 + gecos: Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org + home: /home/jsmith + shell: /bin/bash +) + +R2=: passrec record'' + username: jdoe + password: x + gid: 1002 + uid: 1000 + gecos: Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org + home: /home/jdoe + shell: /bin/bash +) + +R3=: passrec record'' + username: xyz + password: x + gid: 1003 + uid: 1000 + gecos: X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org + home: /home/xyz + shell: /bin/bash +) + +passwd=: <'/tmp/passwd.txt' NB. file needs to be writable on implementation machine + +(R1,R2) fwrite passwd +R3 fappend passwd + +assert 1 e. R3 E. fread passwd diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java b/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java new file mode 100644 index 0000000000..93a68243a4 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java @@ -0,0 +1,119 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class RecordAppender { + + public static class Record { + + String account, password; + Integer uid, gid; + String[] gecos; + String directory, shell; + + public Record(String account, String password, int uid, int gid, + String gecos[], String directory, String shell) { + this.account = account; + this.password = password; + this.uid = uid; + this.gid = gid; + this.gecos = gecos; + this.directory = directory; + this.shell = shell; + } + + public Record(String line) { + String[] token = line.trim().split(":"); + if ((token == null) || (token.length < 7)) { + throw new IllegalArgumentException(line); + } + this.account = token[0].trim(); + this.password = token[1].trim(); + this.uid = Integer.parseInt(token[2].trim()); + this.gid = Integer.parseInt(token[3].trim()); + this.gecos = token[4].trim().split(","); + this.directory = token[5].trim(); + this.shell = token[6].trim(); + } + + public String asLine() { + StringBuilder sb = new StringBuilder(); + sb.append(account + ":" + password + ":"); + sb.append(uid + ":" + gid + ":"); + for (int i = 0; i < gecos.length; i++) { + sb.append((i == 0 ? "" : ",") + gecos[i].trim()); + } + sb.append(":" + directory + ":" + shell + "\n"); + return sb.toString(); + } + } + + public static void main(String[] args) { + File file = null; + FileWriter writer = null; + BufferedReader br = null; + String line = null; + Record record = null; + try { + file = File.createTempFile("_rosetta", ".passwd"); + + writer = new FileWriter(file); + + writer.write(new Record("jsmith", "x", 1001, 1000, new String[] { + "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", + "jsmith@rosettacode.org" }, "/home/jsmith", "/bin/bash") + .asLine()); + + writer.write(new Record("jdoe", "x", 1002, 1000, new String[] { + "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", + "jdoe@rosettacode.org" }, "/home/jdoe", "/bin/bash") + .asLine()); + + writer.close(); + + // Setting the 'append'-Parameter to true writes data + // to the end of the file rather than the beginning + + writer = new FileWriter(file, true); + + writer.write(new Record("xyz", "x", 1003, 1000, new String[] { + "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", + "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") + .asLine()); + + writer.close(); + + br = new BufferedReader(new FileReader(file)); + while ((line = br.readLine()) != null) { + record = new Record(line); + if (record.account.equals("xyz")) { + System.out.println("Appended Record: " + record.asLine()); + } + } + + br.close(); + + } catch (IOException e) { + System.err.println("Running Example failed: " + e.getMessage()); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException ignored) { + } + try { + if (writer != null) { + writer.close(); + } + } catch (IOException ignored) { + } + if (file != null) { + file.delete(); + } + } + } + +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/MATLAB/append-a-record-to-the-end-of-a-text-file.m b/Task/Append-a-record-to-the-end-of-a-text-file/MATLAB/append-a-record-to-the-end-of-a-text-file.m new file mode 100644 index 0000000000..d3d81797cf --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/MATLAB/append-a-record-to-the-end-of-a-text-file.m @@ -0,0 +1,58 @@ + DS{1}.account='jsmith'; + DS{1}.password='x'; + DS{1}.UID=1001; + DS{1}.GID=1000; + DS{1}.fullname='Joe Smith'; + DS{1}.office='Room 1007'; + DS{1}.extension='(234)555-8917'; + DS{1}.homephone='(234)555-0077'; + DS{1}.email='jsmith@rosettacode.org'; + DS{1}.directory='/home/jsmith'; + DS{1}.shell='/bin/bash'; + + DS{2}.account='jdoe'; + DS{2}.password='x'; + DS{2}.UID=1002; + DS{2}.GID=1000; + DS{2}.fullname='Jane Doe'; + DS{2}.office='Room 1004'; + DS{2}.extension='(234)555-8914'; + DS{2}.homephone='(234)555-0044'; + DS{2}.email='jdoe@rosettacode.org'; + DS{2}.directory='/home/jdoe'; + DS{2}.shell='/bin/bash'; + + function WriteRecord(fid, rec) + fprintf(fid,"%s:%s:%i:%i:%s,%s,%s,%s,%s:%s%s\n", rec.account, rec.password, rec.UID, rec.GID, rec.fullname, rec.office, rec.extension, rec.homephone, rec.email, rec.directory, rec.shell); + return; + end + + %% write + fid = fopen('passwd.txt','w'); + WriteRecord(fid,DS{1}); + WriteRecord(fid,DS{2}); + fclose(fid); + + new.account='xyz'; + new.password='x'; + new.UID=1003; + new.GID=1000; + new.fullname='X Yz'; + new.office='Room 1003'; + new.extension='(234)555-8913'; + new.homephone='(234)555-0033'; + new.email='xyz@rosettacode.org'; + new.directory='/home/xyz'; + new.shell='/bin/bash'; + + %% append + fid = fopen('passwd.txt','a+'); + WriteRecord(fid,new); + fclose(fid); + + % read password file + fid = fopen('passwd.txt','r'); + while ~feof(fid) + printf('%s\n',fgetl(fid)); + end; + fclose(fid); diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Perl/append-a-record-to-the-end-of-a-text-file.pl b/Task/Append-a-record-to-the-end-of-a-text-file/Perl/append-a-record-to-the-end-of-a-text-file.pl new file mode 100644 index 0000000000..d802cd481f --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Perl/append-a-record-to-the-end-of-a-text-file.pl @@ -0,0 +1,106 @@ +use strict; +use warnings; + +use Fcntl qw( :flock SEEK_END ); + +use constant { + RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], + GECOS_FIELDS => [qw( fullname office extension homephone email )], + RECORD_SEP => ':', + GECOS_SEP => ',', + PASSWD_FILE => 'passwd.txt', +}; + +# here's our three records +my $records_to_write = [ + { + account => 'jsmith', + password => 'x', + UID => 1001, + GID => 1000, + GECOS => { + fullname => 'John Smith', + office => 'Room 1007', + extension => '(234)555-8917', + homephone => '(234)555-0077', + email => 'jsmith@rosettacode.org', + }, + directory => '/home/jsmith', + shell => '/bin/bash', + }, + { + account => 'jdoe', + password => 'x', + UID => 1002, + GID => 1000, + GECOS => { + fullname => 'Jane Doe', + office => 'Room 1004', + extension => '(234)555-8914', + homephone => '(234)555-0044', + email => 'jdoe@rosettacode.org', + }, + directory => '/home/jdoe', + shell => '/bin/bash', + }, +]; +my $record_to_append = { + account => 'xyz', + password => 'x', + UID => 1003, + GID => 1000, + GECOS => { + fullname => 'X Yz', + office => 'Room 1003', + extension => '(234)555-8913', + homephone => '(234)555-0033', + email => 'xyz@rosettacode.org', + }, + directory => '/home/xyz', + shell => '/bin/bash', +}; + +sub record_to_string { + my $rec = shift; + my $sep = shift // RECORD_SEP; + my $fields = shift // RECORD_FIELDS; + my @ary; + for my $field (@$fields) { + my $r = $rec->{$field}; + die "Field '$field' not found" unless defined $r; # simple sanity check + push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); + } + return join $sep, @ary; +} + +sub write_records_to_file { + my $records = shift; + my $filename = shift // PASSWD_FILE; + open my $fh, '>>', $filename or die "Can't open $filename: $!"; + flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; + # if someone appended while we were waiting... + seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; + print $fh record_to_string($_), "\n" for @$records; + flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; + # note: the file is closed automatically when function returns (and refcount of $fh becomes 0) +} + +# write two records to file +write_records_to_file( $records_to_write ); + +# append one more record to file +write_records_to_file( [$record_to_append] ); + +# test +{ + use Test::Simple tests => 1; + + open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; + my @lines = <$fh>; + chomp @lines; + ok( + $lines[-1] eq +'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', + "Appended record: $lines[-1]" + ); +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PicoLisp/append-a-record-to-the-end-of-a-text-file.l b/Task/Append-a-record-to-the-end-of-a-text-file/PicoLisp/append-a-record-to-the-end-of-a-text-file.l new file mode 100644 index 0000000000..53d33b5a20 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/PicoLisp/append-a-record-to-the-end-of-a-text-file.l @@ -0,0 +1,27 @@ +(setq L '((jsmith x 1001 1000 + "Joe Smith,Room 1007,(234)555-8917,\ + (234)555-0077,jsmith@rosettacode.org" + /home/jsmith /bin/bash ) + (jdoe x 1002 1000 + "Jane Doe,Room 1004,(234)555-8914,\ + (234)555-0044,jdoe@rosettacode.org" + /home/jsmith /bin/bash ) ) ) + +(setq A '(xyz x 1003 1000 + "X Yz,Room 1003,(234)555-8913,\ + (234)555-0033,xyz@rosettacode.org" + /home/xyz /bin/bash ) ) + +(out "mythical" + (for I L + (prinl (glue ': I)) ) ) +(out "+mythical" + (prinl (glue ': A)) ) +(in "mythical" + (do 2 (line)) + (println + (and + (= "xyz" (pack (till ':))) + (= 3 (lines "mythical") ) ) ) ) + +(bye) diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py b/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py new file mode 100644 index 0000000000..e21feece57 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py @@ -0,0 +1,48 @@ +############################# +# Create a passwd text file +############################# +# note that UID & gid are of type "text" +passwd_list=[ + dict(account='jsmith', password='x', UID=1001, GID=1000, # UID and GID are type int + GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', + homephone='(234)555-0077', email='jsmith@rosettacode.org'), + directory='/home/jsmith', shell='/bin/bash'), + dict(account='jdoe', password='x', UID=1002, GID=1000, + GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', + homephone='(234)555-0044', email='jdoe@rosettacode.org'), + directory='/home/jdoe', shell='/bin/bash') +] + +passwd_fields="account password UID GID GECOS directory shell".split() +GECOS_fields="fullname office extension homephone email".split() + +def passwd_text_repr(passwd_rec): +# convert individual fields to string type + passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) + for field in passwd_rec: # convert "int" fields + if not isinstance(passwd_rec[field], str): + passwd_rec[field]=`passwd_rec[field]` + return ":".join([ passwd_rec[field] for field in passwd_fields ]) + +passwd_text=open("passwd.txt","w") +for passwd_rec in passwd_list: + print >> passwd_text,passwd_text_repr(passwd_rec) +passwd_text.close() + +################################# +# Load text ready for appending +################################# +passwd_text=open("passwd.txt","a+") +new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, + GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', + homephone='(234)555-0033', email='xyz@rosettacode.org'), + directory='/home/xyz', shell='/bin/bash') +print >> passwd_text, passwd_text_repr(new_rec) +passwd_text.close() + +############################################## +# Finally reopen and check record was appended +############################################## +passwd_list=list(open("passwd.txt","r")) +if "xyz" in passwd_list[-1]: + print "Appended record:",passwd_list[-1][:-1] diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/README b/Task/Append-a-record-to-the-end-of-a-text-file/README new file mode 100644 index 0000000000..03ec58d52e --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx b/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx new file mode 100644 index 0000000000..7dfbc98a4e --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx @@ -0,0 +1,48 @@ +/*REXX pgm: writes two records, close file, appends another record. */ +signal on syntax; signal on novalue /*handle REXX program errors. */ +tFID='PASSWD.TXT' /*define the name of the out file*/ +call lineout tFID /*close the file, just in case; */ + /*could be open from calling pgm.*/ +call writeRec tFID,, /*append 1st record to the file. */ + 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' + +call writeRec tFID,, /*append 2nd record to the file. */ + 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' + +call lineout fid /*close the file. */ + +call writeRec tFID,, /*append 3rd record to the file. */ + 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' +/*─account─pw────uid───gid──────────────fullname,office,extension,homephone,Email────────────────────────directory───────shell──*/ + +call lineout fid /*safe programming: close file. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────WRITEREC subroutine─────────────────*/ +writeRec: parse arg fid,_ /*get the fileID, and the 1st arg*/ +sep=':' /*field delimiter used in file. */ + /*Note: SEP field should be ··· */ + /*··· unique and can be any size.*/ + do i=3 to arg() /*get each argument and append it*/ + _=_ ||sep|| arg(i) /*to the prev. arg, with a : sep.*/ + end /*i*/ + + do tries=0 for 11 /*keep trying for 66 seconds. */ + r=lineout(fid,_) /*write (append) the new record. */ + if r==0 then return /*Zero? Then record was written.*/ + call sleep tries /*Error: so try again after delay*/ + end /*tries*/ /*Note: not all REXXes have SLEEP*/ + + /*possibly: no write access, */ + /* proper authority, */ + /* permission, etc. */ +call err r 'record's(r) "not written to file" fid +exit 13 +/*───────────────────────────────error handling subroutines and others.─*/ +err: say; say; say center(' error! ',40,"*"); 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) + +s: if arg(1)==1 then return arg(3);return word(arg(2) 's',1) diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-1.rapidq b/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-1.rapidq new file mode 100644 index 0000000000..7306007084 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-1.rapidq @@ -0,0 +1,28 @@ +'Short solution: Append record and read last record +$Include "Rapidq.inc" + +dim file as qfilestream +dim filename as string +dim LogRec as string + +'First create our logfile +filename = "C:\Logfile2.txt" +file.open(filename, fmCreate) +file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" +file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" +file.close + +'Append record +file.open(filename, fmOpenWrite) +file.position = File.size +file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" +file.close + +'Read last record +file.open (filename, fmOpenRead) +while not file.EOF + LogRec = File.Readline +wend +file.close + +showmessage "Appended record: " + LogRec diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-2.rapidq b/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-2.rapidq new file mode 100644 index 0000000000..ac9902151b --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/RapidQ/append-a-record-to-the-end-of-a-text-file-2.rapidq @@ -0,0 +1,145 @@ +'Full solution: Create an object with all required fields and +'build-in functions to append a record and to read the last record +$include "Rapidq.inc" + +Type TLogFile extends QObject + Private: + file as qfilestream + + Public: + account as string + password as string + UID as integer + GID as integer + GECOS.fullname as string + GECOS.office as string + GECOS.extension as string + GECOS.homephone as string + GECOS.email as string + directory as string + shell as string + + RSep as string + GSep as string + + function AppendRecord(LogFile as string) as integer + with This + if fileexists(LogFile) then + Result = .file.open(LogFile, fmOpenWrite) + else + Result = .file.open(LogFile, fmCreate) + end if + + .file.position = .file.size + .file.writeline .account + .RSep + .password + .RSep + str$(.UID) + .RSep + str$(.GID) + .RSep +_ + .GECOS.fullname + .GSep + .GECOS.office + .GSep + .GECOS.extension +_ + .GSep + .GECOS.homephone + .GSep + .GECOS.email + .RSep +_ + .directory + .RSep + .shell + .file.close + end with + end function + + Function ReadLastRecord(LogFile as string) as string + dim x as integer + dim LogRec as string + dim GECOSRec as string + + With This + if fileexists(LogFile) then + .file.open(LogFile, fmOpenRead) + While not .file.eof + LogRec = .file.readline + Wend + .file.close + + .account = field$(LogRec, .RSep, 1) + .password = field$(LogRec, .RSep, 2) + .UID = val(field$(LogRec, .RSep, 3)) + .GID = val(field$(LogRec, .RSep, 4)) + GECOSRec = field$(LogRec, .RSep, 5) + .directory = field$(LogRec, .RSep, 6) + .shell = field$(LogRec, .RSep, 7) + .GECOS.fullname = field$(GECOSRec, .GSep, 1) + .GECOS.office = field$(GECOSRec, .GSep, 2) + .GECOS.extension = field$(GECOSRec, .GSep, 3) + .GECOS.homephone = field$(GECOSRec, .GSep, 4) + .GECOS.email = field$(GECOSRec, .GSep, 5) + + else + showmessage "Can't read file " + Logfile + + end if + end with + End function + + Constructor + RSep = ":" + GSep = "," + End Constructor +end type + +'--- Now we can use our LogFile object: +dim LogFile as TLogFile + +'--- Let's save a record: Set field values +Logfile.account = "jsmith" +Logfile.password = "X" +Logfile.UID = 1001 +Logfile.GID = 1000 +Logfile.directory = "/home/jsmith" +Logfile.shell = "/bin/bash" +Logfile.GECOS.fullname = "Joe Smith" +Logfile.GECOS.office = "Room 1007" +Logfile.GECOS.extension = "(234)555-8917" +Logfile.GECOS.homephone = "(234)555-0077" +Logfile.GECOS.email = "jsmith@rosettacode.org" +'--- And save it to our logfile +Logfile.appendrecord("c:\A test.txt") + +'--- Let's save the second one: Set field values +Logfile.account = "jdoe" +Logfile.password = "X" +Logfile.UID = 1002 +Logfile.GID = 1000 +Logfile.directory = "/home/jsmith" +Logfile.shell = "/bin/bash" +Logfile.GECOS.fullname = "Jane Doe" +Logfile.GECOS.office = "Room 1004" +Logfile.GECOS.extension = "(234)555-8914" +Logfile.GECOS.homephone = "(234)555-0044" +Logfile.GECOS.email = "jdoe@rosettacode.org" +'--- And save it to our logfile +Logfile.appendrecord("c:\A test.txt") + +'--- And append the last one: Set field values +Logfile.account = "xyz" +Logfile.password = "X" +Logfile.UID = 1003 +Logfile.GID = 1000 +Logfile.directory = "/home/xyz" +Logfile.shell = "/bin/bash" +Logfile.GECOS.fullname = "X Yz" +Logfile.GECOS.office = "Room 1003" +Logfile.GECOS.extension = "(234)555-8913" +Logfile.GECOS.homephone = "(234)555-0033" +Logfile.GECOS.email = "xyz@rosettacode.org" +'--- And save it to our logfile +Logfile.appendrecord("c:\A test.txt") + + +'--- Read last record: load all CSV fields in our LogFile object props +Logfile.ReadLastRecord("c:\A test.txt") +'--- And simply Read values from the objects properties +Print Logfile.account +Print Logfile.password +Print Logfile.UID +Print Logfile.GID +Print Logfile.directory +Print Logfile.shell +Print Logfile.GECOS.fullname +Print Logfile.GECOS.office +Print Logfile.GECOS.extension +Print Logfile.GECOS.homephone +Print Logfile.GECOS.email +Print "" +input "Press enter to exit:";a$ diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Ruby/append-a-record-to-the-end-of-a-text-file.rb b/Task/Append-a-record-to-the-end-of-a-text-file/Ruby/append-a-record-to-the-end-of-a-text-file.rb new file mode 100644 index 0000000000..103ae63e8a --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Ruby/append-a-record-to-the-end-of-a-text-file.rb @@ -0,0 +1,36 @@ +Gecos = Struct.new :fullname, :office, :extension, :homephone, :email +class Gecos + def to_s + "%s,%s,%s,%s,%s" % [fullname, office, extension, homephone, email] + end +end + +# Another way define 'to_s' method +Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do + def to_s + to_a.map(&:to_s).join(':') + end +end + +jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') +jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') +xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') + +filename = 'append.records.test' + +# create the passwd file with two records +File.open(filename, 'w') do |io| + io.puts jsmith + io.puts jdoe +end + +puts "before appending:" +puts File.readlines(filename) + +# append the third record +File.open(filename, 'a') do |io| + io.puts xyz +end + +puts "after appending:" +puts File.readlines(filename) diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Scala/append-a-record-to-the-end-of-a-text-file.scala b/Task/Append-a-record-to-the-end-of-a-text-file/Scala/append-a-record-to-the-end-of-a-text-file.scala new file mode 100644 index 0000000000..4c5574897a --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Scala/append-a-record-to-the-end-of-a-text-file.scala @@ -0,0 +1,56 @@ +import java.io.{File, FileWriter, IOException} +import scala.io.Source + +object RecordAppender extends App { + val rawDataIt = Source.fromString(rawData).getLines() + + def writeStringToFile(file: File, data: String, appending: Boolean = false) = + using(new FileWriter(file, appending))(_.write(data)) + + def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B = + try f(resource) finally resource.close() + + def rawData = + """jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash + |jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash + |xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash""".stripMargin + + case class Record(account: String, + password: String, + uid: Int, + gid: Int, + gecos: Array[String], + directory: String, + shell: String) { + def asLine: String = s"$account:$password:$uid:$gid:${gecos.mkString(",")}:$directory:$shell\n" + } + + object Record { + def apply(line: String): Record = { + val token = line.trim.split(":") + require((token != null) || (token.length == 7)) + this(token(0).trim, + token(1).trim, + Integer.parseInt(token(2).trim), + Integer.parseInt(token(3).trim), + token(4).split(","), + token(5).trim, + token(6).trim) + } + } + + try { + val file = File.createTempFile("_rosetta", ".passwd") + using(new FileWriter(file))(writer => rawDataIt.take(2).foreach(line => writer.write(Record(line).asLine))) + + writeStringToFile(file, Record(rawDataIt.next()).asLine, appending = true) // Append a record + + Source.fromFile(file).getLines().foreach(line => { + if (line startsWith """xyz""") print(s"Selected record: ${Record(line).asLine}") + }) + scala.compat.Platform.collectGarbage() // JVM Windows related bug workaround JDK-4715154 + file.deleteOnExit() + } catch { + case e: IOException => println(s"Running Example failed: ${e.getMessage}") + } +} // 57 lines diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Tcl/append-a-record-to-the-end-of-a-text-file.tcl b/Task/Append-a-record-to-the-end-of-a-text-file/Tcl/append-a-record-to-the-end-of-a-text-file.tcl new file mode 100644 index 0000000000..3901124610 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Tcl/append-a-record-to-the-end-of-a-text-file.tcl @@ -0,0 +1,85 @@ +# Model the data as nested lists, as that is a natural fit for Tcl +set basicRecords { + { + jsmith + x + 1001 + 1000 + { + {Joe Smith} + {Room 1007} + (234)555-8917 + (234)555-0077 + jsmith@rosettacode.org + } + /home/jsmith + /bin/bash + } + { + jdoe + x + 1002 + 1000 + { + {Jane Doe} + {Room 1004} + (234)555-8914 + (234)555-0044 + jdoe@rosettacode.org + } + /home/jsmith + /bin/bash + } +} +set addedRecords { + { + xyz + x + 1003 + 1000 + { + {X Yz} + {Room 1003} + (234)555-8913 + (234)555-0033 + xyz@rosettacode.org + } + /home/xyz + /bin/bash + } +} + +proc printRecords {records fd} { + fconfigure $fd -buffering none + foreach record $records { + lset record 4 [join [lindex $record 4] ","] + puts -nonewline $fd [join $record ":"]\n + } +} +proc readRecords fd { + set result {} + foreach line [split [read $fd] "\n"] { + if {$line eq ""} continue + set record [split $line ":"] + # Special handling for GECOS + lset record 4 [split [lindex $record 4] ","] + lappend result $record + } + return $result +} + +# Write basic set +set f [open ./passwd w] +printRecords $basicRecords $f +close $f + +# Append the extra ones +# Use {WRONLY APPEND} on Tcl 8.4 +set f [open ./passwd a] +printRecords $addedRecords $f +close $f + +set f [open ./passwd] +set recs [readRecords $f] +close $f +puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]" diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/UNIX-Shell/append-a-record-to-the-end-of-a-text-file.sh b/Task/Append-a-record-to-the-end-of-a-text-file/UNIX-Shell/append-a-record-to-the-end-of-a-text-file.sh new file mode 100644 index 0000000000..178fe86dd9 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/UNIX-Shell/append-a-record-to-the-end-of-a-text-file.sh @@ -0,0 +1,49 @@ +rec1=( + jsmith + x + 1001 + 1000 + "Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org" + /home/jsmith + /bin/bash +) + +rec2=( + jdoe + x + 1002 + 1000 + "Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org" + /home/jdoe + /bin/bash +) + +rec3=( + xyz + x + 1003 + 1000 + "X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org" + /home/xyz + /bin/bash +) + +filename=./passwd-ish + +# use parentheses to run the commands in a subshell, so the +# current shell's IFS variable is not changed +( + IFS=: + echo "${rec1[*]}" + echo "${rec2[*]}" +) > "$filename" + +echo before appending: +cat "$filename" + +# appending, use the ">>" redirection symbol +IFS=: +echo "${rec3[*]}" >> "$filename" + +echo after appending: +cat "$filename" diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/00DESCRIPTION b/Task/Arithmetic-geometric-mean-Calculate-Pi/00DESCRIPTION new file mode 100644 index 0000000000..a18a4854c7 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/00DESCRIPTION @@ -0,0 +1,17 @@ +[http://www.maa.org/sites/default/files/pdf/upload_library/22/Ford/Almkvist-Berndt585-608.pdf Almkvist Berndt 1988] begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi. + +With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing: + +\pi = +\frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2} +{1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)} + + +This allows you to make the approximation, for any large N: + +\pi \approx +\frac{4\; a_N^2} +{1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)} + + +The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi. diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/C++/arithmetic-geometric-mean-calculate-pi.cpp b/Task/Arithmetic-geometric-mean-Calculate-Pi/C++/arithmetic-geometric-mean-calculate-pi.cpp new file mode 100644 index 0000000000..f207cdb7a4 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/C++/arithmetic-geometric-mean-calculate-pi.cpp @@ -0,0 +1,35 @@ +#include + +void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, + const mpf_class& op2) +{ + rop1 = (op1 + op2) / 2; + rop2 = op1 * op2; + mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); +} + +int main(void) +{ + mpf_set_default_prec(300000); + mpf_class x0, y0, resA, resB, Z; + + x0 = 1; + y0 = 0.5; + Z = 0.25; + mpf_sqrt(y0.get_mpf_t(), y0.get_mpf_t()); + + int n = 1; + for (int i = 0; i < 8; i++) { + agm(resA, resB, x0, y0); + Z -= n * (resA - x0) * (resA - x0); + n *= 2; + + agm(x0, y0, resA, resB); + Z -= n * (x0 - resA) * (x0 - resA); + n *= 2; + } + + x0 = x0 * x0 / Z; + gmp_printf ("%.100000Ff\n", x0.get_mpf_t()); + return 0; +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/C/arithmetic-geometric-mean-calculate-pi.c b/Task/Arithmetic-geometric-mean-Calculate-Pi/C/arithmetic-geometric-mean-calculate-pi.c new file mode 100644 index 0000000000..e3a2b572fa --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/C/arithmetic-geometric-mean-calculate-pi.c @@ -0,0 +1,42 @@ +#include "gmp.h" + +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) { + mpf_set_default_prec (300000); + mpf_t x0, y0, resA, resB, Z, var; + + mpf_init_set_ui (x0, 1); + mpf_init_set_d (y0, 0.5); + mpf_sqrt (y0, y0); + mpf_init (resA); + mpf_init (resB); + mpf_init_set_d (Z, 0.25); + mpf_init (var); + + int n = 1; + int i; + for(i=0; i<8; i++){ + agm(x0, y0, resA, resB); + mpf_sub(var, resA, x0); + mpf_mul(var, var, var); + mpf_mul_ui(var, var, n); + mpf_sub(Z, Z, var); + n += n; + agm(resA, resB, x0, y0); + mpf_sub(var, x0, resA); + mpf_mul(var, var, var); + mpf_mul_ui(var, var, n); + mpf_sub(Z, Z, var); + n += n; + } + mpf_mul(x0, x0, x0); + mpf_div(x0, x0, Z); + gmp_printf ("%.100000Ff\n", x0); + return 0; +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Haskell/arithmetic-geometric-mean-calculate-pi.hs b/Task/Arithmetic-geometric-mean-Calculate-Pi/Haskell/arithmetic-geometric-mean-calculate-pi.hs new file mode 100644 index 0000000000..18691c9667 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Haskell/arithmetic-geometric-mean-calculate-pi.hs @@ -0,0 +1,33 @@ +import Prelude hiding (pi) +import Data.Number.MPFR hiding (sqrt, pi, div) +import Data.Number.MPFR.Instances.Near () + +-- A generous overshoot of the number of bits needed for a +-- given number of digits. +digitBits :: (Integral a, Num a) => a -> a +digitBits n = (n + 1) `div` 2 * 8 + +-- Calculate pi accurate to a given number of digits. +pi :: Integer -> MPFR +pi digits = + let eps = fromString ("1e-" ++ show digits) + (fromInteger $ digitBits digits) 0 + two = fromInt Near (getPrec eps) 2 + twoi = 2 :: Int + twoI = 2 :: Integer + pis a g s n = + let aB = (a + g) / two + gB = sqrt (a * g) + aB2 = aB ^^ twoi + sB = s + (two ^^ n) * (aB2 - gB ^^ twoi) + num = 4 * aB2 + den = 1 - sB + in (num / den) : pis aB gB sB (n + 1) + puntil f (a:b:xs) = if f a b then b else puntil f (b:xs) + in puntil (\a b -> abs (a - b) < eps) + $ pis one (one / sqrt two) zero twoI + +main :: IO () +main = do + -- The last decimal is rounded. + putStrLn $ toString 1000 $ pi 1000 diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/J/arithmetic-geometric-mean-calculate-pi.j b/Task/Arithmetic-geometric-mean-Calculate-Pi/J/arithmetic-geometric-mean-calculate-pi.j new file mode 100644 index 0000000000..0c047b0896 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/J/arithmetic-geometric-mean-calculate-pi.j @@ -0,0 +1,25 @@ +DP=: 100 + +round=: DP&$: : (4 : 0) + b %~ <.1r2+y*b=. 10x^x +) + +sqrt=: DP&$: : (4 : 0) " 0 + assert. 0<:y + %/ <.@%: (2 x: (2*x) round y)*10x^2*x+0>.>.10^.y +) + +pi =: 3 : 0 + A =. N =. 1x + 'G Z HALF' =. (% sqrt 2) , 1r4 1r2 + for_I. i.18 do. + X =. ((A + G) * HALF) , sqrt A * G + VAR =. ({.X) - A + Z =. Z - VAR * VAR * N + N =. +: N + 'A G' =. X + PI =: A * A % Z + smoutput (0j100":PI) , 4 ": I + end. + PI +) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Mathematica/arithmetic-geometric-mean-calculate-pi.math b/Task/Arithmetic-geometric-mean-Calculate-Pi/Mathematica/arithmetic-geometric-mean-calculate-pi.math new file mode 100644 index 0000000000..4fca4bf983 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Mathematica/arithmetic-geometric-mean-calculate-pi.math @@ -0,0 +1,8 @@ +piCalc[n_,precision_]:=($precision=precision;4*a[n]^2)/(1-Sum[2^(1+k)*(a[k]^2-b[k]^2),{k,1,n}]) +a[h_]:=(a[h]=(N[#,$precision]&@a[h-1]+b[h-1])/2) +b[h_]:=(b[h]=N[#,$precision]&@Sqrt[a[h-1] b[h-1]]) +a[0]=1; +b[0]=1/Sqrt[2]; + +N[Pi, 1000000] - piCalc[10, 5] +0.*10^-996 diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/PARI-GP/arithmetic-geometric-mean-calculate-pi.pari b/Task/Arithmetic-geometric-mean-Calculate-Pi/PARI-GP/arithmetic-geometric-mean-calculate-pi.pari new file mode 100644 index 0000000000..0522f02847 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/PARI-GP/arithmetic-geometric-mean-calculate-pi.pari @@ -0,0 +1,2 @@ +pi(n)=my(a=1,g=2^-.5);(1-2*sum(k=1,n,[a,g]=[(a+g)/2,sqrt(a*g)];(a^2-g^2)< FatRat) { + return FatRat.new: + sqrt($r.nude[0] * 10**(number-of-decimals*2) div $r.nude[1]), + 10**number-of-decimals; +} + +my FatRat ($a, $n) = 1.FatRat xx 2; +my FatRat $g = sqrt(1/2.FatRat); +my $z = .25; + +for ^10 { + given [ ($a + $g)/2, sqrt($a * $g) ] { + $z -= (.[0] - $a)**2 * $n; + $n += $n; + ($a, $g) = @$_; + say ($a ** 2 / $z).substr: 0, 2 + number-of-decimals; + } +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-1.pl b/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-1.pl new file mode 100644 index 0000000000..23ab3dd171 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-1.pl @@ -0,0 +1,23 @@ +use Math::BigFloat try => "GMP,Pari"; + +my $digits = shift || 100; # Get number of digits from command line +print agm_pi($digits), "\n"; + +sub agm_pi { + my $digits = shift; + my $acc = $digits + 8; + my $HALF = Math::BigFloat->new("0.5"); + my ($an, $bn, $tn, $pn) = (Math::BigFloat->bone, $HALF->copy->bsqrt($acc), + $HALF->copy->bmul($HALF), Math::BigFloat->bone); + while ($pn < $acc) { + my $prev_an = $an->copy; + $an->badd($bn)->bmul($HALF, $acc); + $bn->bmul($prev_an)->bsqrt($acc); + $prev_an->bsub($an); + $tn->bsub($pn * $prev_an * $prev_an); + $pn->badd($pn); + } + $an->badd($bn); + $an->bmul($an,$acc)->bdiv(4*$tn, $digits); + return $an; +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-2.pl b/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-2.pl new file mode 100644 index 0000000000..642474f195 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Perl/arithmetic-geometric-mean-calculate-pi-2.pl @@ -0,0 +1,17 @@ +use strict; +use warnings; +use Math::BigFloat; + +Math::BigFloat->div_scale(100); + +my $a = my $n = 1; +my $g = 1 / sqrt(Math::BigFloat->new(2)); +my $z = 0.25; +for( 0 .. 17 ) { + my $x = [ ($a + $g) * 0.5, sqrt($a * $g) ]; + my $var = $x->[0] - $a; + $z -= $var * $var * $n; + $n += $n; + ($a, $g) = @$x; +} +print $a * $a / $z, "\n"; diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/PicoLisp/arithmetic-geometric-mean-calculate-pi.l b/Task/Arithmetic-geometric-mean-Calculate-Pi/PicoLisp/arithmetic-geometric-mean-calculate-pi.l new file mode 100644 index 0000000000..aff2660d6f --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/PicoLisp/arithmetic-geometric-mean-calculate-pi.l @@ -0,0 +1,21 @@ +(scl 40) + +(de pi () + (let + (A 1.0 N 1.0 Z 0.25 + G (/ (* 1.0 1.0) (sqrt 2.0 1.0)) ) + (use (X1 X2 V) + (do 18 + (setq + X1 (/ (* (+ A G) 0.5) 1.0) + X2 (sqrt (* A G)) + V (- X1 A) + Z (- Z (/ (* (/ (* V V) 1.0) N) 1.0)) + N (+ N N) + A X1 + G X2 ) ) ) + (round (/ (* A A) Z) 40)) ) + +(println (pi)) + +(bye) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Python/arithmetic-geometric-mean-calculate-pi.py b/Task/Arithmetic-geometric-mean-Calculate-Pi/Python/arithmetic-geometric-mean-calculate-pi.py new file mode 100644 index 0000000000..dda1802965 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Python/arithmetic-geometric-mean-calculate-pi.py @@ -0,0 +1,13 @@ +from decimal import * + +D = Decimal +getcontext().prec = 100 +a = n = D(1) +g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5) +for i in range(18): + x = [(a + g) * half, (a * g).sqrt()] + var = x[0] - a + z -= var * var * n + n += n + a, g = x +print(a * a / z) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/README b/Task/Arithmetic-geometric-mean-Calculate-Pi/README new file mode 100644 index 0000000000..f2ad7fc83a --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx new file mode 100644 index 0000000000..055f17fbd4 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx @@ -0,0 +1,21 @@ +/*REXX program calculates the value of pi using the AGM algorithm. */ +parse arg d .; if d=='' then d=500 /*D specified? Then use default.*/ +numeric digits d+5 /*set the numeric digits to D+5. */ +a=1; n=1; z=1/4; g=sqrt(1/2) /*calculate some initial values. */ + + do j=1 until a==old; old=a /*keep calculating until no noise*/ + x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms*/ + z=z-n*(x-a)**2; n=n+n; a=x /*Z is used in final calculation.*/ + end /*j*/ /* [↑] stop if A equals OLD */ + +pi=a**2/z /*display the computed value of π*/ +numeric digits d /*set the numeric digits to D */ +say pi/1 /*display the computed value of π*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; m.=9; p=digits() +numeric digits 9; numeric form; m.0=p +parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2; m.1=p + do j=2 while p>9; m.j=p; p=p%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=.5*(g+x/g); end /*k*/ + numeric digits m.0; return (g/1) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx new file mode 100644 index 0000000000..f01480f22b --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx @@ -0,0 +1,24 @@ +/*REXX program calculates the value of pi using the AGM algorithm. */ +parse arg d .; if d=='' then d=500 /*D specified? Then use default.*/ +numeric digits d+5 /*set the numeric digits to D+5. */ +a=1; n=1; z=1/4; g=sqrt(1/2) /*calculate some initial values. */ + + do j=1 until a==old; old=a /*keep calculating until no noise*/ + x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms*/ + z=z-n*(x-a)**2; n=n+n; a=x /*Z is used in final calculation.*/ + many=compare(a,old) /*how many accurate digs computed*/ + if many==0 then many=d /*adjust for the very last time. */ + say right('iteration' j,20) right(many,9) "digits" /*show digs*/ + end /*j*/ /* [↑] stop if A equals OLD */ +say /*display a blank line for a sep.*/ +pi=a**2/z /*calculate the value of pi. */ +numeric digits d /*set the numeric digits to D */ +say pi/1 /*display the computed value of π*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; m.=9; p=digits() +numeric digits 9; numeric form; m.0=p +parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2; m.1=p + do j=2 while p>9; m.j=p; p=p%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=.5*(g+x/g); end /*k*/ + numeric digits m.0; return (g/1) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-3.rexx b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-3.rexx new file mode 100644 index 0000000000..70b4c5ac59 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-3.rexx @@ -0,0 +1,48 @@ +Do d=10 To 13 + Say d pib(d) + End +Do d=1000 To 1005 + pi=pib(d) + say d left(pi,5)'...'substr(pi,997) + End +Exit +pib: Procedure +/* REXX --------------------------------------------------------------- +* program calculates the value of pi using the AGM algorithm. +* building on top of version 2 +* reformatted, improved, and using 'my own' sqrt +* 08.07.2014 Walter Pachl +*--------------------------------------------------------------------*/ + Parse Arg d . + If d=='' Then + d=500 /* D specified? Then use default.*/ + Numeric Digits d+5 /* set the numeric digits to D+5. */ + a=1 + n=1 + z=1/4 + g=sqrt(1/2) /* calculate some initial values. */ + Do j=1 Until a==old + old=a /* keep calculating until no noise*/ + x=(a+g)*.5 + g=sqrt(a*g) /* calculate the next set of terms*/ + z=z-n*(x-a)**2 + n=n+n + a=x + End + pi=a**2/z + Numeric Digits d /* set the numeric digits to D */ + Return pi+0 + +sqrt: Procedure + Parse Arg x + xprec=digits() + iprec=xprec+10 + Numeric Digits iprec + r0=x + r =1 + Do i=1 By 1 Until r=r0 | (abs(r*r-x)<10**-iprec) + r0 = r + r = (r + x/r) / 2 + End + Numeric Digits xprec + Return (r+0) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Racket/arithmetic-geometric-mean-calculate-pi.rkt b/Task/Arithmetic-geometric-mean-Calculate-Pi/Racket/arithmetic-geometric-mean-calculate-pi.rkt new file mode 100644 index 0000000000..906dae436c --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Racket/arithmetic-geometric-mean-calculate-pi.rkt @@ -0,0 +1,23 @@ +#lang racket +(require math/bigfloat) + +(define (pi/a-g rep) + (let loop ([a 1.bf] + [g (bf1/sqrt 2.bf)] + [z (bf/ 1.bf 4.bf)] + [n (bf 1)] + [r 0]) + (if (< r rep) + (let* ([a-p (bf/ (bf+ a g) 2.bf)] + [g-p (bfsqrt (bf* a g))] + [z-p (bf- z (bf* (bfsqr (bf- a-p a)) n))]) + (loop a-p g-p z-p (bf* n 2.bf) (add1 r))) + (bf/ (bfsqr a) z)))) + +(parameterize ([bf-precision 100]) + (displayln (bigfloat->string (pi/a-g 5))) + (displayln (bigfloat->string pi.bf))) + +(parameterize ([bf-precision 200]) + (displayln (bigfloat->string (pi/a-g 6))) + (displayln (bigfloat->string pi.bf))) diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Ruby/arithmetic-geometric-mean-calculate-pi.rb b/Task/Arithmetic-geometric-mean-Calculate-Pi/Ruby/arithmetic-geometric-mean-calculate-pi.rb new file mode 100644 index 0000000000..ae9e30ba4c --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Ruby/arithmetic-geometric-mean-calculate-pi.rb @@ -0,0 +1,20 @@ +# Calculate Pi using the Arithmetic Geometric Mean of 1 and 1/sqrt(2) +# +# +# Nigel_Galloway +# March 8th., 2012. +# +require 'flt' +Flt::BinNum.Context.precision = 8192 +a = n = 1 +g = 1 / Flt::BinNum(2).sqrt +z = 0.25 +(0..17).each{ + x = [(a + g) * 0.5, (a * g).sqrt] + var = x[0] - a + z -= var * var * n + n += n + a = x[0] + g = x[1] +} +puts a * a / z diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Tcl/arithmetic-geometric-mean-calculate-pi.tcl b/Task/Arithmetic-geometric-mean-Calculate-Pi/Tcl/arithmetic-geometric-mean-calculate-pi.tcl new file mode 100644 index 0000000000..ac142eb40f --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Tcl/arithmetic-geometric-mean-calculate-pi.tcl @@ -0,0 +1,23 @@ +package require math::bigfloat +namespace import math::bigfloat::* + +proc agm/π {N {precision 8192}} { + set 1 [int2float 1 $precision] + set 2 [int2float 2 $precision] + set n 1 + set a $1 + set g [div $1 [sqrt $2]] + set z [div $1 [int2float 4 $precision]] + for {set i 0} {$i <= $N} {incr i} { + set x0 [div [add $a $g] $2] + set x1 [sqrt [mul $a $g]] + set var [sub $x0 $a] + set z [sub $z [mul [mul $var $n] $var]] + incr n $n + set a $x0 + set g $x1 + } + return [tostr [div [mul $a $a] $z]] +} + +puts [agm/π 17] diff --git a/Task/Benfords-law/00DESCRIPTION b/Task/Benfords-law/00DESCRIPTION new file mode 100644 index 0000000000..246bf34e89 --- /dev/null +++ b/Task/Benfords-law/00DESCRIPTION @@ -0,0 +1,18 @@ +{{Wikipedia|Benford's_law}} +'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. + +This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. + +A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability + +:P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right) + +For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). + +Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can [[Fibonacci sequence|generate]] them or load them [http://www.ibiblio.org/pub/docs/books/gutenberg/etext01/fbncc10.txt from a file]; whichever is easiest. Display your actual vs expected distribution. + +''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. + +;See also: +* [http://www.numberphile.com/videos/benfords_law.html numberphile.com]. +* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}. diff --git a/Task/Benfords-law/AWK/benfords-law.awk b/Task/Benfords-law/AWK/benfords-law.awk new file mode 100644 index 0000000000..52417f3b5d --- /dev/null +++ b/Task/Benfords-law/AWK/benfords-law.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f BENFORDS_LAW.AWK +BEGIN { + n = 1000 + for (i=1; i<=n; i++) { + arr[substr(fibonacci(i),1,1)]++ + } + print("digit expected observed deviation") + for (i=1; i<=9; i++) { + expected = log10(i+1) - log10(i) + actual = arr[i] / n + deviation = expected - actual + printf("%5d %8.4f %8.4f %9.4f\n",i,expected*100,actual*100,abs(deviation*100)) + } + exit(0) +} +function fibonacci(n, a,b,c,i) { + a = 0 + b = 1 + for (i=1; i<=n; i++) { + c = a + b + a = b + b = c + } + return(c) +} +function abs(x) { if (x >= 0) { return x } else { return -x } } +function log10(x) { return log(x)/log(10) } diff --git a/Task/Benfords-law/Ada/benfords-law-1.ada b/Task/Benfords-law/Ada/benfords-law-1.ada new file mode 100644 index 0000000000..b11e243437 --- /dev/null +++ b/Task/Benfords-law/Ada/benfords-law-1.ada @@ -0,0 +1,49 @@ +with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; + +procedure Benford is + + subtype Nonzero_Digit is Natural range 1 .. 9; + function First_Digit(S: String) return Nonzero_Digit is + (if S(S'First) in '1' .. '9' + then Nonzero_Digit'Value(S(S'First .. S'First)) + else First_Digit(S(S'First+1 .. S'Last))); + + package N_IO is new Ada.Text_IO.Integer_IO(Natural); + + procedure Print(D: Nonzero_Digit; Counted, Sum: Natural) is + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + package F_IO is new Ada.Text_IO.Float_IO(Float); + Actual: constant Float := Float(Counted) / Float(Sum); + Expected: constant Float := Math.Log(1.0 + 1.0 / Float(D), Base => 10.0); + Deviation: constant Float := abs(Expected-Actual); + begin + N_IO.Put(D, 5); + N_IO.Put(Counted, 14); + F_IO.Put(Float(Sum)*Expected, Fore => 16, Aft => 1, Exp => 0); + F_IO.Put(100.0*Actual, Fore => 9, Aft => 2, Exp => 0); + F_IO.Put(100.0*Expected, Fore => 11, Aft => 2, Exp => 0); + F_IO.Put(100.0*Deviation, Fore => 13, Aft => 2, Exp => 0); + end Print; + + Cnt: array(Nonzero_Digit) of Natural := (1 .. 9 => 0); + D: Nonzero_Digit; + Sum: Natural := 0; + Counter: Positive; + +begin + while not Ada.Text_IO.End_Of_File loop + -- each line in the input file holds Counter, followed by Fib(Counter) + N_IO.Get(Counter); + -- Counter and skip it, we just don't need it + D := First_Digit(Ada.Text_IO.Get_Line); + -- read the rest of the line and extract the first digit + Cnt(D) := Cnt(D)+1; + Sum := Sum + 1; + end loop; + Ada.Text_IO.Put_Line(" Digit Found[total] Expected[total] Found[%]" + & " Expected[%] Difference[%]"); + for I in Nonzero_Digit loop + Print(I, Cnt(I), Sum); + Ada.Text_IO.New_Line; + end loop; +end Benford; diff --git a/Task/Benfords-law/Ada/benfords-law-2.ada b/Task/Benfords-law/Ada/benfords-law-2.ada new file mode 100644 index 0000000000..e041c0ce41 --- /dev/null +++ b/Task/Benfords-law/Ada/benfords-law-2.ada @@ -0,0 +1 @@ + -- N_IO.Get(Counter); diff --git a/Task/Benfords-law/Aime/benfords-law.aime b/Task/Benfords-law/Aime/benfords-law.aime new file mode 100644 index 0000000000..2eb7a0227e --- /dev/null +++ b/Task/Benfords-law/Aime/benfords-law.aime @@ -0,0 +1,95 @@ +text +sum(text a, text b) +{ + data d; + integer e, f, n, r; + + e = length(a); + f = length(b); + + r = 0; + + n = min(e, f); + while (n) { + n -= 1; + e -= 1; + f -= 1; + r += a[e] - '0'; + r += b[f] - '0'; + b_insert(d, 0, r % 10 + '0'); + r /= 10; + } + + if (f) { + e = f; + a = b; + } + + while (e) { + e -= 1; + r += a[e] - '0'; + b_insert(d, 0, r % 10 + '0'); + r /= 10; + } + + if (r) { + b_insert(d, 0, r + '0'); + } + + return b_string(d); +} + +text +fibs(list l, integer n) +{ + integer c, i; + text a, b, w; + + l_r_integer(l, 1, 1); + + a = "0"; + b = "1"; + i = 1; + while (i < n) { + w = sum(a, b); + a = b; + b = w; + c = w[0] - '0'; + l_r_integer(l, c, 1 + l_q_integer(l, c)); + i += 1; + } + + return w; +} + +integer +main(void) +{ + integer i, n; + list f; + real m; + + n = 1000; + + i = 10; + while (i) { + i -= 1; + lb_p_integer(f, 0); + } + + fibs(f, n); + + m = 100r / n; + + o_text("\t\texpected\t found\n"); + i = 0; + while (i < 9) { + i += 1; + o_winteger(8, i); + o_wpreal(16, 3, 3, 100 * log10(1 + 1r / i)); + o_wpreal(16, 3, 3, l_q_integer(f, i) * m); + o_text("\n"); + } + + return 0; +} diff --git a/Task/Benfords-law/AutoHotkey/benfords-law.ahk b/Task/Benfords-law/AutoHotkey/benfords-law.ahk new file mode 100644 index 0000000000..61929fa93d --- /dev/null +++ b/Task/Benfords-law/AutoHotkey/benfords-law.ahk @@ -0,0 +1,43 @@ +SetBatchLines, -1 +fib := NStepSequence(1, 1, 2, 1000) +Out := "Digit`tExpected`tObserved`tDeviation`n" +n := [] +for k, v in fib + d := SubStr(v, 1, 1) + , n[d] := n[d] ? n[d] + 1 : 1 +for k, v in n + Exppected := 100 * Log(1+ (1 / k)) + , Observed := (v / fib.MaxIndex()) * 100 + , Out .= k "`t" Exppected "`t" Observed "`t" Abs(Exppected - Observed) "`n" +MsgBox, % Out + +NStepSequence(v1, v2, n, k) { + a := [v1, v2] + Loop, % k - 2 { + a[j := A_Index + 2] := 0 + Loop, % j < n + 2 ? j - 1 : n + a[j] := BigAdd(a[j - A_Index], a[j]) + } + return, a +} + +BigAdd(a, b) { + if (StrLen(b) > StrLen(a)) + t := a, a := b, b := t + LenA := StrLen(a) + 1, LenB := StrLen(B) + 1, Carry := 0 + Loop, % LenB - 1 + Sum := SubStr(a, LenA - A_Index, 1) + SubStr(B, LenB - A_Index, 1) + Carry + , Carry := Sum // 10 + , Result := Mod(Sum, 10) . Result + Loop, % I := LenA - LenB { + if (!Carry) { + Result := SubStr(a, 1, I) . Result + break + } + Sum := SubStr(a, I, 1) + Carry + , Carry := Sum // 10 + , Result := Mod(Sum, 10) . Result + , I-- + } + return, (Carry ? Carry : "") . Result +} diff --git a/Task/Benfords-law/C++/benfords-law.cpp b/Task/Benfords-law/C++/benfords-law.cpp new file mode 100644 index 0000000000..f3eac082bf --- /dev/null +++ b/Task/Benfords-law/C++/benfords-law.cpp @@ -0,0 +1,62 @@ +//to cope with the big numbers , I used the Class Library for Numbers( CLN ) +//if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace cln ; + +class NextNum { +public : + NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } + cl_I operator( )( ) { + cl_I result = first + second ; + first = second ; + second = result ; + return result ; + } +private : + cl_I first ; + cl_I second ; +} ; + +void findFrequencies( const std::vector & fibos , std::map &numberfrequencies ) { + for ( cl_I bignumber : fibos ) { + std::ostringstream os ; + fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h + int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; + auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; + if ( ! result.second ) + numberfrequencies[ firstdigit ]++ ; + } +} + +int main( ) { + std::vector fibonaccis( 1000 ) ; + fibonaccis[ 0 ] = 0 ; + fibonaccis[ 1 ] = 1 ; + cl_I a = 0 ; + cl_I b = 1 ; + //since a and b are passed as references to the generator's constructor + //they are constantly changed ! + std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; + std::cout << std::endl ; + std::map frequencies ; + findFrequencies( fibonaccis , frequencies ) ; + std::cout << " found expected\n" ; + for ( int i = 1 ; i < 10 ; i++ ) { + double found = static_cast( frequencies[ i ] ) / 1000 ; + double expected = std::log10( 1 + 1 / static_cast( i )) ; + std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; + std::cout.precision( 3 ) ; + std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; + } + return 0 ; +} diff --git a/Task/Benfords-law/C/benfords-law.c b/Task/Benfords-law/C/benfords-law.c new file mode 100644 index 0000000000..9c6a182fde --- /dev/null +++ b/Task/Benfords-law/C/benfords-law.c @@ -0,0 +1,64 @@ +#include +#include +#include + +float *benford_distribution(void) +{ + static float prob[9]; + for (int i = 1; i < 10; i++) + prob[i - 1] = log10f(1 + 1.0 / i); + + return prob; +} + +float *get_actual_distribution(char *fn) +{ + FILE *input = fopen(fn, "r"); + if (!input) + { + perror("Can't open file"); + exit(EXIT_FAILURE); + } + + int tally[9] = { 0 }; + char c; + int total = 0; + while ((c = getc(input)) != EOF) + { + /* get the first nonzero digit on the current line */ + while (c < '1' || c > '9') + c = getc(input); + + tally[c - '1']++; + total++; + + /* discard rest of line */ + while ((c = getc(input)) != '\n' && c != EOF) + ; + } + fclose(input); + + static float freq[9]; + for (int i = 0; i < 9; i++) + freq[i] = tally[i] / (float) total; + + return freq; +} + +int main(int argc, char **argv) +{ + if (argc != 2) + { + printf("Usage: benford \n"); + return EXIT_FAILURE; + } + + float *actual = get_actual_distribution(argv[1]); + float *expected = benford_distribution(); + + puts("digit\tactual\texpected"); + for (int i = 0; i < 9; i++) + printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); + + return EXIT_SUCCESS; +} diff --git a/Task/Benfords-law/CoffeeScript/benfords-law.coffee b/Task/Benfords-law/CoffeeScript/benfords-law.coffee new file mode 100644 index 0000000000..6332478e82 --- /dev/null +++ b/Task/Benfords-law/CoffeeScript/benfords-law.coffee @@ -0,0 +1,21 @@ +fibgen = () -> + a = 1; b = 0 + return () -> + ([a, b] = [b, a+b])[1] + +leading = (x) -> x.toString().charCodeAt(0) - 0x30 + +f = fibgen() + +benford = (0 for i in [1..9]) +benford[leading(f()) - 1] += 1 for i in [1..1000] + +log10 = (x) -> Math.log(x) * Math.LOG10E + +actual = benford.map (x) -> x * 0.001 +expected = (log10(1 + 1/x) for x in [1..9]) + +console.log "Leading digital distribution of the first 1,000 Fibonacci numbers" +console.log "Digit\tActual\tExpected" +for i in [1..9] + console.log i + "\t" + actual[i - 1].toFixed(3) + '\t' + expected[i - 1].toFixed(3) diff --git a/Task/Benfords-law/Common-Lisp/benfords-law.lisp b/Task/Benfords-law/Common-Lisp/benfords-law.lisp new file mode 100644 index 0000000000..fa7928c04a --- /dev/null +++ b/Task/Benfords-law/Common-Lisp/benfords-law.lisp @@ -0,0 +1,43 @@ +(defun calculate-distribution (numbers) + "Return the frequency distribution of the most significant nonzero + digits in the given list of numbers. The first element of the list + is the frequency for digit 1, the second for digit 2, and so on." + + (defun nonzero-digit-p (c) + "Check whether the character is a nonzero digit" + (and (digit-char-p c) (char/= c #\0))) + + (defun first-digit (n) + "Return the most significant nonzero digit of the number or NIL if + there is none." + (let* ((s (write-to-string n)) + (c (find-if #'nonzero-digit-p s))) + (when c + (digit-char-p c)))) + + (let ((tally (make-array 9 :element-type 'integer :initial-element 0))) + (loop for n in numbers + for digit = (first-digit n) + when digit + do (incf (aref tally (1- digit)))) + (loop with total = (length numbers) + for digit-count across tally + collect (/ digit-count total)))) + +(defun calculate-benford-distribution () + "Return the frequency distribution according to Benford's law. + The first element of the list is the probability for digit 1, the second + element the probability for digit 2, and so on." + (loop for i from 1 to 9 + collect (log (1+ (/ i)) 10))) + +(defun benford (numbers) + "Print a table of the actual and expected distributions for the given + list of numbers." + (let ((actual-distribution (calculate-distribution numbers)) + (expected-distribution (calculate-benford-distribution))) + (write-line "digit actual expected") + (format T "~:{~3D~9,3F~8,3F~%~}" + (map 'list #'list '(1 2 3 4 5 6 7 8 9) + actual-distribution + expected-distribution)))) diff --git a/Task/Benfords-law/D/benfords-law-1.d b/Task/Benfords-law/D/benfords-law-1.d new file mode 100644 index 0000000000..cd32ab5422 --- /dev/null +++ b/Task/Benfords-law/D/benfords-law-1.d @@ -0,0 +1,24 @@ +import std.stdio, std.range, std.math, std.conv, std.bigint; + +double[2][9] benford(R)(R seq) if (isForwardRange!R && !isInfinite!R) { + typeof(return) freqs = 0; + uint seqLen = 0; + foreach (d; seq) + if (d != 0) { + freqs[d.text[0] - '1'][1]++; + seqLen++; + } + + foreach (immutable i, ref p; freqs) + p = [log10(1.0 + 1.0 / (i + 1)), p[1] / seqLen]; + return freqs; +} + +void main() { + auto fibs = recurrence!q{a[n - 1] + a[n - 2]}(1.BigInt, 1.BigInt); + + writefln("%9s %9s %9s", "Actual", "Expected", "Deviation"); + foreach (immutable i, immutable p; fibs.take(1000).benford) + writefln("%d: %5.2f%% | %5.2f%% | %5.4f%%", + i+1, p[1] * 100, p[0] * 100, abs(p[1] - p[0]) * 100); +} diff --git a/Task/Benfords-law/D/benfords-law-2.d b/Task/Benfords-law/D/benfords-law-2.d new file mode 100644 index 0000000000..2fb3acded4 --- /dev/null +++ b/Task/Benfords-law/D/benfords-law-2.d @@ -0,0 +1,18 @@ +import std.stdio, std.range, std.math, std.conv, std.bigint, + std.algorithm, std.array; + +auto benford(R)(R seq) if (isForwardRange!R && !isInfinite!R) { + return seq.filter!q{a != 0}.map!q{a.text[0]-'1'}.array.sort().group; +} + +void main() { + auto fibs = recurrence!q{a[n - 1] + a[n - 2]}(1.BigInt, 1.BigInt); + auto expected = iota(1, 10).map!(d => log10(1.0 + 1.0 / d)); + + enum N = 1_000; + writefln("%9s %9s %9s", "Actual", "Expected", "Deviation"); + foreach (immutable i, immutable f; fibs.take(N).benford) + writefln("%d: %5.2f%% | %5.2f%% | %5.4f%%", i + 1, + f * 100.0 / N, expected[i] * 100, + abs((f / double(N)) - expected[i]) * 100); +} diff --git a/Task/Benfords-law/Erlang/benfords-law.erl b/Task/Benfords-law/Erlang/benfords-law.erl new file mode 100644 index 0000000000..78f07eb667 --- /dev/null +++ b/Task/Benfords-law/Erlang/benfords-law.erl @@ -0,0 +1,25 @@ +-module( benfords_law ). +-export( [actual_distribution/1, distribution/1, task/0] ). + +actual_distribution( Ns ) -> lists:foldl( fun first_digit_count/2, dict:new(), Ns ). + +distribution( N ) -> math:log10( 1 + (1 / N) ). + +task() -> + Total = 1000, + Fibonaccis = fib( Total ), + Actual_dict = actual_distribution( Fibonaccis ), + Keys = lists:sort( dict:fetch_keys( Actual_dict) ), + io:fwrite( "Digit Actual Benfords expected~n" ), + [io:fwrite("~p ~p ~p~n", [X, dict:fetch(X, Actual_dict) / Total, distribution(X)]) || X <- Keys]. + + + +fib( N ) -> fib( N, 0, 1, [] ). +fib( 0, Current, _, Acc ) -> lists:reverse( [Current | Acc] ); +fib( N, Current, Next, Acc ) -> fib( N-1, Next, Current+Next, [Current | Acc] ). + +first_digit_count( 0, Dict ) -> Dict; +first_digit_count( N, Dict ) -> + [Key | _] = erlang:integer_to_list( N ), + dict:update_counter( Key - 48, 1, Dict ). diff --git a/Task/Benfords-law/Forth/benfords-law.fth b/Task/Benfords-law/Forth/benfords-law.fth new file mode 100644 index 0000000000..f516d2fc21 --- /dev/null +++ b/Task/Benfords-law/Forth/benfords-law.fth @@ -0,0 +1,44 @@ +: 3drop drop 2drop ; +: f2drop fdrop fdrop ; + +: int-array create cells allot does> swap cells + ; + +: 1st-fib 0e 1e ; +: next-fib ftuck f+ ; + +: 1st-digit ( fp -- n ) + pad 6 represent 3drop pad c@ [char] 0 - ; + +10 int-array counts + +: tally + 0 counts 10 cells erase + 1st-fib + 1000 0 DO + 1 fdup 1st-digit counts +! + next-fib + LOOP f2drop ; + +: benford ( d -- fp ) + s>f 1/f 1e f+ flog ; + +: tab 9 emit ; + +: heading ( -- ) + cr ." Leading digital distribution of the first 1,000 Fibonacci numbers:" + cr ." Digit" tab ." Actual" tab ." Expected" ; + +: .fixed ( n -- ) \ print count as decimal fraction + s>d <# # # # [char] . hold #s #> type space ; + +: report ( -- ) + precision 3 set-precision + heading + 10 1 DO + cr i 3 .r + tab i counts @ .fixed + tab i benford f. + LOOP + set-precision ; + +: compute-benford tally report ; diff --git a/Task/Benfords-law/Fortran/benfords-law-1.f b/Task/Benfords-law/Fortran/benfords-law-1.f new file mode 100644 index 0000000000..b445028bc8 --- /dev/null +++ b/Task/Benfords-law/Fortran/benfords-law-1.f @@ -0,0 +1,9 @@ +-*- mode: compilation; default-directory: "/tmp/" -*- +Compilation started at Sat May 18 01:13:00 + +a=./f && make $a && $a +f95 -Wall -ffree-form f.F -o f + 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW + 0.300999999 0.177000001 0.125000000 9.60000008E-02 7.99999982E-02 6.70000017E-02 5.70000000E-02 5.29999994E-02 4.50000018E-02 LEADING FIBONACCI DIGIT + +Compilation finished at Sat May 18 01:13:00 diff --git a/Task/Benfords-law/Fortran/benfords-law-2.f b/Task/Benfords-law/Fortran/benfords-law-2.f new file mode 100644 index 0000000000..1a504d43fc --- /dev/null +++ b/Task/Benfords-law/Fortran/benfords-law-2.f @@ -0,0 +1,69 @@ +subroutine fibber(a,b,c,d) + ! compute most significant digits, Fibonacci like. + implicit none + integer (kind=8), intent(in) :: a,b + integer (kind=8), intent(out) :: c,d + d = a + b + if (15 .lt. log10(float(d))) then + c = b/10 + d = d/10 + else + c = b + endif +end subroutine fibber + +integer function leadingDigit(a) + implicit none + integer (kind=8), intent(in) :: a + integer (kind=8) :: b + b = a + do while (9 .lt. b) + b = b/10 + end do + leadingDigit = transfer(b,leadingDigit) +end function leadingDigit + +real function benfordsLaw(a) + implicit none + integer, intent(in) :: a + benfordsLaw = log10(1.0 + 1.0 / a) +end function benfordsLaw + +program benford + + implicit none + + interface + + subroutine fibber(a,b,c,d) + implicit none + integer (kind=8), intent(in) :: a,b + integer (kind=8), intent(out) :: c,d + end subroutine fibber + + integer function leadingDigit(a) + implicit none + integer (kind=8), intent(in) :: a + end function leadingDigit + + real function benfordsLaw(a) + implicit none + integer, intent(in) :: a + end function benfordsLaw + + end interface + + integer (kind=8) :: a, b, c, d + integer :: i, count(10) + data count/10*0/ + a = 1 + b = 1 + do i = 1, 1001 + count(leadingDigit(a)) = count(leadingDigit(a)) + 1 + call fibber(a,b,c,d) + a = c + b = d + end do + write(6,*) (benfordsLaw(i),i=1,9),'THE LAW' + write(6,*) (count(i)/1000.0 ,i=1,9),'LEADING FIBONACCI DIGIT' +end program benford diff --git a/Task/Benfords-law/Go/benfords-law.go b/Task/Benfords-law/Go/benfords-law.go new file mode 100644 index 0000000000..7003f19cd1 --- /dev/null +++ b/Task/Benfords-law/Go/benfords-law.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "math" +) + +func Fib1000() []float64 { + a, b, r := 0., 1., [1000]float64{} + for i := range r { + r[i], a, b = b, b, b+a + } + return r[:] +} + +func main() { + show(Fib1000(), "First 1000 Fibonacci numbers") +} + +func show(c []float64, title string) { + var f [9]int + for _, v := range c { + f[fmt.Sprintf("%g", v)[0]-'1']++ + } + fmt.Println(title) + fmt.Println("Digit Observed Predicted") + for i, n := range f { + fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), + math.Log10(1+1/float64(i+1))) + } +} diff --git a/Task/Benfords-law/Haskell/benfords-law.hs b/Task/Benfords-law/Haskell/benfords-law.hs new file mode 100644 index 0000000000..11ea5a5a76 --- /dev/null +++ b/Task/Benfords-law/Haskell/benfords-law.hs @@ -0,0 +1,17 @@ +import qualified Data.Map as M +import Data.Char (digitToInt) + +fstdigit :: Integer -> Int +fstdigit = digitToInt . head . show + +n = 1000::Int +fibs = 1:1:zipWith (+) fibs (tail fibs) +fibdata = map fstdigit $ take n fibs +freqs = M.fromListWith (+) $ zip fibdata (repeat 1) + +tab :: [(Int, Double, Double)] +tab = [(d, + (fromIntegral (M.findWithDefault 0 d freqs) /(fromIntegral n) ), + logBase 10.0 $ 1 + 1/(fromIntegral d) ) | d<-[1..9]] + +main = print tab diff --git a/Task/Benfords-law/Icon/benfords-law.icon b/Task/Benfords-law/Icon/benfords-law.icon new file mode 100644 index 0000000000..e982afb1ed --- /dev/null +++ b/Task/Benfords-law/Icon/benfords-law.icon @@ -0,0 +1,34 @@ +global counts, total + +procedure main() + + counts := table(0) + total := 0.0 + every benlaw(fib(1 to 1000)) + + every i := 1 to 9 do + write(i,": ",right(100*counts[string(i)]/total,9)," ",100*P(i)) + +end + +procedure benlaw(n) + if counts[n ? (tab(upto('123456789')),move(1))] +:= 1 then total +:= 1 +end + +procedure P(d) + return log(1+1.0/d, 10) +end + +procedure fib(n) # From Fibonacci Sequence task + return fibMat(n)[1] +end + +procedure fibMat(n) + if n <= 0 then return [0,0] + if n = 1 then return [1,0] + fp := fibMat(n/2) + c := fp[1]*fp[1] + fp[2]*fp[2] + d := fp[1]*(fp[1]+2*fp[2]) + if n%2 = 1 then return [c+d, d] + else return [d, c] +end diff --git a/Task/Benfords-law/J/benfords-law.j b/Task/Benfords-law/J/benfords-law.j new file mode 100644 index 0000000000..23e3dbae5d --- /dev/null +++ b/Task/Benfords-law/J/benfords-law.j @@ -0,0 +1,36 @@ +log10 =: 10&^. +benford =: log10@:(1+%) +assert '0.30 0.18 0.12 0.10 0.08 0.07 0.06 0.05 0.05' -: 5j2 ": benford >: i. 9 + + +append_next_fib =: , +/@:(_2&{.) +assert 5 8 13 -: append_next_fib 5 8 + +leading_digits =: {.@":&> +assert '581' -: leading_digits 5 8 13x + +count =: #/.~ /: ~. +assert 2 1 3 4 -: count 'XCXBAXACXC' NB. 2 A's, 1 B, 3 C's, and some X's. + +normalize =: % +/ +assert 1r3 2r3 -: normalize 1 2x + +FIB =: append_next_fib ^: (1000-#) 1 1 +LDF =: leading_digits FIB + + +TALLY_BY_KEY =: count LDF +assert 9 -: # TALLY_BY_KEY NB. If all of [1-9] are present then we know what the digits are. + +mean =: +/ % # +center=: - mean +mp =: $:~ :(+/ .*) +num =: mp&:center +den =: %:@:(*&:(+/@:(*:@:center))) +r =: num % den NB. r is the LibreOffice correl function +assert '_0.982' -: 6j3 ": 1 2 3 r 6 5 3 NB. confirmed using LibreOffice correl function + + +assert '0.9999' -: 6j4 ": (normalize TALLY_BY_KEY) r benford >: i.9 + +assert '0.9999' -: 6j4 ": TALLY_BY_KEY r benford >: i.9 NB. Of course we don't need normalization diff --git a/Task/Benfords-law/Java/benfords-law.java b/Task/Benfords-law/Java/benfords-law.java new file mode 100644 index 0000000000..904711c63c --- /dev/null +++ b/Task/Benfords-law/Java/benfords-law.java @@ -0,0 +1,41 @@ +import java.math.BigInteger; + +public class Benford { + private static interface NumberGenerator { + BigInteger[] getNumbers(); + } + + private static class FibonacciGenerator implements NumberGenerator { + public BigInteger[] getNumbers() { + final BigInteger[] fib = new BigInteger[ 1000 ]; + fib[ 0 ] = fib[ 1 ] = BigInteger.ONE; + for ( int i = 2; i < fib.length; i++ ) + fib[ i ] = fib[ i - 2 ].add( fib[ i - 1 ] ); + return fib; + } + } + + private final int[] firstDigits = new int[ 9 ]; + private final int count; + + private Benford( final NumberGenerator ng ) { + final BigInteger[] numbers = ng.getNumbers(); + count = numbers.length; + for ( final BigInteger number : numbers ) + firstDigits[ Integer.valueOf( number.toString().substring( 0, 1 ) ) - 1 ]++; + } + + public String toString() { + final StringBuilder result = new StringBuilder(); + for ( int i = 0; i < firstDigits.length; i++ ) + result.append( i + 1 ) + .append( '\t' ).append( firstDigits[ i ] / ( double )count ) + .append( '\t' ).append( Math.log10( 1 + 1d / ( i + 1 ) ) ) + .append( '\n' ); + return result.toString(); + } + + public static void main( final String[] args ) { + System.out.println( new Benford( new FibonacciGenerator() ) ); + } +} diff --git a/Task/Benfords-law/Julia/benfords-law.julia b/Task/Benfords-law/Julia/benfords-law.julia new file mode 100644 index 0000000000..0ad27c7f0a --- /dev/null +++ b/Task/Benfords-law/Julia/benfords-law.julia @@ -0,0 +1,5 @@ +fib(n) = ([one(n) one(n) ; one(n) zero(n)]^n)[1,2] + +ben(l) = [count(x->x==i, map(n->string(n)[1],l)) for i='1':'9']./length(l) + +benford(l) = [Number[1:9] ben(l) log10(1.+1./[1:9])] diff --git a/Task/Benfords-law/Liberty-BASIC/benfords-law.liberty b/Task/Benfords-law/Liberty-BASIC/benfords-law.liberty new file mode 100644 index 0000000000..c28f9abf53 --- /dev/null +++ b/Task/Benfords-law/Liberty-BASIC/benfords-law.liberty @@ -0,0 +1,35 @@ +dim bin(9) + +N=1000 +for i = 0 to N-1 + num$ = str$(fiboI(i)) + d=val(left$(num$,1)) + 'print num$, d + bin(d)=bin(d)+1 +next +print + +print "Digit", "Actual freq", "Expected freq" +for i = 1 to 9 + print i, bin(i)/N, using("#.###", P(i)) +next + + +function P(d) + P = log10(d+1)-log10(d) +end function + +function log10(x) + log10 = log(x)/log(10) +end function + +function fiboI(n) + a = 0 + b = 1 + for i = 1 to n + temp = a + b + a = b + b = temp + next i + fiboI = a +end function diff --git a/Task/Benfords-law/Lua/benfords-law.lua b/Task/Benfords-law/Lua/benfords-law.lua new file mode 100644 index 0000000000..afa93c003a --- /dev/null +++ b/Task/Benfords-law/Lua/benfords-law.lua @@ -0,0 +1,20 @@ +actual = {} +expected = {} +for i = 1, 9 do + actual[i] = 0 + expected[i] = math.log10(1 + 1 / i) +end + +n = 0 +file = io.open("fibs1000.txt", "r") +for line in file:lines() do + digit = string.byte(line, 1) - 48 + actual[digit] = actual[digit] + 1 + n = n + 1 +end +file:close() + +print("digit actual expected") +for i = 1, 9 do + print(i, actual[i] / n, expected[i]) +end diff --git a/Task/Benfords-law/Mathematica/benfords-law.math b/Task/Benfords-law/Mathematica/benfords-law.math new file mode 100644 index 0000000000..b3fae86ea4 --- /dev/null +++ b/Task/Benfords-law/Mathematica/benfords-law.math @@ -0,0 +1,3 @@ +fibdata = Array[First@IntegerDigits@Fibonacci@# &, 1000]; +Table[{d, N@Count[fibdata, d]/Length@fibdata, Log10[1. + 1/d]}, {d, 1, + 9}] // Grid diff --git a/Task/Benfords-law/NetRexx/benfords-law.netrexx b/Task/Benfords-law/NetRexx/benfords-law.netrexx new file mode 100644 index 0000000000..b392547d2b --- /dev/null +++ b/Task/Benfords-law/NetRexx/benfords-law.netrexx @@ -0,0 +1,41 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method brenfordDeveation(nlist = Rexx[]) public static + observed = 0 + loop n_ over nlist + d1 = n_.left(1) + if d1 = 0 then iterate n_ + observed[d1] = observed[d1] + 1 + end n_ + say ' '.right(4) 'Observed'.right(11) 'Expected'.right(11) 'Deviation'.right(11) + loop n_ = 1 to 9 + actual = (observed[n_] / (nlist.length - 1)) + expect = Rexx(Math.log10(1 + 1 / n_)) + deviat = expect - actual + say n_.right(3)':' (actual * 100).format(3, 6)'%' (expect * 100).format(3, 6)'%' (deviat * 100).abs().format(3, 6)'%' + end n_ + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method fibonacciList(size = 1000) public static returns Rexx[] + fibs = Rexx[size + 1] + fibs[0] = 0 + fibs[1] = 1 + loop n_ = 2 to size + fibs[n_] = fibs[n_ - 1] + fibs[n_ - 2] + end n_ + return fibs + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg n_ . + if n_ = '' then n_ = 1000 + fibList = fibonacciList(n_) + say 'Fibonacci sequence to' n_ + brenfordDeveation(fibList) + return diff --git a/Task/Benfords-law/PARI-GP/benfords-law.pari b/Task/Benfords-law/PARI-GP/benfords-law.pari new file mode 100644 index 0000000000..9535cbc06e --- /dev/null +++ b/Task/Benfords-law/PARI-GP/benfords-law.pari @@ -0,0 +1,9 @@ +distribution(v)={ + my(t=vector(9,n,sum(i=1,#v,v[i]==n))); + print("Digit\tActual\tExpected"); + for(i=1,9,print(i, "\t", t[i], "\t", round(#v*(log(i+1)-log(i))/log(10)))) +}; +dist(f)=distribution(vector(1000,n,digits(f(n))[1])); +lucas(n)=fibonacci(n-1)+fibonacci(n+1); +dist(fibonacci) +dist(lucas) diff --git a/Task/Benfords-law/PL-I/benfords-law.pli b/Task/Benfords-law/PL-I/benfords-law.pli new file mode 100644 index 0000000000..39840f4bd4 --- /dev/null +++ b/Task/Benfords-law/PL-I/benfords-law.pli @@ -0,0 +1,39 @@ +(fofl, size, subrg): +Benford: procedure options(main); /* 20 October 2013 */ + declare sc(1000) char(1), f(1000) float (16); + declare d fixed (1); + + call Fibonacci(f); + call digits(sc, f); + + put skip list ('digit expected obtained'); + do d= 1 upthru 9; + put skip edit (d, log10(1 + 1/d), tally(sc, trim(d))/1000) + (f(3), 2 f(13,8) ); + end; + +Fibonacci: procedure (f); + declare f(*) float (16); + declare i fixed binary; + + f(1), f(2) = 1; + do i = 3 to 1000; + f(i) = f(i-1) + f(i-2); + end; +end Fibonacci; + +digits: procedure (sc, f); + declare sc(*) char(1), f(*) float (16); + sc = substr(trim(f), 1, 1); +end digits; + +tally: procedure (sc, d) returns (fixed binary); + declare sc(*) char(1), d char(1); + declare (i, t) fixed binary; + t = 0; + do i = 1 to 1000; + if sc(i) = d then t = t + 1; + end; + return (t); +end tally; +end Benford; diff --git a/Task/Benfords-law/PL-pgSQL/benfords-law.sql b/Task/Benfords-law/PL-pgSQL/benfords-law.sql new file mode 100644 index 0000000000..32fbeb50bc --- /dev/null +++ b/Task/Benfords-law/PL-pgSQL/benfords-law.sql @@ -0,0 +1,34 @@ +WITH recursive +constant(val) AS +( +select 1000. +) +, +fib(a,b) AS +( +SELECT CAST(0 AS numeric), CAST(1 AS numeric) +UNION ALL +SELECT b,a+b +FROM fib +) +, +benford(first_digit, probability_real, probability_theoretical) AS +( +SELECT *, + CAST(log(1. + 1./CAST(first_digit AS INT)) AS NUMERIC(5,4)) probability_theoretical +FROM ( + SELECT first_digit, CAST(COUNT(1)/(select val from constant) AS NUMERIC(5,4)) probability_real FROM + ( + SELECT SUBSTRING(CAST(a AS VARCHAR(100)),1,1) first_digit + FROM fib + WHERE SUBSTRING(CAST(a AS VARCHAR(100)),1,1) <> '0' + LIMIT (select val from constant) + ) t + GROUP BY first_digit +) f +ORDER BY first_digit ASC +) +select * +from benford cross join + (select cast(corr(probability_theoretical,probability_real) as numeric(5,4)) correlation + from benford) c diff --git a/Task/Benfords-law/Perl-6/benfords-law.pl6 b/Task/Benfords-law/Perl-6/benfords-law.pl6 new file mode 100644 index 0000000000..0f265b2d01 --- /dev/null +++ b/Task/Benfords-law/Perl-6/benfords-law.pl6 @@ -0,0 +1,14 @@ +sub benford(@a) { bag +« @a».comb: /<( <[ 1..9 ]> )> <[ , . \d ]>*/ } + +sub show(%distribution) { + printf "%9s %9s %s\n", ; + for 1 .. 9 -> $digit { + my $actual = %distribution{$digit} * 100 / [+] %distribution.values; + my $expected = (1 + 1 / $digit).log(10) * 100; + printf "%d: %5.2f%% | %5.2f%% | %.2f%%\n", + $digit, $actual, $expected, abs($expected - $actual); + } +} + +multi MAIN($file) { show benford $file.IO.lines } +multi MAIN() { show benford ( 1, 1, 2, *+* ... * )[^1000] } diff --git a/Task/Benfords-law/Perl/benfords-law.pl b/Task/Benfords-law/Perl/benfords-law.pl new file mode 100644 index 0000000000..c712537a48 --- /dev/null +++ b/Task/Benfords-law/Perl/benfords-law.pl @@ -0,0 +1,25 @@ +#!/usr/bin/perl +use strict ; +use warnings ; +use POSIX qw( log10 ) ; + +my @fibonacci = ( 0 , 1 ) ; +while ( @fibonacci != 1000 ) { + push @fibonacci , $fibonacci[ -1 ] + $fibonacci[ -2 ] ; +} +my @actuals ; +my @expected ; +for my $i( 1..9 ) { + my $sum = 0 ; + map { $sum++ if $_ =~ /\A$i/ } @fibonacci ; + push @actuals , $sum / 1000 ; + push @expected , log10( 1 + 1/$i ) ; +} +print " Observed Expected\n" ; +for my $i( 1..9 ) { + print "$i : " ; + my $result = sprintf ( "%.2f" , 100 * $actuals[ $i - 1 ] ) ; + printf "%11s %%" , $result ; + $result = sprintf ( "%.2f" , 100 * $expected[ $i - 1 ] ) ; + printf "%15s %%\n" , $result ; +} diff --git a/Task/Benfords-law/Prolog/benfords-law.pro b/Task/Benfords-law/Prolog/benfords-law.pro new file mode 100644 index 0000000000..cf8374bf32 --- /dev/null +++ b/Task/Benfords-law/Prolog/benfords-law.pro @@ -0,0 +1,44 @@ +%_________________________________________________________________ +% Does the Fibonacci sequence follow Benford's law? +%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +% Fibonacci sequence generator +fib(C, [P,S], C, N) :- N is P + S. +fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V). + +fib(0, 0). +fib(1, 1). +fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on + +% The benford law calculated +benford(D, Val) :- Val is log10(1+1/D). + +% Retrieves the first characters of the first 1000 fibonacci numbers +% (excluding zero) +firstchar(V) :- + fib(C,N), N =\= 0, atom_chars(N, [Ch|_]), number_chars(V, [Ch]), + (C>999-> !; true). + +% Increment the n'th list item (1 based), result -> third argument. +incNth(1, [Dh|Dt], [Ch|Dt]) :- !, succ(Dh, Ch). +incNth(H, [Dh|Dt], [Dh|Ct]) :- succ(Hn, H), !, incNth(Hn, Dt, Ct). + +% Calculate the frequency of the all the list items +freq([], D, D). +freq([H|T], D, C) :- incNth(H, D, L), !, freq(T, L, C). + +freq([H|T], Freq) :- + length([H|T], Len), min_list([H|T], Min), max_list([H|T], Max), + findall(0, between(Min,Max,_), In), + freq([H|T], In, F), % Frequency stored in F + findall(N, (member(V, F), N is V/Len), Freq). % Normalise F->Freq + +% Output the results +writeHdr :- + format('~t~w~15| - ~t~w\n', ['Benford', 'Measured']). +writeData(Benford, Freq) :- + format('~t~2f%~15| - ~t~2f%\n', [Benford*100, Freq*100]). + +go :- % main goal + findall(B, (between(1,9,N), benford(N,B)), Benford), + findall(C, firstchar(C), Fc), freq(Fc, Freq), + writeHdr, maplist(writeData, Benford, Freq). diff --git a/Task/Benfords-law/Python/benfords-law.py b/Task/Benfords-law/Python/benfords-law.py new file mode 100644 index 0000000000..17d746617c --- /dev/null +++ b/Task/Benfords-law/Python/benfords-law.py @@ -0,0 +1,39 @@ +from __future__ import division +from itertools import islice, count +from collections import Counter +from math import log10 +from random import randint + +expected = [log10(1+1/d) for d in range(1,10)] + +def fib(): + a,b = 1,1 + while True: + yield a + a,b = b,a+b + +# powers of 3 as a test sequence +def power_of_threes(): + return (3**k for k in count(0)) + +def heads(s): + for a in s: yield int(str(a)[0]) + +def show_dist(title, s): + c = Counter(s) + size = sum(c.values()) + res = [c[d]/size for d in range(1,10)] + + print("\n%s Benfords deviation" % title) + for r, e in zip(res, expected): + print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) + +def rand1000(): + while True: yield randint(1,9999) + +if __name__ == '__main__': + show_dist("fibbed", islice(heads(fib()), 1000)) + show_dist("threes", islice(heads(power_of_threes()), 1000)) + + # just to show that not all kind-of-random sets behave like that + show_dist("random", islice(heads(rand1000()), 10000)) diff --git a/Task/Benfords-law/R/benfords-law.r b/Task/Benfords-law/R/benfords-law.r new file mode 100644 index 0000000000..ac15f628c1 --- /dev/null +++ b/Task/Benfords-law/R/benfords-law.r @@ -0,0 +1,31 @@ +pbenford <- function(d){ + return(log10(1+(1/d))) +} + +get_lead_digit <- function(number){ + return(as.numeric(substr(number,1,1))) +} + +fib_iter <- function(n){ + first <- 1 + second <- 0 + for(i in 1:n){ + sum <- first + second + first <- second + second <- sum + } + return(sum) +} + +fib_sequence <- mapply(fib_iter,c(1:1000)) +lead_digits <- mapply(get_lead_digit,fib_sequence) + +observed_frequencies <- table(lead_digits)/1000 +expected_frequencies <- mapply(pbenford,c(1:9)) + +data <- data.frame(observed_frequencies,expected_frequencies) +colnames(data) <- c("digit","obs.frequency","exp.frequency") +dev_percentage <- abs((data$obs.frequency-data$exp.frequency)*100) +data <- data.frame(data,dev_percentage) + +print(data) diff --git a/Task/Benfords-law/README b/Task/Benfords-law/README new file mode 100644 index 0000000000..c85e8e2abf --- /dev/null +++ b/Task/Benfords-law/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Benford's_law diff --git a/Task/Benfords-law/REXX/benfords-law.rexx b/Task/Benfords-law/REXX/benfords-law.rexx new file mode 100644 index 0000000000..893b777c59 --- /dev/null +++ b/Task/Benfords-law/REXX/benfords-law.rexx @@ -0,0 +1,33 @@ +/*REXX program demonstrates some common trig functions (30 digits shown)*/ +numeric digits 50 /*use only 50 digits for LN, LOG.*/ +parse arg N .; if N=='' then N=1000 /*allow sample size specification*/ + /*══════════════apply Benford's law to Fibonacci numbers.*/ +@.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2+@.jm1; end /*j*/ +call show_results "Benford's law applied to" N 'Fibonacci numbers' + /*══════════════apply Benford's law to prime numbers. */ +p=0; do j=2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j;end +call show_results "Benford's law applied to" N 'prime numbers' + /*══════════════apply Benford's law to factorials. */ + do j=1 for N; @.j=!(j); end /*j*/ +call show_results "Benford's law applied to" N 'factorial products' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOW_RESULTS subroutine─────────────*/ +show_results: w1=max(length('observed'),length(N-2)) ; say +pad=' '; w2=max(length('expected' ),length(N )) +say pad 'digit' pad center('observed',w1) pad center('expected',w2) +say pad '─────' pad center('',w1,'─') pad center('',w2,'─') pad arg(1) +!.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/ + + do k=1 for 9 /*show results for Fibonacci nums*/ + say pad center(k,5) pad center(format(!.k/N,,length(N-2)),w1), + pad center(format(log(1+1/k),,length(N)+2),w2) + end /*k*/ +return +/*──────────────────────────────────one─line subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end /*j*/; return ! +e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 +isprime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1 +ln10:return 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896538 +ln:procedure expose $.;parse arg x,f;if x==10 then do;_=ln10();xx=format(_);if xx\==_ then return xx;end;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 +log:return ln(arg(1))/ln(10) diff --git a/Task/Benfords-law/Racket/benfords-law.rkt b/Task/Benfords-law/Racket/benfords-law.rkt new file mode 100644 index 0000000000..3defed63c9 --- /dev/null +++ b/Task/Benfords-law/Racket/benfords-law.rkt @@ -0,0 +1,36 @@ +#lang racket + +(define (log10 n) (/ (log n) (log 10))) + +(define (first-digit n) + (quotient n (expt 10 (inexact->exact (floor (log10 n)))))) + +(define N 10000) + +(define fibs + (let loop ([n N] [a 0] [b 1]) + (if (zero? n) '() (cons b (loop (sub1 n) b (+ a b)))))) + +(define v (make-vector 10 0)) +(for ([n fibs]) + (define f (first-digit n)) + (vector-set! v f (add1 (vector-ref v f)))) + +(printf "N OBS EXP\n") +(define (pct n) (~r (* n 100.0) #:precision 1 #:min-width 4)) +(for ([i (in-range 1 10)]) + (printf "~a: ~a% ~a%\n" i + (pct (/ (vector-ref v i) N)) + (pct (log10 (+ 1 (/ i)))))) + +;; Output: +;; N OBS EXP +;; 1: 30.1% 30.1% +;; 2: 17.6% 17.6% +;; 3: 12.5% 12.5% +;; 4: 9.7% 9.7% +;; 5: 7.9% 7.9% +;; 6: 6.7% 6.7% +;; 7: 5.8% 5.8% +;; 8: 5.1% 5.1% +;; 9: 4.6% 4.6% diff --git a/Task/Benfords-law/Ruby/benfords-law.rb b/Task/Benfords-law/Ruby/benfords-law.rb new file mode 100644 index 0000000000..42719d3bbd --- /dev/null +++ b/Task/Benfords-law/Ruby/benfords-law.rb @@ -0,0 +1,37 @@ +EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)} + +def fib(n) + a,b = 0,1 + n.times.map{ret, a, b = a, b, a+b; ret} +end + +# powers of 3 as a test sequence +def power_of_threes(n) + n.times.map{|k| 3**k} +end + +def heads(s) + s.map{|a| a.to_s[0].to_i} +end + +def show_dist(title, s) + s = heads(s) + c = Array.new(10, 0) + s.each{|x| c[x] += 1} + size = s.size.to_f + res = (1..9).map{|d| c[d]/size} + puts "\n %s Benfords deviation" % title + res.zip(EXPECTED).each.with_index(1) do |(r, e), i| + puts "%2d: %5.1f%% %5.1f%% %5.1f%%" % [i, r*100, e*100, (r - e).abs*100] + end +end + +def random(n) + n.times.map{rand(1..n)} +end + +show_dist("fibbed", fib(1000)) +show_dist("threes", power_of_threes(1000)) + +# just to show that not all kind-of-random sets behave like that +show_dist("random", random(10000)) diff --git a/Task/Benfords-law/Run-BASIC/benfords-law.run b/Task/Benfords-law/Run-BASIC/benfords-law.run new file mode 100644 index 0000000000..8a80663c2f --- /dev/null +++ b/Task/Benfords-law/Run-BASIC/benfords-law.run @@ -0,0 +1,30 @@ +N = 1000 +for i = 0 to N - 1 + n$ = str$(fibonacci(i)) + j = val(left$(n$,1)) + actual(j) = actual(j) +1 +next +print +html "" +for i = 1 to 9 + html "" +next +html "
DigitActualExpected
";i;"";using("##.###",actual(i)/10);"";using("##.###", frequency(i)*100);"
" +end + +function frequency(n) + frequency = log10(n+1) - log10(n) +end function + +function log10(n) + log10 = log(n) / log(10) +end function + +function fibonacci(n) + b = 1 + for i = 1 to n + temp = fibonacci + b + fibonacci = b + b = temp + next i +end function diff --git a/Task/Benfords-law/SQL/benfords-law.sql b/Task/Benfords-law/SQL/benfords-law.sql new file mode 100644 index 0000000000..aa5a8b34a9 --- /dev/null +++ b/Task/Benfords-law/SQL/benfords-law.sql @@ -0,0 +1,43 @@ +-- Create table +create table benford (num integer); + +-- Seed table +insert into benford (num) values (1); +insert into benford (num) values (1); +insert into benford (num) values (2); + +-- Populate table +insert into benford (num) + select + ult + penult + from + (select max(num) as ult from benford), + (select max(num) as penult from benford where num not in (select max(num) from benford)) + +-- Repeat as many times as desired +-- in Oracle SQL*Plus, press "Slash, Enter" a lot of times +-- or wrap this in a loop, but that will require something db-specific... + +-- Do sums +select + digit, + count(digit) / numbers as actual, + log(10, 1 + 1 / digit) as expected +from + ( + select + floor(num/power(10,length(num)-1)) as digit + from + benford + ), + ( + select + count(*) as numbers + from + benford + ) +group by digit, numbers +order by digit; + +-- Tidy up +drop table benford; diff --git a/Task/Benfords-law/Scala/benfords-law.scala b/Task/Benfords-law/Scala/benfords-law.scala new file mode 100644 index 0000000000..2d4e765605 --- /dev/null +++ b/Task/Benfords-law/Scala/benfords-law.scala @@ -0,0 +1,29 @@ +// Fibonacci Sequence (begining with 1,1): 1 1 2 3 5 8 13 21 34 55 ... +val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail } + + +/** + * Given a numeric sequence, return the distribution of the most-signicant-digit + * as expected by Benford's Law and then by actual distribution. + */ +def benford[N:Numeric]( data:Seq[N] ) : Map[Int,(Double,Double)] = { + + import scala.math._ + + val maxSize = 10000000 // An arbitrary size to avoid problems with endless streams + + val size = (data.take(maxSize)).size.toDouble + + val distribution = data.take(maxSize).groupBy(_.toString.head.toString.toInt).map{ case (d,l) => (d -> l.size) } + + (for( i <- (1 to 9) ) yield { (i -> (log10(1D + 1D / i), (distribution(i) / size))) }).toMap +} + +{ + println( "Fibonacci Sequence (size=1000): 1 1 2 3 5 8 13 21 34 55 ...\n" ) + println( "%9s %9s %9s".format( "Actual", "Expected", "Deviation" ) ) + + benford( fibs.take(1000) ).toList.sorted foreach { + case (k, v) => println( "%d: %5.2f%% | %5.2f%% | %5.4f%%".format(k,v._2*100,v._1*100,math.abs(v._2-v._1)*100) ) + } +} diff --git a/Task/Benfords-law/Tcl/benfords-law-1.tcl b/Task/Benfords-law/Tcl/benfords-law-1.tcl new file mode 100644 index 0000000000..423b6099ed --- /dev/null +++ b/Task/Benfords-law/Tcl/benfords-law-1.tcl @@ -0,0 +1,19 @@ +proc benfordTest {numbers} { + # Count the leading digits (RE matches first digit in each number, + # even if negative) + set accum {1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0} + foreach n $numbers { + if {[regexp {[1-9]} $n digit]} { + dict incr accum $digit + } + } + + # Print the report + puts " digit | measured | theory" + puts "-------+----------+--------" + dict for {digit count} $accum { + puts [format "%6d | %7.2f%% | %5.2f%%" $digit \ + [expr {$count * 100.0 / [llength $numbers]}] \ + [expr {log(1+1./$digit)/log(10)*100.0}]] + } +} diff --git a/Task/Benfords-law/Tcl/benfords-law-2.tcl b/Task/Benfords-law/Tcl/benfords-law-2.tcl new file mode 100644 index 0000000000..a257fc9efb --- /dev/null +++ b/Task/Benfords-law/Tcl/benfords-law-2.tcl @@ -0,0 +1,7 @@ +proc fibs n { + for {set a 1;set b [set i 0]} {$i < $n} {incr i} { + lappend result [set b [expr {$a + [set a $b]}]] + } + return $result +} +benfordTest [fibs 1000] diff --git a/Task/Bernoulli-numbers/00DESCRIPTION b/Task/Bernoulli-numbers/00DESCRIPTION new file mode 100644 index 0000000000..3f30f6a737 --- /dev/null +++ b/Task/Bernoulli-numbers/00DESCRIPTION @@ -0,0 +1,23 @@ +[[wp:Bernoulli number|Bernoulli numbers]] are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per the National Institute of Standards and Technology convention). The n'th Bernoulli number is expressed as '''B'''''n''. + +;Task +* show the Bernoulli numbers '''B'''0 through '''B'''60, suppressing all output of values which are equal to zero. (Other than '''B'''1, all odd Bernoulli numbers have a value of 0 (zero). +* express the numbers as fractions (most are improper fractions). +** fractions should be reduced. +** index each number in some way so that it can be discerned which number is being displayed. +** align the solidi (/) if used (extra credit). + +;An algorithm +The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from [[wp:Bernoulli_number#Algorithmic_description|wikipedia]] is as follows: + + '''for''' ''m'' '''from''' 0 '''by''' 1 '''to''' ''n'' '''do''' + ''A''[''m''] ← 1/(''m''+1) + '''for''' ''j'' '''from''' ''m'' '''by''' -1 '''to''' 1 '''do''' + ''A''[''j''-1] ← ''j''×(''A''[''j''-1] - ''A''[''j'']) + '''return''' ''A''[0] (which is ''B''''n'') + +;See also +* Sequence [http://oeis.org/A027641 A027641 Numerator of Bernoulli number B_n] on The On-Line Encyclopedia of Integer Sequences. +* Sequence [http://oeis.org/A027642 A027642 Denominator of Bernoulli number B_n] on The On-Line Encyclopedia of Integer Sequences. +* Entry [http://mathworld.wolfram.com/BernoulliNumber.html Bernoulli number] on The Eric Weisstein's World of Mathematics (TM). +* Luschny's [http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html The Bernoulli Manifesto] for a discussion on B_1 = -½ vs. +½. diff --git a/Task/Bernoulli-numbers/00META.yaml b/Task/Bernoulli-numbers/00META.yaml new file mode 100644 index 0000000000..aed8ff126a --- /dev/null +++ b/Task/Bernoulli-numbers/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Mathematics diff --git a/Task/Bernoulli-numbers/C/bernoulli-numbers.c b/Task/Bernoulli-numbers/C/bernoulli-numbers.c new file mode 100644 index 0000000000..1ebe42e19b --- /dev/null +++ b/Task/Bernoulli-numbers/C/bernoulli-numbers.c @@ -0,0 +1,51 @@ +#include +#include + +#define mpq_for(buf, op, n)\ + do {\ + size_t i;\ + for (i = 0; i < (n); ++i)\ + mpq_##op(buf[i]);\ + } while (0) + +void bernoulli(mpq_t rop, unsigned int n) +{ + unsigned int m, j; + mpq_t *a = malloc(sizeof(mpq_t) * (n + 1)); + mpq_for(a, init, n + 1); + + for (m = 0; m <= n; ++m) { + mpq_set_ui(a[m], 1, m + 1); + for (j = m; j > 0; --j) { + mpq_sub(a[j-1], a[j], a[j-1]); + mpq_set_ui(rop, j, 1); + mpq_mul(a[j-1], a[j-1], rop); + } + } + + mpq_set(rop, a[0]); + mpq_for(a, clear, n + 1); + free(a); +} + +int main(void) +{ + mpq_t rop; + mpz_t n, d; + mpq_init(rop); + mpz_inits(n, d, NULL); + + unsigned int i; + for (i = 0; i <= 60; ++i) { + bernoulli(rop, i); + if (mpq_cmp_ui(rop, 0, 1)) { + mpq_get_num(n, rop); + mpq_get_den(d, rop); + gmp_printf("B(%-2u) = %44Zd / %Zd\n", i, n, d); + } + } + + mpz_clears(n, d, NULL); + mpq_clear(rop); + return 0; +} diff --git a/Task/Bernoulli-numbers/Common-Lisp/bernoulli-numbers.lisp b/Task/Bernoulli-numbers/Common-Lisp/bernoulli-numbers.lisp new file mode 100644 index 0000000000..ae2b406728 --- /dev/null +++ b/Task/Bernoulli-numbers/Common-Lisp/bernoulli-numbers.lisp @@ -0,0 +1,43 @@ +(defun bernouilli (n) + (loop with a = (make-array (list (1+ n))) + for m from 0 to n do + (setf (aref a m) (/ 1 (+ m 1))) + (loop for j from m downto 1 do + (setf (aref a (- j 1)) + (* j (- (aref a j) (aref a (- j 1)))))) + finally (return (aref a 0)))) + +;;Print outputs to stdout: + +(loop for n from 0 to 60 do + (let ((b (bernouilli n))) + (when (not (zerop b)) + (format t "~a: ~a~%" n b)))) + + +;;For the "extra credit" challenge, we need to align the slashes. + +(let (results) + ;;collect the results + (loop for n from 0 to 60 do + (let ((b (bernouilli n))) + (when (not (zerop b)) (push (cons b n) results)))) + ;;parse the numerators into strings; save the greatest length in max-length + (let ((max-length (apply #'max (mapcar (lambda (r) + (length (format nil "~a" (numerator r)))) + (mapcar #'car results))))) + ;;Print the numbers with using the fixed-width formatter: ~Nd, where N is + ;;the number of leading spaces. We can't just pass in the width variable + ;;but we can splice together a formatting string that includes it. + + ;;We also can't use the fixed-width formatter on a ratio, so we have to split + ;;the ratio and splice it back together like idiots. + (loop for n in (mapcar #'cdr (reverse results)) + for r in (mapcar #'car (reverse results)) do + (format t (concatenate 'string + "B(~2d): ~" + (format nil "~a" max-length) + "d/~a~%") + n + (numerator r) + (denominator r))))) diff --git a/Task/Bernoulli-numbers/D/bernoulli-numbers.d b/Task/Bernoulli-numbers/D/bernoulli-numbers.d new file mode 100644 index 0000000000..8ccded852d --- /dev/null +++ b/Task/Bernoulli-numbers/D/bernoulli-numbers.d @@ -0,0 +1,18 @@ +import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational; + +auto bernoulli(in uint n) pure nothrow /*@safe*/ { + auto A = new Rational[n + 1]; + foreach (immutable m; 0 .. n + 1) { + A[m] = Rational(1, m + 1); + foreach_reverse (immutable j; 1 .. m + 1) + A[j - 1] = j * (A[j - 1] - A[j]); + } + return A[0]; +} + +void main() { + immutable berns = 61.iota.map!bernoulli.enumerate.filter!(t => t[1]).array; + immutable width = berns.map!(b => b[1].numerator.text.length).reduce!max; + foreach (immutable b; berns) + writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof); +} diff --git a/Task/Bernoulli-numbers/Go/bernoulli-numbers.go b/Task/Bernoulli-numbers/Go/bernoulli-numbers.go new file mode 100644 index 0000000000..c7497d868a --- /dev/null +++ b/Task/Bernoulli-numbers/Go/bernoulli-numbers.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "math/big" + "strings" +) + +func b(n int) *big.Rat { + var f big.Rat + a := make([]big.Rat, n+1) + for m := range a { + a[m].SetFrac64(1, int64(m+1)) + for j := m; j >= 1; j-- { + d := &a[j-1] + d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j])) + } + } + return f.Set(&a[0]) +} + +func align(b *big.Rat, w int) string { + s := b.String() + return strings.Repeat(" ", w-strings.Index(s, "/")) + s +} + +func main() { + for n := 0; n <= 60; n++ { + if b := b(n); b.Num().BitLen() > 0 { + fmt.Printf("B(%2d) =%s\n", n, align(b, 45)) + } + } +} diff --git a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs new file mode 100644 index 0000000000..a5f7b2ae56 --- /dev/null +++ b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs @@ -0,0 +1,17 @@ +module Main where + +import Data.Ratio +import System.Environment + +main = getArgs >>= printM . defaultArg where + defaultArg as = if null as then 60 else read (head as) + +printM m = mapM_ (putStrLn . printP) . takeWhile ((<= m).fst) + . filter (\(_,b) -> b /= 0%1) . zip [0..] $ bernoullis + +printP (i,r) = "B(" ++ show i ++ ")=" ++ show (numerator r) ++ "/" ++ show (denominator r) + +bernoullis = map head . iterate (ulli 1) . map berno $ enumFrom 0 where + berno i = 1 % (i+1) + ulli _ [_] = [] + ulli i (x:y:xs) = (i%1)*(x-y) : ulli (i+1) (y:xs) diff --git a/Task/Bernoulli-numbers/Icon/bernoulli-numbers.icon b/Task/Bernoulli-numbers/Icon/bernoulli-numbers.icon new file mode 100644 index 0000000000..d6e5fe9ed5 --- /dev/null +++ b/Task/Bernoulli-numbers/Icon/bernoulli-numbers.icon @@ -0,0 +1,20 @@ +link "rational" + +procedure main(args) + limit := integer(!args) | 60 + every b := bernoulli(i := 0 to limit) do + if b.numer > 0 then write(right(i,3),": ",align(rat2str(b),60)) +end + +procedure bernoulli(n) + (A := table(0))[0] := rational(1,1,1) + every m := 1 to n do { + A[m] := rational(1,m+1,1) + every j := m to 1 by -1 do A[j-1] := mpyrat(rational(j,1,1), subrat(A[j-1],A[j])) + } + return A[0] +end + +procedure align(r,n) + return repl(" ",n-find("/",r))||r +end diff --git a/Task/Bernoulli-numbers/J/bernoulli-numbers-1.j b/Task/Bernoulli-numbers/J/bernoulli-numbers-1.j new file mode 100644 index 0000000000..8dc9052f02 --- /dev/null +++ b/Task/Bernoulli-numbers/J/bernoulli-numbers-1.j @@ -0,0 +1,3 @@ +B=:3 :0"0 + +/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y +) diff --git a/Task/Bernoulli-numbers/J/bernoulli-numbers-2.j b/Task/Bernoulli-numbers/J/bernoulli-numbers-2.j new file mode 100644 index 0000000000..1d9bdb7707 --- /dev/null +++ b/Task/Bernoulli-numbers/J/bernoulli-numbers-2.j @@ -0,0 +1,34 @@ + require'strings' + 'B',.rplc&'r/_-'"1": (#~ 0 ~: {:"1)(,.B) i.61 +B 0 1 +B 1 1/2 +B 2 1/6 +B 4 -1/30 +B 6 1/42 +B 8 -1/30 +B10 5/66 +B12 -691/2730 +B14 7/6 +B16 -3617/510 +B18 43867/798 +B20 -174611/330 +B22 854513/138 +B24 -236364091/2730 +B26 8553103/6 +B28 -23749461029/870 +B30 8615841276005/14322 +B32 -7709321041217/510 +B34 2577687858367/6 +B36 -26315271553053477373/1919190 +B38 2929993913841559/6 +B40 -261082718496449122051/13530 +B42 1520097643918070802691/1806 +B44 -27833269579301024235023/690 +B46 596451111593912163277961/282 +B48 -5609403368997817686249127547/46410 +B50 495057205241079648212477525/66 +B52 -801165718135489957347924991853/1590 +B54 29149963634884862421418123812691/798 +B56 -2479392929313226753685415739663229/870 +B58 84483613348880041862046775994036021/354 +B60 -1215233140483755572040304994079820246041491/56786730 diff --git a/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple b/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple new file mode 100644 index 0000000000..7ddf77c3ec --- /dev/null +++ b/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple @@ -0,0 +1,11 @@ +k:=length(numer(bernoulli(60))): + +G := proc(n) local b,i; + b := `if`(n=1/2,1/2,bernoulli(2*n)); + printf("%a%s%a\n",'B'[2*n], + cat(" "$i=1..(5+k-length(numer(b)) + +(1+signum(b))/2)-length(2*n)),b); + NULL; + end proc: + +G(0), G(1/2), seq(G(i),i=1..30); diff --git a/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-1.math b/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-1.math new file mode 100644 index 0000000000..f08fb4b01b --- /dev/null +++ b/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-1.math @@ -0,0 +1,11 @@ +bernoulli[n_] := Module[{a = ConstantArray[0, n + 2]}, + Do[ + a[[m]] = 1/m; + If[m == 1 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; + Do[ + a[[j - 1]] = (j - 1)*(a[[j - 1]] - a[[j]]); + If[j == 2 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; + , {j, m, 2, -1}]; + , {m, 1, n + 1}]; + ] +bernoulli[60] diff --git a/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-2.math b/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-2.math new file mode 100644 index 0000000000..f70329cdca --- /dev/null +++ b/Task/Bernoulli-numbers/Mathematica/bernoulli-numbers-2.math @@ -0,0 +1,2 @@ +Table[{i, BernoulliB[i]}, {i, 0, 60}]; +Select[%, #[[2]] != 0 &] // TableForm diff --git a/Task/Bernoulli-numbers/PARI-GP/bernoulli-numbers.pari b/Task/Bernoulli-numbers/PARI-GP/bernoulli-numbers.pari new file mode 100644 index 0000000000..633c3b506b --- /dev/null +++ b/Task/Bernoulli-numbers/PARI-GP/bernoulli-numbers.pari @@ -0,0 +1 @@ +for(n=0,60,t=bernfrac(n);if(t,print(n" "t))) diff --git a/Task/Bernoulli-numbers/PL-I/bernoulli-numbers.pli b/Task/Bernoulli-numbers/PL-I/bernoulli-numbers.pli new file mode 100644 index 0000000000..57fdffe015 --- /dev/null +++ b/Task/Bernoulli-numbers/PL-I/bernoulli-numbers.pli @@ -0,0 +1,33 @@ +Bern: procedure options (main); /* 4 July 2014 */ + declare i fixed binary; + declare B complex fixed (31); + +Bernoulli: procedure (n) returns (complex fixed (31)); + declare n fixed binary; + declare anum(0:n) fixed (31), aden(0:n) fixed (31); + declare (j, m) fixed; + declare F fixed (31); + + do m = 0 to n; + anum(m) = 1; + aden(m) = m+1; + do j = m to 1 by -1; + anum(j-1) = j*( aden(j)*anum(j-1) - aden(j-1)*anum(j) ); + aden(j-1) = ( aden(j-1) * aden(j) ); + F = gcd(abs(anum(j-1)), abs(aden(j-1)) ); + if F ^= 1 then + do; + anum(j-1) = anum(j-1) / F; + aden(j-1) = aden(j-1) / F; + end; + end; + end; + return ( complex(anum(0), aden(0)) ); +end Bernoulli; + + do i = 0, 1, 2 to 36 by 2; /* 36 is upper limit imposed by hardware. */ + B = Bernoulli(i); + put skip edit ('B(' , trim(i) , ')=' , real(B) , '/' , trim(imag(B)) ) + (3 A, column(10), F(32), 2 A); + end; +end Bern; diff --git a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-1.pl6 b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-1.pl6 new file mode 100644 index 0000000000..2274542255 --- /dev/null +++ b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-1.pl6 @@ -0,0 +1,17 @@ +sub bernoulli($n) { + my @a; + for 0..$n -> $m { + @a[$m] = FatRat.new(1, $m + 1); + for reverse 1..$m -> $j { + @a[$j - 1] = $j * (@a[$j - 1] - @a[$j]); + } + } + return @a[0]; +} + +constant @bpairs = grep *.value.so, ($_ => bernoulli($_) for 0..60); + +my $width = [max] @bpairs.map: *.value.numerator.chars; +my $form = "B(%2d) = \%{$width}d/%d\n"; + +printf $form, .key, .value.nude for @bpairs; diff --git a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-2.pl6 b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-2.pl6 new file mode 100644 index 0000000000..b837245e8c --- /dev/null +++ b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-2.pl6 @@ -0,0 +1,18 @@ +constant bernoulli = gather { + my @a; + for 0..* -> $m { + @a = FatRat.new(1, $m + 1), + -> $prev { + my $j = @a.elems; + $j * (@a.shift - $prev); + } ... { not @a.elems } + take $m => @a[*-1] if @a[*-1]; + } +} + +constant @bpairs = bernoulli[^52]; + +my $width = [max] @bpairs.map: *.value.numerator.chars; +my $form = "B(%d)\t= \%{$width}d/%d\n"; + +printf $form, .key, .value.nude for @bpairs; diff --git a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 new file mode 100644 index 0000000000..55223d6e18 --- /dev/null +++ b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 @@ -0,0 +1,7 @@ +my sub infix:(\prev,\this) { this.key => this.key * (this.value - prev.value) } + +constant bernoulli = grep *.value, map { (.key => .value.[*-1]) }, do + 0 => [FatRat.new(1,1)], + -> (:key($pm),:value(@pa)) { + $pm + 1 => [ map *.value, [\bop] ($pm + 2 ... 1) Z=> FatRat.new(1, $pm + 2), @pa ]; + } ... *; diff --git a/Task/Bernoulli-numbers/Perl/bernoulli-numbers-1.pl b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-1.pl new file mode 100644 index 0000000000..a747e87734 --- /dev/null +++ b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-1.pl @@ -0,0 +1,24 @@ +#!perl +use strict; +use warnings; +use List::Util qw(max); +use Math::BigRat; + +my $one = Math::BigRat->new(1); +sub bernoulli_print { + my @a; + for my $m ( 0 .. 60 ) { + push @a, $one / ($m + 1); + for my $j ( reverse 1 .. $m ) { + # This line: + ( $a[$j-1] -= $a[$j] ) *= $j; + # is a faster version of the following line: + # $a[$j-1] = $j * ($a[$j-1] - $a[$j]); + # since it avoids unnecessary object creation. + } + next unless $a[0]; + printf "B(%2d) = %44s/%s\n", $m, $a[0]->parts; + } +} + +bernoulli_print(); diff --git a/Task/Bernoulli-numbers/Perl/bernoulli-numbers-2.pl b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-2.pl new file mode 100644 index 0000000000..598973caeb --- /dev/null +++ b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-2.pl @@ -0,0 +1,6 @@ +use ntheory qw/bernfrac/; + +for my $n (0 .. 60) { + my($num,$den) = bernfrac($n); + printf "B(%2d) = %44s/%s\n", $n, $num, $den if $num != 0; +} diff --git a/Task/Bernoulli-numbers/Perl/bernoulli-numbers-3.pl b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-3.pl new file mode 100644 index 0000000000..a47b6341b2 --- /dev/null +++ b/Task/Bernoulli-numbers/Perl/bernoulli-numbers-3.pl @@ -0,0 +1,6 @@ +use Math::Pari qw/bernfrac/; + +for my $n (0 .. 60) { + my($num,$den) = split "/", bernfrac($n); + printf("B(%2d) = %44s/%s\n", $n, $num, $den||1) if $num != 0; +} diff --git a/Task/Bernoulli-numbers/PicoLisp/bernoulli-numbers.l b/Task/Bernoulli-numbers/PicoLisp/bernoulli-numbers.l new file mode 100644 index 0000000000..0ca6607515 --- /dev/null +++ b/Task/Bernoulli-numbers/PicoLisp/bernoulli-numbers.l @@ -0,0 +1,74 @@ +(load "@lib/frac.l") + +(de fact (N) + (cache '(NIL) N + (if (=0 N) 1 (apply * (range 1 N))) ) ) + +(de binomial (N K) + (frac + (/ + (fact N) + (* (fact (- N K)) (fact K)) ) + 1 ) ) + +(de A (N M) + (let Sum (0 . 1) + (for X M + (setq Sum + (f+ + Sum + (f* + (binomial (+ N 3) (- N (* X 6))) + (berno (- N (* X 6)) ) ) ) ) ) + Sum ) ) + +(de berno (N) + (cache '(NIL) N + (cond + ((=0 N) (1 . 1)) + ((= 1 N) (-1 . 2)) + ((bit? 1 N) (0 . 1)) + (T + (case (% N 6) + (0 + (f/ + (f- + (frac (+ N 3) 3) + (A N (/ N 6)) ) + (binomial (+ N 3) N) ) ) + (2 + (f/ + (f- + (frac (+ N 3) 3) + (A N (/ (- N 2) 6)) ) + (binomial (+ N 3) N) ) ) + (4 + (f/ + (f- + (f* (-1 . 1) (frac (+ N 3) 6)) + (A N (/ (- N 4) 6)) ) + (binomial (+ N 3) N) ) ) ) ) ) ) ) + +(de berno-brute (N) + (cache '(NIL) N + (let Sum (0 . 1) + (cond + ((=0 N) (1 . 1)) + ((= 1 N) (-1 . 2)) + ((bit? 1 N) (0 . 1)) + (T + (for (X 0 (> N X) (inc X)) + (setq Sum + (f+ + Sum + (f* (binomial (inc N) X) (berno-brute X)) ) ) ) + (f/ (f* (-1 . 1) Sum) (binomial (inc N) N)) ) ) ) ) ) + +(for (N 0 (> 62 N) (inc N)) + (if (or (= N 1) (not (bit? 1 N))) + (tab (2 4 -60) N " => " (sym (berno N))) ) ) + +(for (N 0 (> 400 N) (inc N)) + (test (berno N) (berno-brute N)) ) + +(bye) diff --git a/Task/Bernoulli-numbers/Python/bernoulli-numbers-1.py b/Task/Bernoulli-numbers/Python/bernoulli-numbers-1.py new file mode 100644 index 0000000000..b2ca22b772 --- /dev/null +++ b/Task/Bernoulli-numbers/Python/bernoulli-numbers-1.py @@ -0,0 +1,15 @@ +from fractions import Fraction as Fr + +def bernoulli(n): + A = [0] * (n+1) + for m in range(n+1): + A[m] = Fr(1, m+1) + for j in range(m, 0, -1): + A[j-1] = j*(A[j-1] - A[j]) + return A[0] # (which is Bn) + +bn = [(i, bernoulli(i)) for i in range(61)] +bn = [(i, b) for i,b in bn if b] +width = max(len(str(b.numerator)) for i,b in bn) +for i,b in bn: + print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator)) diff --git a/Task/Bernoulli-numbers/Python/bernoulli-numbers-2.py b/Task/Bernoulli-numbers/Python/bernoulli-numbers-2.py new file mode 100644 index 0000000000..bcb81b7ebb --- /dev/null +++ b/Task/Bernoulli-numbers/Python/bernoulli-numbers-2.py @@ -0,0 +1,14 @@ +def bernoulli2(): + A, m = [], 0 + while True: + A.append(Fr(1, m+1)) + for j in range(m, 0, -1): + A[j-1] = j*(A[j-1] - A[j]) + yield A[0] # (which is Bm) + m += 1 + +bn2 = [ix for ix in zip(range(61), bernoulli2())] +bn2 = [(i, b) for i,b in bn2 if b] +width = max(len(str(b.numerator)) for i,b in bn2) +for i,b in bn2: + print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator)) diff --git a/Task/Bernoulli-numbers/README b/Task/Bernoulli-numbers/README new file mode 100644 index 0000000000..da3400eb4b --- /dev/null +++ b/Task/Bernoulli-numbers/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Bernoulli_numbers diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx new file mode 100644 index 0000000000..4e70243af7 --- /dev/null +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -0,0 +1,53 @@ +/*REXX program calculates a number of Bernoulli numbers (as fractions). */ +parse arg N .; if N=='' then N=60 /*get N. If ¬ given, use default*/ +!.=0; w=max(length(N),4); Nw=N+N%5 /*used for aligning the output. */ +say 'B(n)' center('Bernoulli number expressed as a fraction', max(78-w,Nw)) +say copies('─',w) copies('─', max(78-w,Nw+2*w)) + do #=0 to N /*process numbers from 0 ──► N. */ + b=bern(#); if b==0 then iterate /*calculate Bernoulli#, skip if 0*/ + indent=max(0, nW-pos('/', b)) /*calculate alignment indentation*/ + say right(#,w) left('',indent) b /*display the indented Bernoulli#*/ + end /*#*/ /* [↑] align the Bernoulli number*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────BERN subroutine─────────────────────*/ +bern: parse arg x /*obtain the subroutine argument.*/ +if x==0 then return '1/1' /*handle the special case of zero*/ +if x==1 then return '-1/2' /* " " " " " one.*/ +if x//2 then return 0 /* " " " " " odds*/ + /* [↓] process all #s up to X, */ + do j=2 to x by 2; jp=j+1; d=j+j /* & set some shortcut vars.*/ + if d>digits() then numeric digits d /*increase precision if needed. */ + sn=1-j /*set the numerator. */ + sd=2 /* " " denominator. */ + do k=2 to j-1 by 2 /*calculate a SN/SD sequence. */ + parse var @.k bn '/' ad /*get a previously calculated fra*/ + an=comb(jp,k)*bn /*use COMBination for next term. */ + lcm=lcm.(sd,ad) /*use Least Common Denominator. */ + sn=lcm%sd*sn; sd=lcm /*calculate current numerator. */ + an=lcm%ad*an; ad=lcm /* " next " */ + sn=sn+an /* " current " */ + end /*k*/ /* [↑] calculate SN/SD sequence.*/ + sn=-sn /*adjust the sign for numerator. */ + sd=sd*jp /*calculate the denominitator. */ + if sn\==1 then do /*reduce the fraction if possible*/ + _=gcd.(sn,sd) /*get Greatest Common Denominator*/ + sn=sn%_; sd=sd%_ /*reduce numerator & denominator.*/ + end /* [↑] done with the reduction.*/ + @.j=sn'/'sd /*save the result for next round.*/ + end /*j*/ /* [↑] done with calculating B#.*/ + +return sn'/'sd +/*──────────────────────────────────COMB subroutine─────────────────────*/ +comb: procedure expose !.; parse arg x,y; if x==y then return 1 +if !.!c.x.y\==0 then return !.!c.x.y /*combination computed before ? */ + if x-y values] + [else (define k! (* k (! (- k 1)))) (vector-set! !-memo k k!) k!])) +(define (kCr k r) + ; If we want (kCr ... r>1000000) we'll have to reconsider this. However, until then... + (define hash-key (+ (* 1000000 k) r)) + (hash-ref! kCr-memo hash-key (λ () (/ (! k) (! r) (! (- k r)))))) + +(define (bernoulli.3 n) + (for/sum ((k (in-range 0 (add1 n)))) + (define k+1 (add1 k)) + (* (/ k+1) + (- (for/sum ((r (in-range 0 k+1 2))) (* (kCr k r) (expt r n))) + (for/sum ((r (in-range 1 k+1 2))) (* (kCr k r) (expt r n))))))) + +(define (display/align-fractions caption/idx-fmt Bs) + ;; widths are one more than the order of magnitude + (define oom+1 (compose add1 order-of-magnitude)) + (define-values (I-width N-width D-width) + (for/fold ((I 0) (N 0) (D 0)) + ((b Bs) (n (non-zero-bernoulli-indices (in-naturals)))) + (define +b (abs b)) + (values (max I (oom+1 (max n 1))) + (max N (+ (oom+1 (numerator +b)) (if (negative? b) 1 0))) + (max D (oom+1 (denominator +b)))))) + (define (~a/w/a n w a) (~a n #:width w #:align a)) + (for ((n (non-zero-bernoulli-indices (in-naturals))) (b Bs)) + (printf "~a ~a/~a~%" + (format caption/idx-fmt (~a/w/a n I-width 'right)) + (~a/w/a (numerator b) N-width 'right) + (~a/w/a (denominator b) D-width 'left)))) + +(module+ main + (display/align-fractions "B(~a) =" (bernoulli_0..n bernoulli.3 60))) + +(module+ test + (require rackunit) + ; correctness and timing tests + (check-match (time (bernoulli_0..n bernoulli.1 60)) + (list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...)) + (check-match (time (bernoulli_0..n bernoulli.2 60)) + (list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...)) + (check-match (time (bernoulli_0..n bernoulli.3 60)) + (list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...)) + ; timing only ... + (void (time (bernoulli_0..n bernoulli.3 100)))) diff --git a/Task/Bernoulli-numbers/Ruby/bernoulli-numbers.rb b/Task/Bernoulli-numbers/Ruby/bernoulli-numbers.rb new file mode 100644 index 0000000000..5acdeb3de6 --- /dev/null +++ b/Task/Bernoulli-numbers/Ruby/bernoulli-numbers.rb @@ -0,0 +1,13 @@ +bernoulli = Enumerator.new do |y| + ar, m = [], 0 + loop do + ar << Rational(1, m+1) + m.downto(1){|j| ar[j-1] = j*(ar[j-1] - ar[j]) } + y << ar.first # yield + m += 1 + end +end + +b_nums = bernoulli.take(61) +width = b_nums.map{|b| b.numerator.to_s.size}.max +b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } diff --git a/Task/Bernoulli-numbers/Tcl/bernoulli-numbers.tcl b/Task/Bernoulli-numbers/Tcl/bernoulli-numbers.tcl new file mode 100644 index 0000000000..5a25d6000b --- /dev/null +++ b/Task/Bernoulli-numbers/Tcl/bernoulli-numbers.tcl @@ -0,0 +1,26 @@ +proc bernoulli {n} { + for {set m 0} {$m <= $n} {incr m} { + lappend A [list 1 [expr {$m + 1}]] + for {set j $m} {[set i $j] >= 1} {} { + lassign [lindex $A [incr j -1]] a1 b1 + lassign [lindex $A $i] a2 b2 + set x [set p [expr {$i * ($a1*$b2 - $a2*$b1)}]] + set y [set q [expr {$b1 * $b2}]] + while {$q} {set q [expr {$p % [set p $q]}]} + lset A $j [list [expr {$x/$p}] [expr {$y/$p}]] + } + } + return [lindex $A 0] +} + +set len 0 +for {set n 0} {$n <= 60} {incr n} { + set b [bernoulli $n] + if {[lindex $b 0]} { + lappend result $n {*}$b + set len [expr {max($len, [string length [lindex $b 0]])}] + } +} +foreach {n num denom} $result { + puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom] +} diff --git a/Task/Bitcoin-public-point-to-address/00DESCRIPTION b/Task/Bitcoin-public-point-to-address/00DESCRIPTION new file mode 100644 index 0000000000..015a33cf71 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/00DESCRIPTION @@ -0,0 +1,22 @@ +[[wp:Bitcoin|Bitcoin]] uses a specific encoding format to encode the digest of an [[wp:elliptic curve|elliptic curve]] public point into a short ASCII string. The purpose of this task is to perform such a conversion. + +The encoding steps are: +* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ; +* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ; +* compute the [[SHA-256]] of this string ; +* compute the [[RIPEMD-160]] of this SHA-256 digest ; +* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ; +* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum + +The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I. + +Here is an example public point: +
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
+Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
+ +The corresponding address should be: +16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM + +Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1. + +''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve diff --git a/Task/Bitcoin-public-point-to-address/C/bitcoin-public-point-to-address.c b/Task/Bitcoin-public-point-to-address/C/bitcoin-public-point-to-address.c new file mode 100644 index 0000000000..3dd45c585e --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/C/bitcoin-public-point-to-address.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include + +#define COIN_VER 0 +const char *coin_err; + +typedef unsigned char byte; + +int is_hex(const char *s) { + int i; + for (i = 0; i < 64; i++) + if (!isxdigit(s[i])) return 0; + return 1; +} + +void str_to_byte(const char *src, byte *dst, int n) { + while (n--) sscanf(src + n * 2, "%2hhx", dst + n); +} + +char* base58(byte *s, char *out) { + static const char *tmpl = "123456789" + "ABCDEFGHJKLMNPQRSTUVWXYZ" + "abcdefghijkmnopqrstuvwxyz"; + static char buf[40]; + + int c, i, n; + if (!out) out = buf; + + out[n = 34] = 0; + while (n--) { + for (c = i = 0; i < 25; i++) { + c = c * 256 + s[i]; + s[i] = c / 58; + c %= 58; + } + out[n] = tmpl[c]; + } + + for (n = 0; out[n] == '1'; n++); + memmove(out, out + n, 34 - n); + + return out; +} + +char *coin_encode(const char *x, const char *y, char *out) { + byte s[65]; + byte rmd[5 + RIPEMD160_DIGEST_LENGTH]; + + if (!is_hex(x) || !(is_hex(y))) { + coin_err = "bad public point string"; + return 0; + } + + s[0] = 4; + str_to_byte(x, s + 1, 32); + str_to_byte(y, s + 33, 32); + + rmd[0] = COIN_VER; + RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1); + + memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4); + + return base58(rmd, out); +} + +int main(void) { + puts(coin_encode( + "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", + "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6", + 0)); + return 0; +} diff --git a/Task/Bitcoin-public-point-to-address/D/bitcoin-public-point-to-address.d b/Task/Bitcoin-public-point-to-address/D/bitcoin-public-point-to-address.d new file mode 100644 index 0000000000..6bef17fa8e --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/D/bitcoin-public-point-to-address.d @@ -0,0 +1,58 @@ +import std.stdio, std.algorithm, std.digest.ripemd, sha_256_2; + +// A Bitcoin public point. +struct PPoint { ubyte[32] x, y; } + +private enum bitcoinVersion = 0; +private enum RIPEMD160_digest_len = typeof("".ripemd160Of).length; +private alias sha = SHA256.digest; +alias Address = ubyte[1 + 4 + RIPEMD160_digest_len]; + + +/// Returns a base 58 encoded bitcoin address corresponding to the receiver. +char[] toBase58(ref Address a) pure nothrow @safe { + static immutable symbols = "123456789" ~ + "ABCDEFGHJKLMNPQRSTUVWXYZ" ~ + "abcdefghijkmnopqrstuvwxyz"; + static assert(symbols.length == 58); + + auto result = new typeof(return)(34); + foreach_reverse (ref ri; result) { + uint c = 0; + foreach (ref ai; a) { + immutable d = (c % symbols.length) * 256 + ai; + ai = d / symbols.length; + c = d; + } + ri = symbols[c % symbols.length]; + } + + size_t i = 1; + for (; i < result.length && result[i] == '1'; i++) {} + return result[i - 1 .. $]; +} + + +char[] bitcoinEncode(in ref PPoint p) pure nothrow { + ubyte[typeof(PPoint.x).length + typeof(PPoint.y).length + 1] s; + s[0] = 4; + s[1 .. 1 + p.x.length] = p.x[]; + s[1 + p.x.length .. $] = p.y[]; + + Address rmd; + rmd[0] = bitcoinVersion; + rmd[1 .. RIPEMD160_digest_len + 1] = s.sha.ripemd160Of; + rmd[$-4 .. $] = rmd[0 .. RIPEMD160_digest_len + 1].sha.sha[0 .. 4]; + return rmd.toBase58; +} + + +void main() { + PPoint p = { +cast(typeof(PPoint.x)) +x"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", +cast(typeof(PPoint.y)) +x"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"}; + + p.bitcoinEncode.writeln; +} diff --git a/Task/Bitcoin-public-point-to-address/Go/bitcoin-public-point-to-address.go b/Task/Bitcoin-public-point-to-address/Go/bitcoin-public-point-to-address.go new file mode 100644 index 0000000000..4944558a16 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Go/bitcoin-public-point-to-address.go @@ -0,0 +1,101 @@ +package main + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + + "golang.org/x/crypto/ripemd160" +) + +// Point is a type for a bitcoin public point. +type Point struct { + x, y [32]byte +} + +// SetHex takes two hexidecimal strings and decodes them into the receiver. +func (p *Point) SetHex(x, y string) error { + if len(x) != 64 || len(y) != 64 { + return errors.New("invalid hex string length") + } + if _, err := hex.Decode(p.x[:], []byte(x)); err != nil { + return err + } + _, err := hex.Decode(p.y[:], []byte(y)) + return err +} + +// A25 type in common with Bitcoin/address validation task. +type A25 [25]byte + +// doubleSHA256 method in common with Bitcoin/address validation task. +func (a *A25) doubleSHA256() []byte { + h := sha256.New() + h.Write(a[:21]) + d := h.Sum([]byte{}) + h = sha256.New() + h.Write(d) + return h.Sum(d[:0]) +} + +// UpdateChecksum computes the address checksum on the first 21 bytes and +// stores the result in the last 4 bytes. +func (a *A25) UpdateChecksum() { + copy(a[21:], a.doubleSHA256()) +} + +// SetPoint takes a public point and generates the corresponding address +// into the receiver, complete with valid checksum. +func (a *A25) SetPoint(p *Point) { + c := [65]byte{4} + copy(c[1:], p.x[:]) + copy(c[33:], p.y[:]) + h := sha256.New() + h.Write(c[:]) + s := h.Sum([]byte{}) + h = ripemd160.New() + h.Write(s) + h.Sum(a[1:1]) + a.UpdateChecksum() +} + +// Tmpl in common with Bitcoin/address validation task. +var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + +// A58 returns a base58 encoded bitcoin address corresponding to the receiver. +// Code adapted from the C solution to this task. +func (a *A25) A58() []byte { + var out [34]byte + for n := 33; n >= 0; n-- { + c := 0 + for i := 0; i < 25; i++ { + c = c*256 + int(a[i]) + a[i] = byte(c / 58) + c %= 58 + } + out[n] = tmpl[c] + } + i := 1 + for i < 34 && out[i] == '1' { + i++ + } + return out[i-1:] +} + +func main() { + // parse hex into point object + var p Point + err := p.SetHex( + "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", + "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6") + if err != nil { + fmt.Println(err) + return + } + // generate address object from point + var a A25 + a.SetPoint(&p) + // show base58 representation + fmt.Println(string(a.A58())) +} diff --git a/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 b/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 new file mode 100644 index 0000000000..fd221b9fdc --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 @@ -0,0 +1,26 @@ +use SSL::Digest; + +constant BASE58 = < + 1 2 3 4 5 6 7 8 9 + A B C D E F G H J K L M N P Q R S T U V W X Y Z + a b c d e f g h i j k m n o p q r s t u v w x y z +>; + +sub encode(Int $n) { + $n < BASE58 ?? + BASE58[$n] !! + encode($n div 58) ~ BASE58[$n % 58] +} + +sub public_point_to_address(Int $x is copy, Int $y is copy) { + my @bytes; + for 1 .. 32 { push @bytes, $y % 256; $y div= 256 } + for 1 .. 32 { push @bytes, $x % 256; $x div= 256 } + my $hash = rmd160 sha256 Blob.new: 4, @bytes.reverse; + my $checksum = sha256(sha256 Blob.new: 0, $hash.list).subbuf: 0, 4; + encode reduce * * 256 + * , 0, ($hash, $checksum)».list +} + +say public_point_to_address +0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352, +0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6; diff --git a/Task/Bitcoin-public-point-to-address/Perl/bitcoin-public-point-to-address.pl b/Task/Bitcoin-public-point-to-address/Perl/bitcoin-public-point-to-address.pl new file mode 100644 index 0000000000..eb38ecba5b --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Perl/bitcoin-public-point-to-address.pl @@ -0,0 +1,30 @@ +use bigint; +use Crypt::RIPEMD160; +use Digest::SHA qw(sha256); +my @b58 = qw{ + 1 2 3 4 5 6 7 8 9 + A B C D E F G H J K L M N P Q R S T U V W X Y Z + a b c d e f g h i j k m n o p q r s t u v w x y z +}; +my $b58 = qr/[@{[join '', @b58]}]/x; + +sub encode { my $_ = shift; $_ < 58 ? $b58[$_] : encode($_/58) . $b58[$_%58] } + +sub public_point_to_address { + my ($x, $y) = @_; + my @byte; + for (1 .. 32) { push @byte, $y % 256; $y /= 256 } + for (1 .. 32) { push @byte, $x % 256; $x /= 256 } + @byte = (4, reverse @byte); + my $hash = Crypt::RIPEMD160->hash(sha256 join '', map { chr } @byte); + my $checksum = substr sha256(sha256 chr(0).$hash), 0, 4; + my $value = 0; + for ( (chr(0).$hash.$checksum) =~ /./gs ) { $value = $value * 256 + ord } + (sprintf "%33s", encode $value) =~ y/ /1/r; +} + +print public_point_to_address map {hex "0x$_"} ; + +__DATA__ +50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 +2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6 diff --git a/Task/Bitcoin-public-point-to-address/README b/Task/Bitcoin-public-point-to-address/README new file mode 100644 index 0000000000..e6a405651b --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Bitcoin/public_point_to_address diff --git a/Task/Bitcoin-public-point-to-address/Racket/bitcoin-public-point-to-address.rkt b/Task/Bitcoin-public-point-to-address/Racket/bitcoin-public-point-to-address.rkt new file mode 100644 index 0000000000..75e15b880a --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Racket/bitcoin-public-point-to-address.rkt @@ -0,0 +1,120 @@ +#lang racket/base +(module sha256 racket/base + ;; define a quick SH256 FFI interface, similar to the Racket's default + ;; SHA1 interface (from [[SHA-256#Racket]]) + (provide sha256) + (require ffi/unsafe ffi/unsafe/define openssl/libcrypto) + (define-ffi-definer defcrypto libcrypto) + (defcrypto SHA256_Init (_fun _pointer -> _int)) + (defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) + (defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) + (define (sha256 bytes) + (define ctx (malloc 128)) + (define result (make-bytes 32)) + (SHA256_Init ctx) + (SHA256_Update ctx bytes (bytes-length bytes)) + (SHA256_Final result ctx) + ;; (bytes->hex-string result) -- not needed, we want bytes + result)) + +(require + ;; On windows I needed to "raco planet install soegaard digetst.plt 1 2" + (only-in (planet soegaard/digest:1:2/digest) ripemd160-bytes) + (submod "." sha256)) + +;; Quick utility +(define << arithmetic-shift) ; a bit shorter + +;; From: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses +;; Using Bitcoin's stage numbers: + +;; 1 - Take the corresponding public key generated with it +;; (65 bytes, 1 byte 0x04, 32 bytes corresponding to X coordinate, +;; 32 bytes corresponding to Y coordinate) +(define (stage-1 X Y) + (define (integer->bytes! i B) + (define l (bytes-length B)) + (for ((b (in-range 0 l))) (bytes-set! B (- l b 1) (bitwise-bit-field i (* b 8) (* (+ b 1) 8)))) B) + (integer->bytes! (+ (<< 4 (* 32 8 2)) (<< X (* 32 8)) Y) (make-bytes 65))) + +;; 2 - Perform SHA-256 hashing on the public key +(define stage-2 sha256) + +;; 3 - Perform RIPEMD-160 hashing on the result of SHA-256 +(define stage-3 ripemd160-bytes) + +;; 4 - Add version byte in front of RIPEMD-160 hash (0x00 for Main Network) +(define (stage-4 s3) + (bytes-append #"\0" s3)) + +;; 5 - Perform SHA-256 hash on the extended RIPEMD-160 result +;; 6 - Perform SHA-256 hash on the result of the previous SHA-256 hash +(define (stage-5+6 s4) + (values s4 (sha256 (sha256 s4)))) + +;; 7 - Take the first 4 bytes of the second SHA-256 hash. This is the address checksum +(define (stage-7 s4 s6) + (values s4 (subbytes s6 0 4))) + +;; 8 - Add the 4 checksum bytes from stage 7 at the end of extended RIPEMD-160 hash from stage 4. +;; This is the 25-byte binary Bitcoin Address. +(define (stage-8 s4 s7) + (bytes-append s4 s7)) + +;; 9 - Convert the result from a byte string into a base58 string using Base58Check encoding. +;; This is the most commonly used Bitcoin Address format +(define stage-9 (base58-encode 33)) + +(define ((base58-encode l) B) + (define b58 #"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + (define rv (make-bytes l (char->integer #\1))) ; already padded out with 1's + (define b-int (for/fold ((i 0)) ((b (in-bytes B))) (+ (<< i 8) b))) + (let loop ((b b-int) (l l)) + (if (zero? b) rv + (let-values (((q r) (quotient/remainder b 58))) + (define l- (- l 1)) + (bytes-set! rv l- (bytes-ref b58 r)) + (loop q l-))))) + +;; Takes two (rather large) ints for X and Y, returns base-58 PAP. +(define public-address-point + (compose stage-9 stage-8 stage-7 stage-5+6 stage-4 stage-3 stage-2 stage-1)) + +(public-address-point + #x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 + #x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +(module+ test + (require tests/eli-tester (only-in openssl/sha1 bytes->hex-string)) + (define bytes->HEX-STRING (compose string-upcase bytes->hex-string)) + (test + ((base58-encode 33) + (bytes-append #"\x00\x01\x09\x66\x77\x60\x06\x95\x3D\x55\x67\x43" + #"\x9E\x5E\x39\xF8\x6A\x0D\x27\x3B\xEE\xD6\x19\x67\xF6")) + => + #"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM") + + (define-values (test-X test-Y) + (values #x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 + #x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6)) + (define s1 (stage-1 test-X test-Y)) + (define s2 (stage-2 s1)) + (define s3 (stage-3 s2)) + (define s4 (stage-4 s3)) + (define-values (s4_1 s6) (stage-5+6 s4)) + (define-values (s4_2 s7) (stage-7 s4 s6)) + (define s8 (stage-8 s4 s7)) + (define s9 (stage-9 s8)) + + (test + (bytes->HEX-STRING s1) + => (string-append "0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453" + "A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6") + (bytes->HEX-STRING s2) => "600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408" + (bytes->HEX-STRING s3) => "010966776006953D5567439E5E39F86A0D273BEE" + (bytes->HEX-STRING s4) => "00010966776006953D5567439E5E39F86A0D273BEE" + (bytes->HEX-STRING s6) => "D61967F63C7DD183914A4AE452C9F6AD5D462CE3D277798075B107615C1A8A30" + (bytes->HEX-STRING s7) => "D61967F6" + (bytes->HEX-STRING s8) => "00010966776006953D5567439E5E39F86A0D273BEED61967F6" + s9 => #"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM")) diff --git a/Task/Bitcoin-public-point-to-address/Ruby/bitcoin-public-point-to-address.rb b/Task/Bitcoin-public-point-to-address/Ruby/bitcoin-public-point-to-address.rb new file mode 100644 index 0000000000..bdf53ad982 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Ruby/bitcoin-public-point-to-address.rb @@ -0,0 +1,21 @@ +# Translate public point to Bitcoin address +# +# Nigel_Galloway +# October 12th., 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 +X = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352' +Y = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' +n = '00'+Digest::RMD160.hexdigest(Digest::SHA256.digest(convert('04'+X+Y))) +n+= Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8] +G = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +n,res = n.hex,'' +while n > 0 do + n,ng = n.divmod(58) + res << G[ng] +end +puts res.reverse diff --git a/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-1.tcl b/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-1.tcl new file mode 100644 index 0000000000..8407f99591 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-1.tcl @@ -0,0 +1,29 @@ +package require ripemd160 +package require sha256 + +# Exactly the algorithm from https://en.bitcoin.it/wiki/Base58Check_encoding +proc base58encode data { + set digits "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + for {set zeroes 0} {[string index $data 0] eq "\x00"} {incr zeroes} { + set data [string range $data 1 end] + } + binary scan $data "H*" hex + scan $hex "%llx" num + for {set out ""} {$num > 0} {set num [expr {$num / 58}]} { + append out [string index $digits [expr {$num % 58}]] + } + append out [string repeat [string index $digits 0] $zeroes] + return [string reverse $out] +} + +# Encode a Bitcoin address +proc bitcoin_mkaddr {A B} { + set A [expr {$A & ((1<<256)-1)}] + set B [expr {$B & ((1<<256)-1)}] + set bin [binary format "cH*" 4 [format "%064llx%064llx" $A $B]] + set md [ripemd::ripemd160 [sha2::sha256 -bin $bin]] + set addr [binary format "ca*" 0 $md] + set hash [sha2::sha256 -bin [sha2::sha256 -bin $addr]] + append addr [binary format "a4" [string range $hash 0 3]] + return [base58encode $addr] +} diff --git a/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-2.tcl b/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-2.tcl new file mode 100644 index 0000000000..dfc628b1b2 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Tcl/bitcoin-public-point-to-address-2.tcl @@ -0,0 +1,3 @@ +puts [bitcoin_mkaddr \ + 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 \ + 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6] diff --git a/Task/CSV-data-manipulation/00DESCRIPTION b/Task/CSV-data-manipulation/00DESCRIPTION new file mode 100644 index 0000000000..bd003b6bee --- /dev/null +++ b/Task/CSV-data-manipulation/00DESCRIPTION @@ -0,0 +1,19 @@ +[[wp:Comma-separated values|CSV spreadsheet files]] are suitable for +storing tabular data in a relatively portable way. The CSV format is +flexible but somewhat ill-defined. For present purposes, authors may +assume that the data fields contain no commas, backslashes, or +quotation marks. + +The task here is to read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: + + C1,C2,C3,C4,C5 + 1,5,9,13,17 + 2,6,10,14,18 + 3,7,11,15,19 + 4,8,12,16,20 + +Suggestions +
    +
  • Show how to add a column, headed 'SUM', of the sums of the rows. +
  • If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files. +
diff --git a/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk b/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk new file mode 100644 index 0000000000..f45946981e --- /dev/null +++ b/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk @@ -0,0 +1,13 @@ +#!/usr/bin/awk -f +BEGIN { FS = OFS = "," } +NR==1 { + print $0, "SUM" + next +} +{ + sum = 0 + for (i=1; i<=NF; i++) { + sum += $i + } + print $0, sum +} diff --git a/Task/CSV-data-manipulation/AutoHotkey/csv-data-manipulation.ahk b/Task/CSV-data-manipulation/AutoHotkey/csv-data-manipulation.ahk new file mode 100644 index 0000000000..0d25e3d6d8 --- /dev/null +++ b/Task/CSV-data-manipulation/AutoHotkey/csv-data-manipulation.ahk @@ -0,0 +1,7 @@ +Loop, Read, Data.csv +{ + i := A_Index + Loop, Parse, A_LoopReadLine, CSV + Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",") +} +FileAppend, %Output%, NewData.csv diff --git a/Task/CSV-data-manipulation/C++/csv-data-manipulation.cpp b/Task/CSV-data-manipulation/C++/csv-data-manipulation.cpp new file mode 100644 index 0000000000..18e4cf13f2 --- /dev/null +++ b/Task/CSV-data-manipulation/C++/csv-data-manipulation.cpp @@ -0,0 +1,129 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class CSV +{ +public: + CSV(void) : m_nCols( 0 ), m_nRows( 0 ) + {} + + bool open( const char* filename, char delim = ',' ) + { + std::ifstream file( filename ); + + clear(); + if ( file.is_open() ) + { + open( file, delim ); + return true; + } + + return false; + } + + void open( std::istream& istream, char delim = ',' ) + { + std::string line; + + clear(); + while ( std::getline( istream, line ) ) + { + unsigned int nCol = 0; + std::istringstream lineStream(line); + std::string cell; + + while( std::getline( lineStream, cell, delim ) ) + { + m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); + nCol++; + } + m_nCols = std::max( m_nCols, nCol ); + m_nRows++; + } + } + + bool save( const char* pFile, char delim = ',' ) + { + std::ofstream ofile( pFile ); + if ( ofile.is_open() ) + { + save( ofile ); + return true; + } + return false; + } + + void save( std::ostream& ostream, char delim = ',' ) + { + for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) + { + for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) + { + ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); + if ( (nCol+1) < m_nCols ) + { + ostream << delim; + } + else + { + ostream << std::endl; + } + } + } + } + + void clear() + { + m_oData.clear(); + m_nRows = m_nCols = 0; + } + + std::string& operator()( unsigned int nCol, unsigned int nRow ) + { + m_nCols = std::max( m_nCols, nCol+1 ); + m_nRows = std::max( m_nRows, nRow+1 ); + return m_oData[std::make_pair(nCol, nRow)]; + } + + inline unsigned int GetRows() { return m_nRows; } + inline unsigned int GetCols() { return m_nCols; } + +private: + // trim string for empty spaces in begining and at the end + inline std::string &trim(std::string &s) + { + + s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace)))); + s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end()); + return s; + } + +private: + std::map, std::string> m_oData; + + unsigned int m_nCols; + unsigned int m_nRows; +}; + + +int main() +{ + CSV oCSV; + + oCSV.open( "test_in.csv" ); + oCSV( 0, 0 ) = "Column0"; + oCSV( 1, 1 ) = "100"; + oCSV( 2, 2 ) = "200"; + oCSV( 3, 3 ) = "300"; + oCSV( 4, 4 ) = "400"; + oCSV.save( "test_out.csv" ); + return 0; +} diff --git a/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs b/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs new file mode 100644 index 0000000000..387f5274f8 --- /dev/null +++ b/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; + +namespace CSV +{ + class CSV + { + private Dictionary, string> _data; + private int _rows; + private int _cols; + + public int Rows { get { return _rows; } } + public int Cols { get { return _cols; } } + + public CSV() + { + Clear(); + } + + public void Clear() + { + _rows = 0; + _cols = 0; + _data = new Dictionary, string>(); + } + + public void Open(StreamReader stream, char delim = ',') + { + string line; + int col = 0; + int row = 0; + + Clear(); + + while ((line = stream.ReadLine()) != null) + { + if (line.Length > 0) + { + string[] values = line.Split(delim); + col = 0; + foreach (var value in values) + { + this[col,row] = value; + col++; + } + row++; + } + } + stream.Close(); + } + + public void Save(StreamWriter stream, char delim = ',') + { + for (int row = 0; row < _rows; row++) + { + for (int col = 0; col < _cols; col++) + { + stream.Write(this[col, row]); + if (col < _cols - 1) + { + stream.Write(delim); + } + } + stream.WriteLine(); + } + stream.Flush(); + stream.Close(); + } + + public string this[int col, int row] + { + get + { + try + { + return _data[new Tuple(col, row)]; + } + catch + { + return ""; + } + } + + set + { + _data[new Tuple(col, row)] = value.ToString().Trim(); + _rows = Math.Max(_rows, row + 1); + _cols = Math.Max(_cols, col + 1); + } + } + + static void Main(string[] args) + { + CSV csv = new CSV(); + + csv.Open(new StreamReader(@"test_in.csv")); + csv[0, 0] = "Column0"; + csv[1, 1] = "100"; + csv[2, 2] = "200"; + csv[3, 3] = "300"; + csv[4, 4] = "400"; + csv.Save(new StreamWriter(@"test_out.csv")); + } + } +} diff --git a/Task/CSV-data-manipulation/Clojure/csv-data-manipulation.clj b/Task/CSV-data-manipulation/Clojure/csv-data-manipulation.clj new file mode 100644 index 0000000000..e6e0d44c9b --- /dev/null +++ b/Task/CSV-data-manipulation/Clojure/csv-data-manipulation.clj @@ -0,0 +1,14 @@ +(require '[clojure.data.csv :as csv] + '[clojure.java.io :as io]) + +(defn add-sum-column [coll] + (let [titles (first coll) + values (rest coll)] + (cons (conj titles "SUM") + (map #(conj % (reduce + (map read-string %))) values)))) + +(with-open [in-file (io/reader "test_in.csv")] + (doall + (let [out-data (add-sum-column (csv/read-csv in-file))] + (with-open [out-file (io/writer "test_out.csv")] + (csv/write-csv out-file out-data))))) diff --git a/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp b/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp new file mode 100644 index 0000000000..f1f6ddfdc4 --- /dev/null +++ b/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp @@ -0,0 +1,35 @@ +(defun csv_to_nested_list (filename seperator) + "Reads the csv to a nested lisp list, where each sublist represents a line. +Each line is read in as a string, the commas are substituted by spaces and +parantheses are added to the beginning and the end. Then the string can be interpreted by the +reader as an actual lisp list. A nested lisp containing all sub-lists (lines) is returned. +First line is assumed to be a comment (as no comment syntax is specified)." + (let ((list nil)) + (with-open-file (input filename) + (setf list + (loop for line = (read-line input nil) + while line collect (read-from-string + (substitute #\Tab #\, (format nil "(~a)~%" line))))) + ;; throw away first line, which is assumed to be a comment + (cdr list)))) + +(defun calc_sums (nested_list) + "Return a list of sums of each sub-list in a nested list." + (loop for sublist in nested_list collect (apply #'+ sublist))) + +(defun list_to_csv (nested_list) + "Converts the nested list back into a csv-formatted string." + (substitute #\, #\ + (substitute #\newline #\) + (remove #\((string-trim ")(" (format nil "~A" nested_list)))))) +;; main program +;; prints the results as lisp lists and as csv +(let ((nested_list (csv_to_nested_list "example_comma_csv.txt" #\,)) + (sum_list nil) + (comment "#C1,C2,C3,C4,C5,SUM")) + (setf sum_list (loop + for list in nested_list + for sum in (calc_sums nested_list) + collect (append list (list sum)))) + (format t "~A~%~%" sum_list) ;; print nested list in lisp representation + (format t "~A~%~A~%" comment (list_to_csv sum_list))) ;; print it again as csv diff --git a/Task/CSV-data-manipulation/D/csv-data-manipulation.d b/Task/CSV-data-manipulation/D/csv-data-manipulation.d new file mode 100644 index 0000000000..f9fe784459 --- /dev/null +++ b/Task/CSV-data-manipulation/D/csv-data-manipulation.d @@ -0,0 +1,10 @@ +void main() { + import std.stdio, std.csv, std.file, std.typecons, std.array, + std.algorithm, std.conv, std.range; + + auto rows = "csv_data_in.csv".File.byLine; + auto fout = "csv_data_out.csv".File("w"); + fout.writeln(rows.front); + fout.writef("%(%(%d,%)\n%)", rows.dropOne + .map!(r => r.csvReader!int.front.map!(x => x + 1))); +} diff --git a/Task/CSV-data-manipulation/Erlang/csv-data-manipulation.erl b/Task/CSV-data-manipulation/Erlang/csv-data-manipulation.erl new file mode 100644 index 0000000000..02926d0b78 --- /dev/null +++ b/Task/CSV-data-manipulation/Erlang/csv-data-manipulation.erl @@ -0,0 +1,36 @@ +-module( csv_data ). + +-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ). + +change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ). + +from_binary( Binary ) -> + Lines = binary:split( Binary, <<"\n">>, [global] ), + [binary:split(X, <<",">>, [global]) || X <- Lines]. + +from_file( Name ) -> + {ok, Binary} = file:read_file( Name ), + from_binary( Binary ). + +into_file( Name, CSV ) -> + Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ), + file:write_file( Name, Binaries ). + +task() -> + CSV = from_file( "CSV_file.in" ), + New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ), + into_file( "CSV_file.out", New_CSV ). + + + +change_foldl( {Row_number, Column_number, New}, Acc ) -> + {Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ), + {Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ), + Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters. + +join_binaries( Binaries, Binary ) -> + [_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ), + lists:reverse( Rest ). + +split( 1, List ) -> {[], List}; +split( N, List ) -> lists:split( N - 1, List ). diff --git a/Task/CSV-data-manipulation/Forth/csv-data-manipulation.fth b/Task/CSV-data-manipulation/Forth/csv-data-manipulation.fth new file mode 100644 index 0000000000..2760eb5ecb --- /dev/null +++ b/Task/CSV-data-manipulation/Forth/csv-data-manipulation.fth @@ -0,0 +1,49 @@ +\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues +\ USAGE: +\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" output.csv + + CHAR , CONSTANT SEPARATOR + 3 CONSTANT DECIMALS + 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE + +: colsum ( ca u -- F: -- sum ;return SUM from CSV-string ) + 0E0 OVER SWAP BOUNDS + ?DO ( a ) + I C@ SEPARATOR = + IF ( a ) + I TUCK OVER - >FLOAT IF F+ THEN + 1+ + THEN + LOOP DROP +; +: f>string ( -- ca u F: x -- ) + FSCALE F* + F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #> +; +: rowC!+ ( offs char -- u+1 ;store CHAR at here+OFFS,increment offset ) + OVER HERE + C! 1+ +; +: row$!+ ( offs ca u -- offs+u ;store STRING at here+OFFS,update offset ) + ROT 2DUP + >R HERE + SWAP MOVE R> +; +\ If run program with '-m 4G'option, we have practically 4G to store a row +: csvsum ( fo fi -- ;write into FILEID-OUTPUT processed input from FILEID-INPUT ) + 2DUP + HERE UNUSED ROT READ-LINE THROW + IF ( fo fi fo u ) + HERE SWAP ( fo fi fo ca u ) + SEPARATOR rowC!+ + s\" SUM" row$!+ ( fo fi fo ca u' ) + ROT WRITE-LINE THROW + BEGIN ( fo fi ) + 2DUP HERE UNUSED ROT READ-LINE THROW + WHILE ( fo fi fo u ) + HERE SWAP ( fo fi fo ca u ) + SEPARATOR rowC!+ + HERE OVER colsum f>string ( fo fi fo ca u ca' u' ) + row$!+ ( fo fi fo ca u'+u ) + ROT WRITE-LINE THROW + REPEAT + THEN + 2DROP 2DROP +; diff --git a/Task/CSV-data-manipulation/Go/csv-data-manipulation.go b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go new file mode 100644 index 0000000000..cf94c2bade --- /dev/null +++ b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go @@ -0,0 +1,79 @@ +package main + +import ( + "encoding/csv" + "io" + "log" + "os" + "strconv" +) + +func init() { + log.SetFlags(log.Lshortfile) +} + +func main() { + // Open the sample file given. + csvFile, err := os.Open("sample.csv") + + // Exit on error. + if err != nil { + log.Fatal("Error opening sample csv file:", err) + } + + // Make sure the file is closed before the function returns. + defer csvFile.Close() + + // Create a new csv reader for the file. + csvReader := csv.NewReader(csvFile) + + // Create an output file. + outputFile, err := os.Create("output.csv") + if err != nil { + log.Fatal("Error creating output file:", err) + } + defer outputFile.Close() + + csvWriter := csv.NewWriter(outputFile) + defer csvWriter.Flush() + + // For each row in the data. + for i := 0; ; i++ { + record, err := csvReader.Read() + if err == io.EOF { + break + } + if err != nil { + log.Fatal("Error reading record:", err) + } + + // Skip header row. + if i == 0 { + err = csvWriter.Write(record) + if err != nil { + log.Fatal("Error writing record to output file:", err) + } + continue + } + + // For each cell in the row. + for cell := range record { + // Convert value to integer for manipulation. + v, err := strconv.Atoi(record[cell]) + if err != nil { + log.Fatal("Error parsing cell value:", err) + } + + // Do something to the value. + v += 1 + // Store the new value back in the record variable. + record[cell] = strconv.Itoa(v) + } + + // Write modified record to disk. + err = csvWriter.Write(record) + if err != nil { + log.Fatal("Error writing record to output file:", err) + } + } +} diff --git a/Task/CSV-data-manipulation/Groovy/csv-data-manipulation.groovy b/Task/CSV-data-manipulation/Groovy/csv-data-manipulation.groovy new file mode 100644 index 0000000000..75a8cd37c4 --- /dev/null +++ b/Task/CSV-data-manipulation/Groovy/csv-data-manipulation.groovy @@ -0,0 +1,8 @@ +def csv = [] +def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } } +def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } } + +loadCsv new File('csv.txt') +csv[0][0] = 'Column0' +(1..4).each { i -> csv[i][i] = i * 100 } +saveCsv new File('csv_out.txt') diff --git a/Task/CSV-data-manipulation/Haskell/csv-data-manipulation.hs b/Task/CSV-data-manipulation/Haskell/csv-data-manipulation.hs new file mode 100644 index 0000000000..2a57121834 --- /dev/null +++ b/Task/CSV-data-manipulation/Haskell/csv-data-manipulation.hs @@ -0,0 +1,34 @@ +import Data.Array +import Data.Maybe (isJust) +import Data.List (intercalate) +import Control.Monad (when) + +delimiters = ",;:" + +fields [] = [] +fields xs = let (item, rest) = break (`elem` delimiters) xs + (_, next) = break (`notElem` delimiters) rest + in item : fields next + +unfields Nothing = [] +unfields (Just a) = every fieldNumber $ elems a + where + ((_, _), (_, fieldNumber)) = bounds a + every _ [] = [] + every n xs = let (y, z) = splitAt n xs + in intercalate "," y : every n z + +fieldArray [] = Nothing +fieldArray xs = Just $ listArray ((1,1), (length xs, length $ head xs)) + $ concat xs + +fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile + +fieldsToFile f = writeFile f . unlines . unfields + +someChanges = fmap (// [((1,1), "changed"), ((3,4), "altered"), + ((5,2), "modified")]) + +main = do + a <- fieldsFromFile "example.txt" + when (isJust a) $ fieldsToFile "output.txt" $ someChanges a diff --git a/Task/CSV-data-manipulation/Icon/csv-data-manipulation.icon b/Task/CSV-data-manipulation/Icon/csv-data-manipulation.icon new file mode 100644 index 0000000000..92f72c4729 --- /dev/null +++ b/Task/CSV-data-manipulation/Icon/csv-data-manipulation.icon @@ -0,0 +1,11 @@ +import Utils # To get CSV procedures + +procedure main(A) + f := open(A[1]) | &input + i := 1 + write(!f) # header line(?) + every csv := parseCSV(!f) do { + csv[i+:=1] *:= 100 + write(encodeCSV(csv)) + } +end diff --git a/Task/CSV-data-manipulation/J/csv-data-manipulation-1.j b/Task/CSV-data-manipulation/J/csv-data-manipulation-1.j new file mode 100644 index 0000000000..77ade045da --- /dev/null +++ b/Task/CSV-data-manipulation/J/csv-data-manipulation-1.j @@ -0,0 +1,3 @@ + data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data + data=: (<'"spam"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing) + 'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data diff --git a/Task/CSV-data-manipulation/J/csv-data-manipulation-2.j b/Task/CSV-data-manipulation/J/csv-data-manipulation-2.j new file mode 100644 index 0000000000..f58a1f9a66 --- /dev/null +++ b/Task/CSV-data-manipulation/J/csv-data-manipulation-2.j @@ -0,0 +1,4 @@ + require 'tables/csv' + data=: makenum readcsv 'rc_csv.csv' NB. read data and convert cells to numeric where possible + data=: (<'spam') (2 3;3 0)} data NB. amend 2 cells + data writecsv 'rc_outcsv.csv' NB. write out amended data. Strings are double-quoted diff --git a/Task/CSV-data-manipulation/J/csv-data-manipulation-3.j b/Task/CSV-data-manipulation/J/csv-data-manipulation-3.j new file mode 100644 index 0000000000..32ced15e8d --- /dev/null +++ b/Task/CSV-data-manipulation/J/csv-data-manipulation-3.j @@ -0,0 +1,5 @@ + require 'tables/csv' + 'hdr data'=: split readcsv 'rc_csv.csv' NB. read data, split the header & data + hdr=: hdr , <'SUM' NB. add title for extra column to header + data=: <"0 (,. +/"1) makenum data NB. convert to numeric, sum rows & append column + (hdr,data) writecsv 'rc_out.csv' diff --git a/Task/CSV-data-manipulation/J/csv-data-manipulation-4.j b/Task/CSV-data-manipulation/J/csv-data-manipulation-4.j new file mode 100644 index 0000000000..25e40cf701 --- /dev/null +++ b/Task/CSV-data-manipulation/J/csv-data-manipulation-4.j @@ -0,0 +1,2 @@ + sumCSVrows=: writecsv~ (((<'SUM') ,~ {.) , [: (<"0)@(,. +/"1) makenum@}.)@readcsv + 'rc_out.csv' sumCSVrows 'rc.csv' diff --git a/Task/CSV-data-manipulation/Java/csv-data-manipulation-1.java b/Task/CSV-data-manipulation/Java/csv-data-manipulation-1.java new file mode 100644 index 0000000000..39fab29031 --- /dev/null +++ b/Task/CSV-data-manipulation/Java/csv-data-manipulation-1.java @@ -0,0 +1,104 @@ +import java.io.*; +import java.awt.Point; +import java.util.HashMap; +import java.util.Scanner; + +public class CSV { + + private HashMap _map = new HashMap(); + private int _cols; + private int _rows; + + public void open(File file) throws FileNotFoundException, IOException { + open(file, ','); + } + + public void open(File file, char delimiter) + throws FileNotFoundException, IOException { + Scanner scanner = new Scanner(file); + scanner.useDelimiter(Character.toString(delimiter)); + + clear(); + + while(scanner.hasNextLine()) { + String[] values = scanner.nextLine().split(Character.toString(delimiter)); + + int col = 0; + for ( String value: values ) { + _map.put(new Point(col, _rows), value); + _cols = Math.max(_cols, ++col); + } + _rows++; + } + scanner.close(); + } + + public void save(File file) throws IOException { + save(file, ','); + } + + public void save(File file, char delimiter) throws IOException { + FileWriter fw = new FileWriter(file); + BufferedWriter bw = new BufferedWriter(fw); + + for (int row = 0; row < _rows; row++) { + for (int col = 0; col < _cols; col++) { + Point key = new Point(col, row); + if (_map.containsKey(key)) { + bw.write(_map.get(key)); + } + + if ((col + 1) < _cols) { + bw.write(delimiter); + } + } + bw.newLine(); + } + bw.flush(); + bw.close(); + } + + public String get(int col, int row) { + String val = ""; + Point key = new Point(col, row); + if (_map.containsKey(key)) { + val = _map.get(key); + } + return val; + } + + public void put(int col, int row, String value) { + _map.put(new Point(col, row), value); + _cols = Math.max(_cols, col+1); + _rows = Math.max(_rows, row+1); + } + + public void clear() { + _map.clear(); + _cols = 0; + _rows = 0; + } + + public int rows() { + return _rows; + } + + public int cols() { + return _cols; + } + + public static void main(String[] args) { + try { + CSV csv = new CSV(); + + csv.open(new File("test_in.csv")); + csv.put(0, 0, "Column0"); + csv.put(1, 1, "100"); + csv.put(2, 2, "200"); + csv.put(3, 3, "300"); + csv.put(4, 4, "400"); + csv.save(new File("test_out.csv")); + } catch (Exception e) { + } + } +} diff --git a/Task/CSV-data-manipulation/Java/csv-data-manipulation-2.java b/Task/CSV-data-manipulation/Java/csv-data-manipulation-2.java new file mode 100644 index 0000000000..d0610b0f14 --- /dev/null +++ b/Task/CSV-data-manipulation/Java/csv-data-manipulation-2.java @@ -0,0 +1,125 @@ +import java.io.*; +import java.util.*; + +import org.apache.commons.csv.*; + +public class RCsv { + private static final String NL = System.getProperty("line.separator"); + private static final String FILENAME_IR = "data/csvtest_in.csv"; + private static final String FILENAME_OR = "data/csvtest_sum.csv"; + private static final String COL_NAME_SUM = "SUM, \"integers\""; // demonstrate white space, comma & quote handling + + public static void main(String[] args) { + Reader iCvs = null; + Writer oCvs = null; + System.out.println(textFileContentsToString(FILENAME_IR)); + try { + iCvs = new BufferedReader(new FileReader(FILENAME_IR)); + oCvs = new BufferedWriter(new FileWriter(FILENAME_OR)); + processCsv(iCvs, oCvs); + } + catch (IOException ex) { + ex.printStackTrace(); + } + finally { + try { + if (iCvs != null) { iCvs.close(); } + if (oCvs != null) { oCvs.close(); } + } + catch (IOException ex) { + ex.printStackTrace(); + } + } + System.out.println(textFileContentsToString(FILENAME_OR)); + return; + } + + public static void processCsv(Reader iCvs, Writer oCvs) throws IOException { + CSVPrinter printer = null; + try { + printer = new CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)); + List oCvsHeaders; + List oCvsRecord; + CSVParser records = CSVFormat.DEFAULT.withHeader().parse(iCvs); + Map irHeader = records.getHeaderMap(); + oCvsHeaders = new ArrayList(Arrays.asList((irHeader.keySet()).toArray(new String[0]))); + oCvsHeaders.add(COL_NAME_SUM); + printer.printRecord(oCvsHeaders); + for (CSVRecord record : records) { + oCvsRecord = record2list(record, oCvsHeaders); + printer.printRecord(oCvsRecord); + } + } + finally { + if (printer != null) { + printer.close(); + } + } + return; + } + + private static List record2list(CSVRecord record, List oCvsHeaders) { + List cvsRecord; + Map rMap = record.toMap(); + long recNo = record.getRecordNumber(); + rMap = alterRecord(rMap, recNo); + int sum = 0; + sum = summation(rMap); + rMap.put(COL_NAME_SUM, String.valueOf(sum)); + cvsRecord = new ArrayList(); + for (String key : oCvsHeaders) { + cvsRecord.add(rMap.get(key)); + } + return cvsRecord; + } + + private static Map alterRecord(Map rMap, long recNo) { + int rv; + Random rg = new Random(recNo); + rv = rg.nextInt(50); + String[] ks = rMap.keySet().toArray(new String[0]); + int ix = rg.nextInt(ks.length); + long yv = 0; + String ky = ks[ix]; + String xv = rMap.get(ky); + if (xv != null && xv.length() > 0) { + yv = Long.valueOf(xv) + rv; + rMap.put(ks[ix], String.valueOf(yv)); + } + return rMap; + } + + private static int summation(Map rMap) { + int sum = 0; + for (String col : rMap.keySet()) { + String nv = rMap.get(col); + sum += nv != null && nv.length() > 0 ? Integer.valueOf(nv) : 0; + } + return sum; + } + + private static String textFileContentsToString(String filename) { + StringBuilder lineOut = new StringBuilder(); + Scanner fs = null; + try { + fs = new Scanner(new File(filename)); + lineOut.append(filename); + lineOut.append(NL); + while (fs.hasNextLine()) { + String line = fs.nextLine(); + lineOut.append(line); + lineOut.append(NL); + } + } + catch (FileNotFoundException ex) { + // TODO Auto-generated catch block + ex.printStackTrace(); + } + finally { + if (fs != null) { + fs.close(); + } + } + return lineOut.toString(); + } +} diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua new file mode 100644 index 0000000000..26ddaeabc9 --- /dev/null +++ b/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua @@ -0,0 +1,31 @@ +local csv={} +for line in io.lines('file.csv') do + table.insert(csv, {}) + local i=1 + for j=1,#line do + if line:sub(j,j) == ',' then + table.insert(csv[#csv], line:sub(i,j-1)) + i=j+1 + end + end + table.insert(csv[#csv], line:sub(i,j)) +end + +table.insert(csv[1], 'SUM') +for i=2,#csv do + local sum=0 + for j=1,#csv[i] do + sum=sum + tonumber(csv[i][j]) + end + if sum>0 then + table.insert(csv[i], sum) + end +end + +local newFileData = '' +for i=1,#csv do + newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' +end + +local file=io.open('file.csv', 'w') +file:write(newFileData) diff --git a/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m new file mode 100644 index 0000000000..16512a1db4 --- /dev/null +++ b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m @@ -0,0 +1,13 @@ +filename='data.csv'; +fid = fopen(filename); +header = fgetl(fid); +fclose(fid); +X = dlmread(filename,',',1,0); + +fid = fopen('data.out.csv','w+'); +fprintf(fid,'%s,sum\n',header); +for k=1:size(X,1), + fprintf(fid,"%i,",X(k,:)); + fprintf(fid,"%i\n",sum(X(k,:))); +end; +fclose(fid); diff --git a/Task/CSV-data-manipulation/Maple/csv-data-manipulation-1.maple b/Task/CSV-data-manipulation/Maple/csv-data-manipulation-1.maple new file mode 100644 index 0000000000..9e1328bb4b --- /dev/null +++ b/Task/CSV-data-manipulation/Maple/csv-data-manipulation-1.maple @@ -0,0 +1,3 @@ +M := ImportMatrix("data.csv",source=csv); +M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >; +ExportMatrix("data_out.csv",M,target=csv); diff --git a/Task/CSV-data-manipulation/Maple/csv-data-manipulation-2.maple b/Task/CSV-data-manipulation/Maple/csv-data-manipulation-2.maple new file mode 100644 index 0000000000..fb9bcf708b --- /dev/null +++ b/Task/CSV-data-manipulation/Maple/csv-data-manipulation-2.maple @@ -0,0 +1,24 @@ +> M := ImportMatrix("data.csv",source=csv); + ["C1" "C2" "C3" "C4" "C5"] + [ ] + [ 1 5 9 13 17 ] + [ ] + M := [ 2 6 10 14 18 ] + [ ] + [ 3 7 11 15 19 ] + [ ] + [ 4 8 12 16 20 ] + +> M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >; + ["C1" "C2" "C3" "C4" "C5" "Total"] + [ ] + [ 1 5 9 13 17 45 ] + [ ] + M := [ 2 6 10 14 18 50 ] + [ ] + [ 3 7 11 15 19 55 ] + [ ] + [ 4 8 12 16 20 60 ] + +> ExportMatrix("data_out.csv",M,target=csv); + 96 diff --git a/Task/CSV-data-manipulation/Mathematica/csv-data-manipulation.math b/Task/CSV-data-manipulation/Mathematica/csv-data-manipulation.math new file mode 100644 index 0000000000..91856856b4 --- /dev/null +++ b/Task/CSV-data-manipulation/Mathematica/csv-data-manipulation.math @@ -0,0 +1,9 @@ +iCSV=Import["test.csv"] +->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} +iCSV[[1, 1]] = Column0; +iCSV[[2, 2]] = 100; +iCSV[[3, 3]] = 200; +iCSV[[4, 4]] = 300; +iCSV[[5, 5]] = 400; +iCSV[[2, 3]] = 60; +Export["test.csv",iCSV]; diff --git a/Task/CSV-data-manipulation/NetRexx/csv-data-manipulation.netrexx b/Task/CSV-data-manipulation/NetRexx/csv-data-manipulation.netrexx new file mode 100644 index 0000000000..c93aba55da --- /dev/null +++ b/Task/CSV-data-manipulation/NetRexx/csv-data-manipulation.netrexx @@ -0,0 +1,122 @@ +/* NetRexx */ +options replace format comments java crossref symbols + +import org.apache.commons.csv. + +-- ============================================================================= +class RCsv public final + +properties private constant + NL = String System.getProperty("line.separator") + COL_NAME_SUM = String 'SUM, "integers"' + CSV_IFILE = 'data/csvtest_in.csv' + CSV_OFILE = 'data/csvtest_sumRexx.csv' + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method main(args = String[]) public static + Arg = Rexx(args) + iCvs = Reader null + oCvs = Writer null + parse arg ifile ofile . + if ifile = '', ifile = '.' then ifile = CSV_IFILE + if ofile = '', ofile = '.' then ofile = CSV_OFILE + say textFileContentsToString(ifile) + do + iCvs = BufferedReader(FileReader(ifile)) + oCvs = BufferedWriter(FileWriter(ofile)) + processCsv(iCvs, oCvs); + catch ex = IOException + ex.printStackTrace(); + finally + do + if iCvs \= null then iCvs.close() + if oCvs \= null then oCvs.close() + catch ex = IOException + ex.printStackTrace() + end + end + say textFileContentsToString(ofile) + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException + printer = CSVPrinter null + do + printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) + oCvsHeaders = java.util.List + oCvsRecord = java.util.List + records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) + irHeader = records.getHeaderMap() + oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) + oCvsHeaders.add(COL_NAME_SUM) + printer.printRecord(oCvsHeaders) + recordIterator = records.iterator() + record = CSVRecord + loop while recordIterator.hasNext() + record = CSVRecord recordIterator.next() + oCvsRecord = record2list(record, oCvsHeaders) + printer.printRecord(oCvsRecord) + end + finally + if printer \= null then printer.close() + end + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List + cvsRecord = java.util.List + rMap = record.toMap() + recNo = record.getRecordNumber() + rMap = alterRecord(rMap, recNo) + sum = summation(record.iterator()) + rMap.put(COL_NAME_SUM, sum) + cvsRecord = ArrayList() + loop ci = 0 to oCvsHeaders.size() - 1 + key = oCvsHeaders.get(ci) + cvsRecord.add(rMap.get(key)) + end ci + return cvsRecord + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method alterRecord(rMap = Map, recNo = long) private static binary returns Map + rv = int + rg = Random(recNo) + rv = rg.nextInt(50) + ks = rMap.keySet().toArray(String[0]) + ix = rg.nextInt(ks.length) + yv = long 0 + ky = ks[ix]; + xv = String rMap.get(ky) + if xv \= null & xv.length() > 0 then do + yv = Long.valueOf(xv).longValue() + rv + rMap.put(ks[ix], String.valueOf(yv)) + end + return rMap + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method summation(iColumn = Iterator) private static + sum = 0 + loop while iColumn.hasNext() + nv = Rexx(String iColumn.next()) + if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 + sum = sum + nv + end + return sum + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method textFileContentsToString(filename) private static + lineOut = '' + fs = Scanner null + do + fs = Scanner(File(filename)) + lineOut = lineout || filename || NL + loop while fs.hasNextLine() + line = fs.nextLine() + lineOut = lineout || line || NL + end + catch ex = FileNotFoundException + ex.printStackTrace() + finally + if fs \= null then fs.close() + end + return lineOut diff --git a/Task/CSV-data-manipulation/PHP/csv-data-manipulation.php b/Task/CSV-data-manipulation/PHP/csv-data-manipulation.php new file mode 100644 index 0000000000..8f5615d1cf --- /dev/null +++ b/Task/CSV-data-manipulation/PHP/csv-data-manipulation.php @@ -0,0 +1,36 @@ + 0,5,9,13,17 +$arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 + +//add sum and write file +foreach ($arr as $line) +{ + if ($row==0) + { + array_push($line,"SUM"); + } + else + { + array_push($line,array_sum($line)); + } + fputcsv($handle_output, $line); + $row++; +} +?> diff --git a/Task/CSV-data-manipulation/PL-I/csv-data-manipulation.pli b/Task/CSV-data-manipulation/PL-I/csv-data-manipulation.pli new file mode 100644 index 0000000000..d0bf4df793 --- /dev/null +++ b/Task/CSV-data-manipulation/PL-I/csv-data-manipulation.pli @@ -0,0 +1,65 @@ +*process source xref attributes or(!); + csv: Proc Options(Main); + /********************************************************************* + * 19.10.2013 Walter Pachl + * 'erase d:\csv.out' + * 'set dd:in=d:\csv.in,recsize(300)' + * 'set dd:out=d:\csv.out,recsize(300)' + * Say 'Input:' + * 'type csv.in' + * 'csv' + * Say ' ' + * Say 'Output:' + * 'type csv.out' + *********************************************************************/ + Dcl in Record Input; + Dcl out Record Output; + On Endfile(in) Goto part2; + Dcl (INDEX,LEFT,SUBSTR,TRIM) Builtin; + + Dcl (i,j,p,m,n) Bin Fixed(31) Init(0); + Dcl s Char(100) Var; + Dcl iline(10) Char(100) Var; + Dcl a(20,20) Char(10) Var; + Dcl sum Dec Fixed(3); + Dcl oline Char(100) Var; + + Do i=1 By 1; + Read File(in) Into(s); + iline(i)=s; + m=i; + Call sep((s)); + End; + + part2: + Do i=1 To m; + If i=1 Then + oline=iline(1)!!','!!'SUM'; + Else Do; + sum=0; + Do j=1 To n; + sum=sum+a(i,j); + End; + oline=iline(i)!!','!!trim(sum); + End; + Write File(out) From(oline); + End; + + sep: Procedure(line); + Dcl line Char(*) Var; + loop: + Do j=1 By 1; + p=index(line,','); + If p>0 Then Do; + a(i,j)=left(line,p-1); + line=substr(line,p+1); + End; + Else Do; + a(i,j)=line; + Leave loop; + End; + End; + n=j; + End; + + End; diff --git a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 new file mode 100644 index 0000000000..5b2bcb585f --- /dev/null +++ b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 @@ -0,0 +1,10 @@ +my $csvfile = './whatever.csv'; +my $fh = open($csvfile, :r); +my @header = $fh.get.split(','); +my @csv = map {[.split(',')]}, $fh.lines; +close $fh; + +my $out = open($csvfile, :w); +$out.say((@header,'SUM').join(',')); +$out.say((@$_, [+] @$_).join(',')) for @csv; +close $out; diff --git a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 new file mode 100644 index 0000000000..e2092e5444 --- /dev/null +++ b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 @@ -0,0 +1,5 @@ +use Text::CSV; +my $csvfile = './whatever.csv'; +my @csv = Text::CSV.parse-file($file); +modify(@csv); # do whatever; +csv-write-file( @csv, :file($csvfile) ); diff --git a/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl new file mode 100644 index 0000000000..074111c19e --- /dev/null +++ b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-1.pl @@ -0,0 +1,38 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use List::Util 'sum'; + +my @header = split /,/, <>; +# Remove the newline. +chomp $header[-1]; + +my %column_number; +for my $i (0 .. $#header) { + $column_number{$header[$i]} = $i; +} +my @rows = map [ split /,/ ], <>; +chomp $_->[-1] for @rows; + +# Add 1 to the numbers in the 2nd column: +$_->[1]++ for @rows; + +# Add C1 into C4: +$_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; + +# Add sums to both rows and columns. +push @header, 'Sum'; +$column_number{Sum} = $#header; + +push $_, sum(@$_) for @rows; +push @rows, [ + map { + my $col = $_; + sum(map $_->[ $column_number{$col} ], @rows); + } @header + ]; + +# Print the output. +print join(',' => @header), "\n"; +print join(',' => @$_), "\n" for @rows; diff --git a/Task/CSV-data-manipulation/Perl/csv-data-manipulation-2.pl b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-2.pl new file mode 100644 index 0000000000..9155798d5f --- /dev/null +++ b/Task/CSV-data-manipulation/Perl/csv-data-manipulation-2.pl @@ -0,0 +1,25 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use Text::CSV; +use List::Util 'sum'; + +my $csv = 'Text::CSV'->new({eol => "\n"}) + or die 'Cannot use CSV: ' . 'Text::CSV'->error_diag; + +my $file = shift; +my @rows; +open my $FH, '<', $file or die "Cannot open $file: $!"; +my @header = @{ $csv->getline($FH) }; +while (my $row = $csv->getline($FH)) { + push @rows, $row; +} +$csv->eof or $csv->error_diag; + +# +# The processing is the same. +# + +# Print the output. +$csv->print(*STDOUT, $_) for \@header, @rows; diff --git a/Task/CSV-data-manipulation/PicoLisp/csv-data-manipulation.l b/Task/CSV-data-manipulation/PicoLisp/csv-data-manipulation.l new file mode 100644 index 0000000000..fee70b0c96 --- /dev/null +++ b/Task/CSV-data-manipulation/PicoLisp/csv-data-manipulation.l @@ -0,0 +1,4 @@ +(in "data.csv" + (prinl (line) "," "SUM") + (while (split (line) ",") + (prinl (glue "," @) "," (sum format @)) ) ) diff --git a/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro b/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro new file mode 100644 index 0000000000..028345fd11 --- /dev/null +++ b/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro @@ -0,0 +1,22 @@ +test :- augment('test.csv', 'test.out.csv'). + +% augment( +InFileName, +OutFileName) +augment(InFile, OutFile) :- + open(OutFile, write, OutStream), + ( ( csv_read_file_row(InFile, Row, [line(Line)]), + % Row is of the form row( Item1, Item2, ....). + addrow(Row, Out), + csv_write_stream(OutStream, [Out], []), + fail + ) + ; close(OutStream) + ). + +% If the first item in a row is an integer, then append the sum; +% otherwise append 'SUM': +addrow( Term, NewTerm ) :- + Term =.. [F | List], + List = [X|_], + (integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'), + append(List, [Sum], NewList), + NewTerm =.. [F | NewList]. diff --git a/Task/CSV-data-manipulation/Python/csv-data-manipulation.py b/Task/CSV-data-manipulation/Python/csv-data-manipulation.py new file mode 100644 index 0000000000..d07cacf1e8 --- /dev/null +++ b/Task/CSV-data-manipulation/Python/csv-data-manipulation.py @@ -0,0 +1,11 @@ +import fileinput + +changerow, changecolumn, changevalue = 2, 4, '"Spam"' + +with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: + for line in f: + if fileinput.filelineno() == changerow: + fields = line.rstrip().split(',') + fields[changecolumn-1] = changevalue + line = ','.join(fields) + '\n' + print(line, end='') diff --git a/Task/CSV-data-manipulation/R/csv-data-manipulation-1.r b/Task/CSV-data-manipulation/R/csv-data-manipulation-1.r new file mode 100644 index 0000000000..92beded7d2 --- /dev/null +++ b/Task/CSV-data-manipulation/R/csv-data-manipulation-1.r @@ -0,0 +1,10 @@ +df <- read.csv(textConnection( +"C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20")) + +df <- transform(df,SUM = rowSums(df)) + +write.csv(df,row.names = FALSE) diff --git a/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r b/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r new file mode 100644 index 0000000000..b13e967755 --- /dev/null +++ b/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r @@ -0,0 +1 @@ + write.csv(df,row.names = FALSE,file = "foo.csv") diff --git a/Task/CSV-data-manipulation/README b/Task/CSV-data-manipulation/README new file mode 100644 index 0000000000..ac16cecc77 --- /dev/null +++ b/Task/CSV-data-manipulation/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/CSV_data_manipulation diff --git a/Task/CSV-data-manipulation/REXX/csv-data-manipulation.rexx b/Task/CSV-data-manipulation/REXX/csv-data-manipulation.rexx new file mode 100644 index 0000000000..2fcacd3899 --- /dev/null +++ b/Task/CSV-data-manipulation/REXX/csv-data-manipulation.rexx @@ -0,0 +1,24 @@ +/* REXX *************************************************************** +* extend in.csv to add a column containing the sum of the lines' elems +* 21.06.2013 Walter Pachl +**********************************************************************/ +csv='in.csv' +Do i=1 By 1 While lines(csv)>0 + l=linein(csv) + If i=1 Then + l.i=l',SUM' + Else Do + ol=l + sum=0 + Do While l<>'' + Parse Var l e ',' l + sum=sum+e + End + l.i=ol','sum + End + End +Call lineout csv +'erase' csv +Do i=1 To i-1 + Call lineout csv,l.i + End diff --git a/Task/CSV-data-manipulation/Racket/csv-data-manipulation-1.rkt b/Task/CSV-data-manipulation/Racket/csv-data-manipulation-1.rkt new file mode 100644 index 0000000000..896b0d2f40 --- /dev/null +++ b/Task/CSV-data-manipulation/Racket/csv-data-manipulation-1.rkt @@ -0,0 +1,17 @@ +#lang racket +(require (planet neil/csv:1:=7) net/url) + +(define make-reader + (make-csv-reader-maker + '((separator-chars #\,) + (strip-leading-whitespace? . #t) + (strip-trailing-whitespace? . #t)))) + +(define (all-rows port) + (define read-row (make-reader port)) + (define head (append (read-row) '("SUM"))) + (define rows (for/list ([row (in-producer read-row '())]) + (define xs (map string->number row)) + (append row (list (~a (apply + xs)))))) + (define (->string row) (string-join row "," #:after-last "\n")) + (string-append* (map ->string (cons head rows)))) diff --git a/Task/CSV-data-manipulation/Racket/csv-data-manipulation-2.rkt b/Task/CSV-data-manipulation/Racket/csv-data-manipulation-2.rkt new file mode 100644 index 0000000000..9b39a90ef6 --- /dev/null +++ b/Task/CSV-data-manipulation/Racket/csv-data-manipulation-2.rkt @@ -0,0 +1,8 @@ +(define csv-file + "C1, C2, C3, C4, C5 + 1, 5, 9, 13, 17 + 2, 6, 10, 14, 18 + 3, 7, 11, 15, 19 + 4, 8, 12, 16, 20") + +(display (all-rows (open-input-string csv-file))) diff --git a/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb b/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb new file mode 100644 index 0000000000..882985d075 --- /dev/null +++ b/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb @@ -0,0 +1,12 @@ +require 'csv' +# read: +ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible. + +# manipulate: +ar.first << "SUM" +ar[1..-1].each{|row| row << row.inject(:+)} + +# write: +CSV.open("out.csv", 'w') do |csv| + ar.each{|line| csv << line} +end diff --git a/Task/CSV-data-manipulation/Run-BASIC/csv-data-manipulation.run b/Task/CSV-data-manipulation/Run-BASIC/csv-data-manipulation.run new file mode 100644 index 0000000000..12d41bf4d0 --- /dev/null +++ b/Task/CSV-data-manipulation/Run-BASIC/csv-data-manipulation.run @@ -0,0 +1,34 @@ +csv$ = "C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20 +" + +print csv$ +dim csvData$(5,5) + +for r = 1 to 5 + a$ = word$(csv$,r,chr$(13)) + for c = 1 to 5 + csvData$(r,c) = word$(a$,c,",") + next c +next r + +[loop] +input "Row to change:";r +input "Col to change;";c +if r > 5 or c > 5 then + print "Row ";r;" or Col ";c;" is greater than 5" + goto [loop] +end if +input "Change Row ";r;" Col ";c;" from ";csvData$(r,c);" to ";d$ +csvData$(r,c) = d$ +for r = 1 to 5 + for c = 1 to 5 + print cma$;csvData$(r,c); + cma$ = "," + next c + cma$ = "" + print +next r diff --git a/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala b/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala new file mode 100644 index 0000000000..634a37b191 --- /dev/null +++ b/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala @@ -0,0 +1,28 @@ +import scala.io.Source + +object parseCSV extends App { + + val rawData = """|C1,C2,C3,C4,C5 + |1,5,9,13,17 + |2,6,10,14,18 + |3,7,11,15,19 + |20,21,22,23,24""".stripMargin + + val data = Seq((Source.fromString(rawData).getLines()).map(_.split(",")).toSeq: _*) + + val output = ((data.take(1).flatMap(x => x) :+ "SUM").mkString(",") +: // Header line + data.drop(1).map(_.map(_.toInt)). // Convert per line each array of String to array of integer + map(cells => (cells, cells.sum)). //Add sum column to assemble a tuple. Part 1 are original numbers, 2 is the sum + map(part => s"${part._1.mkString(",")},${part._2}")).mkString("\n") + + println(output) + /* Outputs: + +C1,C2,C3,C4,C5,SUM +1,5,9,13,17,45 +2,6,10,14,18,50 +3,7,11,15,19,55 +20,21,22,23,24,110 + +*/ +} diff --git a/Task/CSV-data-manipulation/Seed7/csv-data-manipulation.seed7 b/Task/CSV-data-manipulation/Seed7/csv-data-manipulation.seed7 new file mode 100644 index 0000000000..3841ce5b89 --- /dev/null +++ b/Task/CSV-data-manipulation/Seed7/csv-data-manipulation.seed7 @@ -0,0 +1,17 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var file: input is STD_NULL; + var array array string: csvData is 0 times 0 times ""; + var integer: line is 0; + begin + input := open(dir(PROGRAM) & "/csvDataManipulation.in", "r"); + while hasNext(input) do + csvData &:= split(getln(input), ","); + end while; + csvData[3][3] := "X"; + for key line range csvData do + writeln(join(csvData[line], ",")); + end for; + end func; diff --git a/Task/CSV-data-manipulation/TUSCRIPT/csv-data-manipulation.tu b/Task/CSV-data-manipulation/TUSCRIPT/csv-data-manipulation.tu new file mode 100644 index 0000000000..1cd6833f57 --- /dev/null +++ b/Task/CSV-data-manipulation/TUSCRIPT/csv-data-manipulation.tu @@ -0,0 +1,18 @@ +$$ MODE DATA +$$ csv=* +C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20 +$$ MODE TUSCRIPT +LOOP/CLEAR n,line=csv + IF (n==1) THEN + line=CONCAT (line,",SUM") + ELSE + lineadd=EXCHANGE(line,":,:':") + sum=SUM(lineadd) + line=JOIN(line,",",sum) + ENDIF + csv=APPEND(csv,line) +ENDLOOP diff --git a/Task/CSV-data-manipulation/Tcl/csv-data-manipulation.tcl b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation.tcl new file mode 100644 index 0000000000..9d26066be0 --- /dev/null +++ b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation.tcl @@ -0,0 +1,29 @@ +package require struct::matrix +package require csv + +proc addSumColumn {filename {title "SUM"}} { + set m [struct::matrix] + + # Load the CSV in + set f [open $filename] + csv::read2matrix $f $m "," auto + close $f + + # Add the column with the sums + set sumcol [$m columns] + $m add column $title + for {set i 1} {$i < [$m rows]} {incr i} { + # Fill out a dummy value + $m set cell $sumcol $i 0 + $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] + } + + # Write the CSV out + set f [open $filename w] + csv::writematrix $m $f + close $f + + $m destroy +} + +addSumColumn "example.csv" diff --git a/Task/CSV-data-manipulation/UNIX-Shell/csv-data-manipulation.sh b/Task/CSV-data-manipulation/UNIX-Shell/csv-data-manipulation.sh new file mode 100644 index 0000000000..374c4bd8e1 --- /dev/null +++ b/Task/CSV-data-manipulation/UNIX-Shell/csv-data-manipulation.sh @@ -0,0 +1,20 @@ +exec 0<"$1" # open the input file on stdin +exec 1>"$1.new" # open an output file on stdout +{ + read -r header + echo "$header,SUM" + IFS=, + while read -r -a numbers; do + sum=0 + for num in "${numbers[@]}"; do + (( sum += num )) + done + + # can write the above loop as + # sum=$(( $(IFS=+; echo "${numbers[*]}") )) + + echo "${numbers[*]},$sum" + done +} && +mv "$1" "$1.bak" && +mv "$1.new" "$1" diff --git a/Task/CSV-data-manipulation/Vedit-macro-language/csv-data-manipulation.vedit b/Task/CSV-data-manipulation/Vedit-macro-language/csv-data-manipulation.vedit new file mode 100644 index 0000000000..ed78319b72 --- /dev/null +++ b/Task/CSV-data-manipulation/Vedit-macro-language/csv-data-manipulation.vedit @@ -0,0 +1,11 @@ +File_Open("input.csv") +for (#1 = 0; #1 < 4; #1++) { + Goto_Line(#1+2) // line (starting from line 2) + if (#1) { + Search(",", ADVANCE+COUNT, #1) // column + } + #2 = Num_Eval() // #2 = old value + Del_Char(Chars_Matched) // delete old value + Num_Ins(#2+100, LEFT+NOCR) // write new value +} +File_Save_As("output.csv", OK+NOMSG) diff --git a/Task/Calendar---for-REAL-programmers/00DESCRIPTION b/Task/Calendar---for-REAL-programmers/00DESCRIPTION new file mode 100644 index 0000000000..dc9837c656 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/00DESCRIPTION @@ -0,0 +1,26 @@ +Provide an algorithm as per the [[Calendar]] task, except the entire code for the algorithm must be presented entirely without lowercase. +Also - as per many 1969 era [[wp:line printer#Paper (forms) handling|line printer]]s - format the calendar to nicely fill a page that is 132 characters wide. + +(Hint: manually convert the code from the [[Calendar]] task to all UPPERCASE) + +This task also is inspired by [http://www.ee.ryerson.ca/~elf/hack/realmen.html Real Programmers Don't Use PASCAL] by Ed Post, Datamation, volume 29 number 7, July 1983. + THE REAL PROGRAMMER'S NATURAL HABITAT + "Taped to the wall is a line-printer Snoopy calender for the year 1969." + +Moreover this task is further inspired by the ''long lost'' corollary article titled: + "Real programmers think in UPPERCASE"! + +Note: Whereas today we ''only'' need to worry about [[wp:ASCII|ASCII]], [[wp:UTF-8|UTF-8]], [[wp:UTF-16/UCS-2|UTF-16]], [[wp:UTF-32/UCS-4|UTF-32]], [[wp:UTF-7|UTF-7]] and [[wp:UTF-EBCDIC|UTF-EBCDIC]] encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into [[wp:36-bit|36-bit]] words as 6 lots of [[wp:6-bit|6-bit]] characters. More extreme words sizes include [[wp:60-bit|60-bit]] words of the [[wp:CDC 6000 series|CDC 6000 series]] computers. The Soviets even had a national character set that was inclusive of all +[[wp:GOST_10859#4-bit code: Binary coded decimal|4-bit]], +[[wp:GOST_10859#5-bit code: with BCD & mathematical operators|5-bit]], +[[wp:GOST_10859#6-bit code: with only Cyrillic upper case letters|6-bit]] & +[[wp:GOST_10859#7-bit code: Cyrillic & Latin upper case letters|7-bit]] depending on how the file was opened... '''And''' one rogue Soviet university went further and built a [http://www.computer-museum.ru/english/setun.htm 1.5-bit] based computer. + +Of course... as us [[wp:Baby-Boom Generation|Boomers]] have turned into [[wp:Geezer|Geezer]]s we have become [[wp:All_caps#Computing|HARD OF HEARING]], +and suffer from chronic [[wp:Presbyopia|Presbyopia]], hence programming in UPPERCASE +is less to do with computer architecture and more to do with practically. :-) + +For economy of size, do not actually include Snoopy generation +in either the code or the output, instead just output a place-holder. + +FYI: a nice ASCII art file of Snoopy can be found at [http://www.textfiles.com/artscene/asciiart/cursepic.art textfiles.com]. Save with a .txt extension. diff --git a/Task/Calendar---for-REAL-programmers/00META.yaml b/Task/Calendar---for-REAL-programmers/00META.yaml new file mode 100644 index 0000000000..0b8885a678 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Date and time diff --git a/Task/Calendar---for-REAL-programmers/ALGOL-68/calendar---for-real-programmers.alg b/Task/Calendar---for-REAL-programmers/ALGOL-68/calendar---for-real-programmers.alg new file mode 100644 index 0000000000..e3dbc47b23 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/ALGOL-68/calendar---for-real-programmers.alg @@ -0,0 +1,108 @@ +'PR' QUOTE 'PR' + +'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN' + + ()'STRING' MONTH NAMES = ( + "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", + "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"), + WEEKDAY NAMES = ("SU","MO","TU","WE","TH","FR","SA"); + 'FORMAT' WEEKDAY FMT = $G,N('UPB' WEEKDAY NAMES - 'LWB' WEEKDAY NAMES)(" "G)$; + + # 'JUGGLE' THE CALENDAR FORMAT TO FIT THE PRINTER/SCREEN WIDTH # + 'INT' DAY WIDTH = 'UPB' WEEKDAY NAMES(1), DAY GAP=1; + 'INT' MONTH WIDTH = (DAY WIDTH+DAY GAP) * 'UPB' WEEKDAY NAMES-1; + 'INT' MONTH HEADING LINES = 2; + 'INT' MONTH LINES = (31 'OVER' 'UPB' WEEKDAY NAMES+MONTH HEADING LINES+2); # +2 FOR HEAD/TAIL WEEKS # + 'INT' YEAR COLS = (PAGE WIDTH+1) 'OVER' (MONTH WIDTH+1); + 'INT' YEAR ROWS = ('UPB' MONTH NAMES-1)'OVER' YEAR COLS + 1; + 'INT' MONTH GAP = (PAGE WIDTH - YEAR COLS*MONTH WIDTH + 1)'OVER' YEAR COLS; + 'INT' YEAR WIDTH = YEAR COLS*(MONTH WIDTH+MONTH GAP)-MONTH GAP; + 'INT' YEAR LINES = YEAR ROWS*MONTH LINES; + + 'MODE' 'MONTHBOX' = (MONTH LINES, MONTH WIDTH)'CHAR'; + 'MODE' 'YEARBOX' = (YEAR LINES, YEAR WIDTH)'CHAR'; + + 'INT' WEEK START = 1; # 'SUNDAY' # + + 'PROC' DAYS IN MONTH = ('INT' YEAR, MONTH)'INT': + 'CASE' MONTH 'IN' 31, + 'IF' YEAR 'MOD' 4 'EQ' 0 'AND' YEAR 'MOD' 100 'NE' 0 'OR' YEAR 'MOD' 400 'EQ' 0 'THEN' 29 'ELSE' 28 'FI', + 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + 'ESAC'; + + 'PROC' DAY OF WEEK = ('INT' YEAR, MONTH, DAY)'INT': 'BEGIN' + # 'DAY' OF THE WEEK BY 'ZELLER'’S 'CONGRUENCE' ALGORITHM FROM 1887 # + 'INT' Y := YEAR, M := MONTH, D := DAY, C; + 'IF' M <= 2 'THEN' M +:= 12; Y -:= 1 'FI'; + C := Y 'OVER' 100; + Y 'MODAB' 100; + (D - 1 + ((M + 1) * 26) 'OVER' 10 + Y + Y 'OVER' 4 + C 'OVER' 4 - 2 * C) 'MOD' 7 + 'END'; + + 'MODE' 'SIMPLEOUT' = 'UNION'('STRING', ()'STRING', 'INT'); + + 'PROC' CPUTF = ('REF'()'CHAR' OUT, 'FORMAT' FMT, 'SIMPLEOUT' ARGV)'VOID':'BEGIN' + 'FILE' F; 'STRING' S; ASSOCIATE(F,S); + PUTF(F, (FMT, ARGV)); + OUT(:'UPB' S):=S; + CLOSE(F) + 'END'; + + 'PROC' MONTH REPR = ('INT' YEAR, MONTH)'MONTHBOX':'BEGIN' + 'MONTHBOX' MONTH BOX; 'FOR' LINE 'TO' 'UPB' MONTH BOX 'DO' MONTH BOX(LINE,):=" "* 2 'UPB' MONTH BOX 'OD'; + 'STRING' MONTH NAME = MONTH NAMES(MONTH); + + # CENTER THE TITLE # + CPUTF(MONTH BOX(1,(MONTH WIDTH - 'UPB' MONTH NAME ) 'OVER' 2+1:), $G$, MONTH NAME); + CPUTF(MONTH BOX(2,), WEEKDAY FMT, WEEKDAY NAMES); + + 'INT' FIRST DAY := DAY OF WEEK(YEAR, MONTH, 1); + 'FOR' DAY 'TO' DAYS IN MONTH(YEAR, MONTH) 'DO' + 'INT' LINE = (DAY+FIRST DAY-WEEK START) 'OVER' 'UPB' WEEKDAY NAMES + MONTH HEADING LINES + 1; + 'INT' CHAR =((DAY+FIRST DAY-WEEK START) 'MOD' 'UPB' WEEKDAY NAMES)*(DAY WIDTH+DAY GAP) + 1; + CPUTF(MONTH BOX(LINE,CHAR:CHAR+DAY WIDTH-1),$G(-DAY WIDTH)$, DAY) + 'OD'; + MONTH BOX + 'END'; + + 'PROC' YEAR REPR = ('INT' YEAR)'YEARBOX':'BEGIN' + 'YEARBOX' YEAR BOX; + 'FOR' LINE 'TO' 'UPB' YEAR BOX 'DO' YEAR BOX(LINE,):=" "* 2 'UPB' YEAR BOX 'OD'; + 'FOR' MONTH ROW 'FROM' 0 'TO' YEAR ROWS-1 'DO' + 'FOR' MONTH COL 'FROM' 0 'TO' YEAR COLS-1 'DO' + 'INT' MONTH = MONTH ROW * YEAR COLS + MONTH COL + 1; + 'IF' MONTH > 'UPB' MONTH NAMES 'THEN' + DONE + 'ELSE' + 'INT' MONTH COL WIDTH = MONTH WIDTH+MONTH GAP; + YEAR BOX( + MONTH ROW*MONTH LINES+1 : (MONTH ROW+1)*MONTH LINES, + MONTH COL*MONTH COL WIDTH+1 : (MONTH COL+1)*MONTH COL WIDTH-MONTH GAP + ) := MONTH REPR(YEAR, MONTH) + 'FI' + 'OD' + 'OD'; + DONE: YEAR BOX + 'END'; + + 'INT' CENTER = (YEAR COLS*(MONTH WIDTH+MONTH GAP) - MONTH GAP - 1) 'OVER' 2; + 'INT' INDENT = (PAGE WIDTH - YEAR WIDTH) 'OVER' 2; + + PRINTF(( + $N(INDENT + CENTER - 9)K G L$, "(INSERT SNOOPY HERE)", + $N(INDENT + CENTER - 1)K 4D L$, YEAR, $L$, + $N(INDENT)K N(YEAR WIDTH)(G) L$, YEAR REPR(YEAR) + )) +'END'; + +MAIN: 'BEGIN' +'CO' INSPIRED BY HTTP://WWW.EE.RYERSON.CA/~ELF/hack/realmen.html + REAL PROGRAMMERS DONT USE PASCAL - ED POST + DATAMATION, VOLUME 29 NUMBER 7, JULY 1983 + THE REAL PROGRAMMERS NATURAL HABITAT +"TAPED TO THE WALL IS A LINE-PRINTER SNOOPY CALENDER FOR THE YEAR 1969" +'CO' + 'INT' MANKIND STEPPED ON THE MOON = 1969, + LINE PRINTER WIDTH = 132; # AS AT 1969! # + PRINT CALENDAR(MANKIND STEPPED ON THE MOON, LINE PRINTER WIDTH) +'END' diff --git a/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.ada b/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.ada new file mode 100644 index 0000000000..5fc5d7f293 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.ada @@ -0,0 +1,21 @@ +WITH PRINTABLE_CALENDAR; + +PROCEDURE REAL_CAL IS + + C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132 + ((WEEKDAY_REP => + "MO TU WE TH FR SA SO", + MONTH_REP => + (" JANUARY ", " FEBRUARY ", + " MARCH ", " APRIL ", + " MAY ", " JUNE ", + " JULY ", " AUGUST ", + " SEPTEMBER ", " OCTOBER ", + " NOVEMBER ", " DECEMBER ") + )); + +BEGIN + C.PRINT_LINE_CENTERED("[SNOOPY]"); + C.NEW_LINE; + C.PRINT(1969, "NINETEEN-SIXTY-NINE"); +END REAL_CAL; diff --git a/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk b/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk new file mode 100644 index 0000000000..cd89d0cb9e --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk @@ -0,0 +1,39 @@ +CALENDAR(YR){ + LASTDAY := [], DAY := [] + TITLES = + (LTRIM + ______JANUARY_________________FEBRUARY_________________MARCH_______ + _______APRIL____________________MAY____________________JUNE________ + ________JULY___________________AUGUST_________________SEPTEMBER_____ + ______OCTOBER_________________NOVEMBER________________DECEMBER______ + ) + STRINGSPLIT, TITLE, TITLES, % CHR(10) + RES := "________________________________" YR CHR(13) CHR(10) + + LOOP 4 { ; 4 VERTICAL SECTIONS + DAY[1]:=YR SUBSTR("0" A_INDEX*3 -2, -1) 01 + DAY[2]:=YR SUBSTR("0" A_INDEX*3 -1, -1) 01 + DAY[3]:=YR SUBSTR("0" A_INDEX*3 , -1) 01 + RES .= CHR(13) CHR(10) TITLE%A_INDEX% CHR(13) CHR(10) "SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA" + LOOP , 6 { ; 6 WEEKS MAX PER MONTH + WEEK := A_INDEX, RES .= CHR(13) CHR(10) + LOOP, 21 { ; 3 WEEKS TIMES 7 DAYS + MON := CEIL(A_INDEX/7), THISWD := MOD(A_INDEX-1,7)+1 + FORMATTIME, WD, % DAY[MON], WDAY + ;~ MSGBOX % WD + FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) + IF (WD>THISWD) { + RES .= "__ " + CONTINUE + } + DD := ((WEEK>3) && DD <10) ? "__" : DD, RES .= DD " ", LASTDAY[MON] := DAY[MON], DAY[MON] +=1, D + RES .= ((WD=7) && A_INDEX < 21) ? "___" : "" + FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) + } + } + RES .= CHR(13) CHR(10) + } + STRINGREPLACE, RES, RES,_,%A_SPACE%, ALL + STRINGREPLACE, RES, RES,%A_SPACE%0,%A_SPACE%%A_SPACE%, ALL + RETURN RES +} diff --git a/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk b/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk new file mode 100644 index 0000000000..b366deaeac --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk @@ -0,0 +1,16 @@ +EXAMPLES: +GUI, FONT,S8, COURIER +GUI, ADD, EDIT, VYR W40 R1 LIMIT4 NUMBER, 1969 +GUI, ADD, EDIT, VEDIT2 W580 R38 +GUI, ADD, BUTTON, DEFAULT HIDDEN GSUBMIT +GUI, SHOW + +SUBMIT: +GUI, SUBMIT, NOHIDE +GUICONTROL,, EDIT2, % CALENDAR(YR) +RETURN + +GUIESCAPE: +GUICLOSE: +EXITAPP +RETURN diff --git a/Task/Calendar---for-REAL-programmers/BBC-BASIC/calendar---for-real-programmers.bbc b/Task/Calendar---for-REAL-programmers/BBC-BASIC/calendar---for-real-programmers.bbc new file mode 100644 index 0000000000..d3e15ee140 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/BBC-BASIC/calendar---for-real-programmers.bbc @@ -0,0 +1,47 @@ + VDU 23,22,1056;336;8,16,16,128 + + YEAR = 1969 + PRINT TAB(62) "[SNOOPY]" TAB(64); YEAR + DIM DOM(5), MJD(5), DM(5), MONTH$(11) + DAYS$ = "SU MO TU WE TH FR SA" + MONTH$() = "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", \ + \ "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" + + FOR MONTH = 1 TO 7 STEP 6 + PRINT + FOR COL = 0 TO 5 + MJD(COL) = FNMJD(1, MONTH + COL, YEAR) + MONTH$ = MONTH$(MONTH + COL - 1) + PRINT TAB(COL*22 + 11 - LEN(MONTH$)/2) MONTH$; + NEXT + FOR COL = 0 TO 5 + PRINT TAB(COL*22 + 1) DAYS$; + DM(COL) = FNDIM(MONTH + COL, YEAR) + NEXT + DOM() = 1 + COL = 0 + REPEAT + DOW = FNDOW(MJD(COL)) + IF DOM(COL)<=DM(COL) THEN + PRINT TAB(COL*22 + DOW*3 + 1); DOM(COL); + DOM(COL) += 1 + MJD(COL) += 1 + ENDIF + IF DOW=6 OR DOM(COL)>DM(COL) COL = (COL + 1) MOD 6 + UNTIL DOM(0)>DM(0) AND DOM(1)>DM(1) AND DOM(2)>DM(2) AND \ + \ DOM(3)>DM(3) AND DOM(4)>DM(4) AND DOM(5)>DM(5) + PRINT + NEXT + END + + DEF FNMJD(D%,M%,Y%) : M% -= 3 : IF M% < 0 M% += 12 : Y% -= 1 + = D% + (153*M%+2)DIV5 + Y%*365 + Y%DIV4 - Y%DIV100 + Y%DIV400 - 678882 + + DEF FNDOW(J%) = (J%+2400002) MOD 7 + + DEF FNDIM(M%,Y%) + CASE M% OF + WHEN 2: = 28 - (Y%MOD4=0) + (Y%MOD100=0) - (Y%MOD400=0) + WHEN 4,6,9,11: = 30 + OTHERWISE = 31 + ENDCASE diff --git a/Task/Calendar---for-REAL-programmers/D/calendar---for-real-programmers.d b/Task/Calendar---for-REAL-programmers/D/calendar---for-real-programmers.d new file mode 100644 index 0000000000..811d815d86 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/D/calendar---for-real-programmers.d @@ -0,0 +1 @@ +import std.string;mixin(import("CALENDAR").toLower);void main(){} diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena new file mode 100644 index 0000000000..c06d704c47 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena @@ -0,0 +1,139 @@ +#define system. +#define system'text. +#define system'routines. +#define system'calendar. +#define extensions. +#define extensions'math. +#define extensions'routines. + +// --- calendar --- + +#symbol MonthNames = ("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"). +#symbol DayNames = ("MO", "TU", "WE", "TH", "FR", "SA", "SU"). + +#class CalendarMonthPrinter +{ + #field theDate. + #field theLine. + #field theMonth. + #field theYear. + #field theRow. + + #constructor new &Year:aYear &Month:aMonth + [ + theMonth := aMonth. + theYear := aYear. + theLine := TextBuffer new. + theRow := Integer new. + ] + + #method firstLine : aDay + [ + theRow << 0. + theDate := Date new &Year:theYear &Month:theMonth &Day:aDay. + control foreach:DayNames &do: aName + [ theLine write:" " write:aName ]. + ] + + #method nextLine + [ + theLine clear. + + (theDate Month == theMonth) + ? [ + theLine~stringOp write:" " &length:(((theDate DayOfWeek) => 0 ? [ 7 ] ! [ theDate DayOfWeek ]) subtract:1 int). + + control do: + [ + theLine~stringOp write:(theDate Day) &paddingLeft:3 &with:" ". + + theDate := theDate add &Days:1. + ] + &until:[(theDate Month != theMonth)or:[theDate DayOfWeek == 1]]. + ]. + + #var(type:int) aLength := theLine length. + (aLength < 21) + ? [ theLine~stringOp write:" " &length:(21 - aLength). ]. + + theRow += 1. + + ^ theRow < 7. + ] + + #method enumerator = + { + set &index:anIndex [ self firstLine:(anIndex + 1) ] + + next [ ^ self nextLine. ] + + get = self. + }. + + #method printTitleTo : anOutput + [ + anOutput~stringOp write:(MonthNames @(theMonth - 1)) &padding:21 &with:" ". + ] + + #method printTo : anOutput + [ + anOutput write:(theLine literal). + ] +} + +#class Calendar +{ + #field theYear. + #field theRowLength. + + #constructor new : aYear + [ + theYear := aYear int. + theRowLength := 3. + ] + + #method printTo:anOutput + [ + anOutput~stringOp write:"[SNOOPY]" &padding:(theRowLength * 25) &with:" " writeLine. + anOutput~stringOp write:theYear &padding:(theRowLength * 25) &with:" " writeLine writeLine. + + #var aRowCount := 12 / theRowLength. + #var Months := matrixControl new &m:aRowCount &n:theRowLength &each: (:i:j) [ CalendarMonthPrinter new &Year:theYear &Month:(i * theRowLength + j + 1) ]. + + control foreach:Months &do: aRow + [ + control foreach:aRow &do: aMonth + [ + aMonth printTitleTo:anOutput. + + anOutput write:" ". + ]. + + anOutput writeLine. + + control for:(ParallelEnumerator new:aRow) &do: aLine + [ + control foreach:aLine &do: aPrinter + [ + aPrinter printTo:anOutput. + + anOutput write:" ". + ]. + + anOutput writeLine. + ]. + ]. + + ] +} + +// --- program --- + +#symbol program = +[ + #var aCalender := Calendar new:(consoleEx write:"Enter the year:" readLine:(Integer new)). + + aCalender printTo:consoleEx. + + consoleEx readChar. +]. diff --git a/Task/Calendar---for-REAL-programmers/GUISS/calendar---for-real-programmers.guiss b/Task/Calendar---for-REAL-programmers/GUISS/calendar---for-real-programmers.guiss new file mode 100644 index 0000000000..04f2638ee1 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/GUISS/calendar---for-real-programmers.guiss @@ -0,0 +1 @@ +RIGHTCLICK:CLOCK,ADJUST DATE AND TIME,BUTTON:CANCEL diff --git a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon new file mode 100644 index 0000000000..8d97ab5b6b --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon @@ -0,0 +1,48 @@ +$include "REALIZE.ICN" + +LINK DATETIME +$define ISLEAPYEAR IsLeapYear +$define JULIAN julian + +PROCEDURE MAIN(A) +PRINTCALENDAR(\A$<1$>|1969) +END + +PROCEDURE PRINTCALENDAR(YEAR) + COLS := 3 + MONS := $<$> + "JANUARY FEBRUARY MARCH APRIL MAY JUNE " || + "JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER " ? + WHILE PUT(MONS, TAB(FIND(" "))) DO MOVE(1) + + WRITE(CENTER("$",COLS * 24 + 4)) + WRITE(CENTER(YEAR,COLS * 24 + 4), CHAR(10)) + + M := LIST(COLS) + EVERY MON := 0 TO 9 BY COLS DO $( + WRITES(" ") + EVERY I := 1 TO COLS DO { + WRITES(CENTER(MONS$,24)) + M$ := CREATE CALENDARFORMATWEEK(1969,MON + I) + $) + WRITE() + EVERY 1 TO 7 DO $( + EVERY C := 1 TO COLS DO $( + WRITES(" ") + EVERY 1 TO 7 DO WRITES(RIGHT(@M$,3)) + $) + WRITE() + $) + $) +END + +PROCEDURE CALENDARFORMATWEEK(YEAR,M) +STATIC D +INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$> + +EVERY SUSPEND "SU"|"MO"|"TU"|"WE"|"TH"|"FR"|"SA" +EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND "" +EVERY SUSPEND 1 TO D$ DO DAY +:= 1 +IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29) +EVERY DAY TO (6*7) DO SUSPEND "" +END diff --git a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon new file mode 100644 index 0000000000..7d0c1f509e --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon @@ -0,0 +1,25 @@ +$define PROCEDURE procedure +$define END end +$define WRITE write +$define WRITES writes +$define SUSPEND suspend +$define DO do +$define TO to +$define EVERY every +$define LIST list +$define WHILE while +$define MAIN main +$define PUT put +$define TAB tab +$define MOVE move +$define CHAR move +$define CENTER center +$define RIGHT right +$define FIND find +$define STATIC static +$define INITIAL initial +$define CREATE create +$define LINK link +$define IF if +$define THEN then +$define BY by diff --git a/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-1.j b/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-1.j new file mode 100644 index 0000000000..aaf2698c08 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-1.j @@ -0,0 +1,10 @@ +B=: + 4 100 400 -/@:<.@:%~ <: +M=: 28+ 3, (10$5$3 2),~ 0 ~:/@:= 4 100 400 | ] +R=: (7 -@| B+ 0, +/\@}:@M) |."0 1 (0,#\#~41) (]&:>: *"1 >/)~ M +H=. _3(_11&{.)\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC' +H=. 'SU MO TU WE TH FR SA',:"1~H +C=: H <@,"(2) 12 6 21 }."1@($,) (' ',3 ":,.#\#~31) {~ R +D=: 0 ": -@<.@%&21@+&1@[ ]\ C@] +L=: |."0 1~ +/ .(*./\@:=)"1&' ' +E=: (|."0 1~ _2 <.@%~ +/ .(*./\.@:=)"1&' ')@:({."1) L +F=: 0 _1 }. 0 1 }. (2+[) E '[INSERT SNOOPY HERE]', ":@], D diff --git a/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-2.j b/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-2.j new file mode 100644 index 0000000000..d0ed499ec5 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/J/calendar---for-real-programmers-2.j @@ -0,0 +1,22 @@ + 132 F 1969 + [INSERT SNOOPY HERE] + 1969 + ┌────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┐ + │ JAN │ FEB │ MAR │ APR │ MAY │ JUN │ + │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│ + │ 1 2 3 4│ 1│ 1│ 1 2 3 4 5│ 1 2 3│ 1 2 3 4 5 6 7│ + │ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 2 3 4 5 6 7 8│ 6 7 8 9 10 11 12│ 4 5 6 7 8 9 10│ 8 9 10 11 12 13 14│ + │12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│ 9 10 11 12 13 14 15│13 14 15 16 17 18 19│11 12 13 14 15 16 17│15 16 17 18 19 20 21│ + │19 20 21 22 23 24 25│16 17 18 19 20 21 22│16 17 18 19 20 21 22│20 21 22 23 24 25 26│18 19 20 21 22 23 24│22 23 24 25 26 27 28│ + │26 27 28 29 30 31 │23 24 25 26 27 28 │23 24 25 26 27 28 29│27 28 29 30 │25 26 27 28 29 30 31│29 30 │ + │ │ │30 31 │ │ │ │ + ├────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┤ + │ JUL │ AUG │ SEP │ OCT │ NOV │ DEC │ + │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│ + │ 1 2 3 4 5│ 1 2│ 1 2 3 4 5 6│ 1 2 3 4│ 1│ 1 2 3 4 5 6│ + │ 6 7 8 9 10 11 12│ 3 4 5 6 7 8 9│ 7 8 9 10 11 12 13│ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 7 8 9 10 11 12 13│ + │13 14 15 16 17 18 19│10 11 12 13 14 15 16│14 15 16 17 18 19 20│12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│14 15 16 17 18 19 20│ + │20 21 22 23 24 25 26│17 18 19 20 21 22 23│21 22 23 24 25 26 27│19 20 21 22 23 24 25│16 17 18 19 20 21 22│21 22 23 24 25 26 27│ + │27 28 29 30 31 │24 25 26 27 28 29 30│28 29 30 │26 27 28 29 30 31 │23 24 25 26 27 28 29│28 29 30 31 │ + │ │31 │ │ │30 │ │ + └────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┘ diff --git a/Task/Calendar---for-REAL-programmers/PHP/calendar---for-real-programmers.php b/Task/Calendar---for-REAL-programmers/PHP/calendar---for-real-programmers.php new file mode 100644 index 0000000000..4df621773a --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/PHP/calendar---for-real-programmers.php @@ -0,0 +1,20 @@ +."$_[99]$_[104]$_[114]$_[115]"()."$_[101]$_[118]$_[97]$_[108]"() diff --git a/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-1.pl b/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-1.pl new file mode 100644 index 0000000000..76727905d5 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-1.pl @@ -0,0 +1,44 @@ +$PROGRAM = '\' + +MY @START_DOW = (3, 6, 6, 2, 4, 0, + 2, 5, 1, 3, 6, 1); +MY @DAYS = (31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31); + +MY @MONTHS; +FOREACH MY $M (0 .. 11) { + FOREACH MY $R (0 .. 5) { + $MONTHS[$M][$R] = JOIN " ", + MAP { $_ < 1 || $_ > $DAYS[$M] ? " " : SPRINTF "%2D", $_ } + MAP { $_ - $START_DOW[$M] + 1 } + $R * 7 .. $R * 7 + 6; + } +} + +SUB P { WARN $_[0], "\\N" } +P UC " [INSERT SNOOPY HERE]"; +P " 1969"; +P ""; +FOREACH (UC(" JANUARY FEBRUARY MARCH APRIL MAY JUNE"), + UC(" JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER")) { + P $_; + MY @MS = SPLICE @MONTHS, 0, 6; + P JOIN " ", ((UC "SU MO TU WE TH FR SA") X 6); + P JOIN " ", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5; +} + +\''; + +# LOWERCASE LETTERS +$E = '%' | '@'; +$C = '#' | '@'; +$H = '(' | '@'; +$O = '/' | '@'; +$T = '4' | '@'; +$R = '2' | '@'; +$A = '!' | '@'; +$Z = ':' | '@'; +$P = '0' | '@'; +$L = ',' | '@'; + +`${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${L}`; diff --git a/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-2.pl b/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-2.pl new file mode 100644 index 0000000000..470c30e4e0 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Perl/calendar---for-real-programmers-2.pl @@ -0,0 +1 @@ +$_=$ARGV[0]//1969;`\143\141\154 $_ >&2` diff --git a/Task/Calendar---for-REAL-programmers/PicoLisp/calendar---for-real-programmers.l b/Task/Calendar---for-REAL-programmers/PicoLisp/calendar---for-real-programmers.l new file mode 100644 index 0000000000..10df769426 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/PicoLisp/calendar---for-real-programmers.l @@ -0,0 +1,14 @@ +(DE CAL (YEAR) + (PRINL "====== " YEAR " ======") + (FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31)) + (LET D (DATE DAT) + (TAB (3 3 4 8) + (WHEN (= 1 (CADDR D)) + (GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) ) + (CADDR D) + (DAY DAT `(INTERN (PACK (MAPCAR CHAR (42 68 97 121))))) + (WHEN (=0 (% (INC DAT) 7)) + (PACK (CHAR 87) "EEk " (WEEK DAT)) ) ) ) ) ) + +(CAL 1969) +(BYE) diff --git a/Task/Calendar---for-REAL-programmers/README b/Task/Calendar---for-REAL-programmers/README new file mode 100644 index 0000000000..a5523fe3ac --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Calendar_-_for_"REAL"_programmers diff --git a/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx b/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx new file mode 100644 index 0000000000..176d0ebeaa --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx @@ -0,0 +1,170 @@ +/*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/ +@ABC= +DO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END +@ABCU=@ABC; UPPER @ABCU +DAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' +MONTHS_='JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER' +DAYS=; MONTHS= + DO J=1 FOR 7 + _=LOWER(WORD(DAYS_,J)) + DAYS=DAYS TRANSLATE(LEFT(_,1))SUBSTR(_,2) + END + DO J=1 FOR 12 + _=LOWER(WORD(MONTHS_,J)) + MONTHS=MONTHS TRANSLATE(LEFT(_,1))SUBSTR(_,2) + END +CALFILL=' '; MC=12; _='1 3 1234567890' "FB"X +PARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN SD SW +_=0; PARSE VAR _ COLS 1 JD 1 LOWERCASE 1 MAXKALPUTS 1 NARROW 1, + NARROWER 1 NARROWEST 1 SHORT 1 SHORTER 1 SHORTEST 1, + SMALL 1 SMALLER 1 SMALLEST 1 UPPERCASE +PARSE ARG MM '/' DD "/" YYYY _ '(' OPS; UOPS=OPS +IF _\=='' | \IS#(MM) | \IS#(DD) | \IS#(YYYY) THEN CALL ERX 86 + +@CALMONTHS ='CALMON' || LOWER('THS') +@CALSPACES ='CALSP' || LOWER('ACES') +@DEPTH ='DEP' || LOWER('TH') +@GRIDS ='GRID' || LOWER('S') +@LOWERCASE ='LOW' || LOWER('ERCASE') +@NARROW ='NAR' || LOWER('ROW') +@NARROWER ='NARROWER' +@NARROWEST ='NARROWES' || LOWER('T') +@SHORT ='SHOR' || LOWER('T') +@SHORTER ='SHORTER' +@SHORTEST ='SHORTES' || LOWER('T') +@UPPERCASE ='UPP' || LOWER('ERCASE') +@WIDTH ='WID' || LOWER('TH') + DO WHILE OPS\==''; OPS=STRIP(OPS,'L'); PARSE VAR OPS _1 2 1 _ . 1 _O OPS + UPPER _ + SELECT + WHEN ABB(@CALMONTHS) THEN MC=NAI() + WHEN ABB(@CALSPACES) THEN CALSPACES=NAI() + WHEN ABB(@DEPTH) THEN SD=NAI() + WHEN ABBN(@GRIDS) THEN GRID=NO() + WHEN ABBN(@LOWERCASE) THEN LOWERCASE=NO() + WHEN ABBN(@NARROW) THEN NARROW=NO() + WHEN ABBN(@NARROWER) THEN NARROWER=NO() + WHEN ABBN(@NARROWEST) THEN NARROWEST=NO() + WHEN ABBN(@SHORT) THEN SHORT=NO() + WHEN ABBN(@SHORTER) THEN SHORTER=NO() + WHEN ABBN(@SHORTEST) THEN SHORTEST=NO() + WHEN ABBN(@SMALL) THEN SMALL=NO() + WHEN ABBN(@SMALLER) THEN SMALLER=NO() + WHEN ABBN(@SMALLEST) THEN SMALLEST=NO() + WHEN ABBN(@UPPERCASE) THEN UPPERCASE=NO() + WHEN ABB(@WIDTH) THEN SW=NAI() + OTHERWISE NOP + END /*SELECT*/ + END /*DO WHILE OPTS\== ...*/ + +MC=INT(MC,'MONTHSCALENDER'); IF MC>0 THEN CAL=1 +DAYS=' 'DAYS; MONTHS=' 'MONTHS +CYYYY=RIGHT(DATE(),4); HYY=LEFT(CYYYY,2); LYY=RIGHT(CYYYY,2) +DY.=31; _=30; PARSE VAR _ DY.4 1 DY.6 1 DY.9 1 DY.11; DY.2=28+LY(YYYY) +YY=RIGHT(YYYY,2); SD=P(SD 43); SW=P(SW 80); CW=10; CINDENT=1; CALWIDTH=76 +IF SMALL THEN DO; NARROW=1 ; SHORT=1 ; END +IF SMALLER THEN DO; NARROWER=1 ; SHORTER=1 ; END +IF SMALLEST THEN DO; NARROWEST=1; SHORTEST=1; END +IF SHORTEST THEN SHORTER=1 +IF SHORTER THEN SHORT =1 +IF NARROW THEN DO; CW=9; CINDENT=3; CALWIDTH=69; END +IF NARROWER THEN DO; CW=4; CINDENT=1; CALWIDTH=34; END +IF NARROWEST THEN DO; CW=2; CINDENT=1; CALWIDTH=20; END +CV_=CALWIDTH+CALSPACES+2 +CALFILL=LEFT(COPIES(CALFILL,CW),CW) + DO J=1 FOR 7; _=WORD(DAYS,J) + DO JW=1 FOR 3; _D=STRIP(SUBSTR(_,CW*JW-CW+1,CW)) + IF JW=1 THEN _D=CENTRE(_D,CW+1) + ELSE _D=LEFT(_D,CW+1) + DAYS.JW=DAYS.JW||_D + END /*JW*/ + __=DAYSN + IF NARROWER THEN DAYSN=__||CENTRE(LEFT(_,3),5) + IF NARROWEST THEN DAYSN=__||CENTER(LEFT(_,2),3) + END /*J*/ +_YYYY=YYYY; CALPUTS=0; CV=1; _MM=MM+0; MONTH=WORD(MONTHS,MM) +DY.2=28+LY(_YYYY); DIM=DY._MM; _DD=01; DOW=DOW(_MM,_DD,_YYYY); $DD=DD+0 + +/*─────────────────────────────NOW: THE BUSINESS OF THE BUILDING THE CAL*/ +CALL CALGEN + DO _J=2 TO MC + IF CV_\=='' THEN DO + CV=CV+CV_ + IF CV+CV_>=SW THEN DO; CV=1; CALL CALPUT + CALL FCALPUTS;CALL CALPB + END + ELSE CALPUTS=0 + END + ELSE DO;CALL CALPB;CALL CALPUT;CALL FCALPUTS;END + _MM=_MM+1; IF _MM==13 THEN DO; _MM=1; _YYYY=_YYYY+1; END + MONTH=WORD(MONTHS,_MM); DY.2=28+LY(_YYYY); DIM=DY._MM + DOW=DOW(_MM,_DD,_YYYY); $DD=0; CALL CALGEN + END /*_J*/ +CALL FCALPUTS +RETURN _ + +/*─────────────────────────────CALGEN SUBROUTINE────────────────────────*/ +CALGEN: CELLX=;CELLJ=;CELLM=;CALCELLS=0;CALLINE=0 +CALL CALPUT +CALL CALPUTL COPIES('─',CALWIDTH),"┌┐"; CALL CALHD +CALL CALPUTL MONTH ' ' _YYYY ; CALL CALHD +IF NARROWEST | NARROWER THEN CALL CALPUTL DAYSN + ELSE DO JW=1 FOR 3 + IF SPACE(DAYS.JW)\=='' THEN CALL CALPUTL DAYS.JW + END +CALFT=1; CALFB=0 + DO JF=1 FOR DOW-1; CALL CELLDRAW CALFILL,CALFILL; END + DO JY=1 FOR DIM; CALL CELLDRAW JY; END +CALFB=1 + DO 7; CALL CELLDRAW CALFILL,CALFILL; END +IF SD>32 & \SHORTER THEN CALL CALPUT +RETURN + +/*─────────────────────────────CELLDRAW SUBROUTINE──────────────────────*/ +CELLDRAW: PARSE ARG ZZ,CDDOY;ZZ=RIGHT(ZZ,2);CALCELLS=CALCELLS+1 +IF CALCELLS>7 THEN DO + CALLINE=CALLINE+1 + CELLX=SUBSTR(CELLX,2) + CELLJ=SUBSTR(CELLJ,2) + CELLM=SUBSTR(CELLM,2) + CELLB=TRANSLATE(CELLX,,")(─-"#) + IF CALLINE==1 THEN CALL CX + CALL CALCSM; CALL CALPUTL CELLX; CALL CALCSJ; CALL CX + CELLX=; CELLJ=; CELLM=; CALCELLS=1 + END +CDDOY=RIGHT(CDDOY,CW); CELLM=CELLM'│'CENTER('',CW) +CELLX=CELLX'│'CENTRE(ZZ,CW); CELLJ=CELLJ'│'CENTER('',CW) +RETURN + +/*═════════════════════════════GENERAL 1-LINE SUBS══════════════════════*/ +ABB:ARG ABBU;PARSE ARG ABB;RETURN ABBREV(ABBU,_,ABBL(ABB)) +ABBL:RETURN VERIFY(ARG(1)LEFT(@ABC,1),@ABC,'M')-1 +ABBN:PARSE ARG ABBN;RETURN ABB(ABBN)|ABB('NO'ABBN) +CALCSJ:IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;IF SD>24&\SHORT THEN CALL CALPUTL CELLJ; RETURN +CALCSM:IF SD>24&\SHORT THEN CALL CALPUTL CELLM;IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;RETURN +CALHD:IF SD>24&\SHORTER THEN CALL CALPUTL;IF SD>32&\SHORTEST THEN CALL CALPUTL;RETURN +CALPB:IF \GRID&SHORTEST THEN CALL PUT CHK;RETURN +CALPUT:CALPUTS=CALPUTS+1;MAXKALPUTS=MAX(MAXKALPUTS,CALPUTS);IF SYMBOL('CT.'CALPUTS)\=='VAR' THEN CT.CALPUTS=;CT.CALPUTS=OVERLAY(ARG(1),CT.CALPUTS,CV);RETURN +CALPUTL:CALL CALPUT COPIES(' ',CINDENT)LEFT(ARG(2)"│",1)CENTER(ARG(1),CALWIDTH)||RIGHT('│'ARG(2),1);RETURN +CX:CX_='├┤';CX=COPIES(COPIES('─',CW)'┼',7);IF CALFT THEN DO;CX=TRANSLATE(CX,'┬',"┼");CALFT=0;END;IF CALFB THEN DO;CX=TRANSLATE(CX,'┴',"┼");CX_='└┘';CALFB=0;END;CALL CALPUTL CX,CX_;RETURN +DOW:PROCEDURE;ARG M,D,Y;IF M<3 THEN DO;M=M+12;Y=Y-1;END;YL=LEFT(Y,2);YR=RIGHT(Y,2);W=(D+(M+1)*26%10+YR+YR%4+YL%4+5*YL)//7;IF W==0 THEN W=7;RETURN W +ER:PARSE ARG _1,_2;CALL '$ERR' "14"P(_1) P(WORD(_1,2) !FID(1)) _2;IF _1<0 THEN RETURN _1;EXIT RESULT +ERR:CALL ER '-'ARG(1),ARG(2);RETURN '' +ERX:CALL ER '-'ARG(1),ARG(2);EXIT '' +FCALPUTS: DO J=1 FOR MAXKALPUTS;CALL PUT CT.J;END;CT.=;MAXKALPUTS=0;CALPUTS=0;RETURN +INT:INT=NUMX(ARG(1),ARG(2));IF \ISINT(INT) THEN CALL ERX 92,ARG(1) ARG(2);RETURN INT/1 +IS#:RETURN VERIFY(ARG(1),#)==0 +ISINT:RETURN DATATYPE(ARG(1),'W') +LOWER:RETURN TRANSLATE(ARG(1),@ABC,@ABCU) +LY:ARG _;IF LENGTH(_)==2 THEN _=HYY||_;LY=_//4==0;IF LY==0 THEN RETURN 0;LY=((_//100\==0)|_//400==0);RETURN LY +NA:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);PARSE VAR OPS NA OPS;IF NA=='' THEN CALL ERX 35,_O;RETURN NA +NAI:RETURN INT(NA(),_O) +NAN:RETURN NUMX(NA(),_O) +NO:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);RETURN LEFT(_,2)\=='NO' +NUM:PROCEDURE;PARSE ARG X .,F,Q;IF X=='' THEN RETURN X;IF DATATYPE(X,'N') THEN RETURN X/1;X=SPACE(TRANSLATE(X,,','),0);IF DATATYPE(X,'N') THEN RETURN X/1;RETURN NUMNOT() +NUMNOT:IF Q==1 THEN RETURN X;IF Q=='' THEN CALL ER 53,X F;CALL ERX 53,X F +NUMX:RETURN NUM(ARG(1),ARG(2),1) +P:RETURN WORD(ARG(1),1) +PUT:_=ARG(1);_=TRANSLATE(_,,'_'CHK);IF \GRID THEN _=UNGRID(_);IF LOWERCASE THEN _=LOWER(_);IF UPPERCASE THEN UPPER _;IF SHORTEST&_=' ' THEN RETURN;CALL TELL _;RETURN +TELL:SAY ARG(1);RETURN +UNGRID:RETURN TRANSLATE(ARG(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣") diff --git a/Task/Calendar---for-REAL-programmers/Racket/calendar---for-real-programmers.rkt b/Task/Calendar---for-REAL-programmers/Racket/calendar---for-real-programmers.rkt new file mode 100644 index 0000000000..46f1fb83fb --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Racket/calendar---for-real-programmers.rkt @@ -0,0 +1,35 @@ +#CI(MODULE NAME-OF-THIS-FILE RACKET +(REQUIRE RACKET/DATE) +(DEFINE (CALENDAR YR) + (DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N))))) + (DEFINE MONTHS + (FOR/LIST ([MN (IN-NATURALS 1)] + [MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY + AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER)]) + (DEFINE S (FIND-SECONDS 0 0 12 1 MN YR)) + (DEFINE PFX (DATE-WEEK-DAY (SECONDS->DATE S))) + (DEFINE DAYS + (LET ([? (IF (= MN 12) (Λ(X Y) Y) (Λ(X Y) X))]) + (ROUND (/ (- (FIND-SECONDS 0 0 12 1 (? (+ 1 MN) 1) (? YR (+ 1 YR))) S) + 60 60 24)))) + (LIST* (~A MNAME #:WIDTH 20 #:ALIGN 'CENTER) "SU MO TU WE TH FR SA" + (MAP STRING-JOIN + (NSPLIT 7 `(,@(MAKE-LIST PFX " ") + ,@(FOR/LIST ([D DAYS]) + (~A (+ D 1) #:WIDTH 2 #:ALIGN 'RIGHT)) + ,@(MAKE-LIST (- 42 PFX DAYS) " "))))))) + (LET* ([S '(" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\ 40~A! 9( 3( 80 39-4! 10\\._\\" + ", ,-4'! 5#2X3@7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\! " + "2/_23\\! /_25\\!/_27\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!")] + [S (REGEXP-REPLACE* "!" (STRING-APPEND* S) "~%")] + [S (REGEXP-REPLACE* "@" S (STRING-FOLDCASE "X"))] + [S (REGEXP-REPLACE* ".(?:[1-7][0-9]*|[1-9])" S + (Λ(M) (MAKE-STRING (STRING->NUMBER (SUBSTRING M 1)) + (STRING-REF M 0))))]) + (PRINTF S YR)) + (FOR-EACH (COMPOSE1 DISPLAYLN STRING-TITLECASE) + (DROPF-RIGHT (FOR*/LIST ([3MS (NSPLIT 3 MONTHS)] [S (APPLY MAP LIST 3MS)]) + (REGEXP-REPLACE " +$" (STRING-JOIN S " ") "")) + (Λ(S) (EQUAL? "" S))))) + +(CALENDAR 1969)) diff --git a/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-1.rb b/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-1.rb new file mode 100644 index 0000000000..46b25450a4 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-1.rb @@ -0,0 +1,26 @@ +# loadup.rb - run UPPERCASE RUBY program + +class Object + alias lowercase_method_missing method_missing + + # Allow UPPERCASE method calls. + def method_missing(sym, *args, &block) + str = sym.to_s + if str == (down = str.downcase) + lowercase_method_missing sym, *args, &block + else + send down, *args, &block + end + end + + # RESCUE an exception without the 'rescue' keyword. + def RESCUE(_BEGIN, _CLASS, _RESCUE) + begin _BEGIN.CALL + rescue _CLASS + _RESCUE.CALL; end + end +end + +_PROGRAM = ARGV.SHIFT +_PROGRAM || ABORT("USAGE: #{$0} PROGRAM.RB ARGS...") +LOAD($0 = _PROGRAM) diff --git a/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-2.rb b/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-2.rb new file mode 100644 index 0000000000..36dcd44baa --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Ruby/calendar---for-real-programmers-2.rb @@ -0,0 +1,84 @@ +# CAL.RB - CALENDAR +REQUIRE 'DATE'.DOWNCASE + +# FIND CLASSES. +OBJECT = [].CLASS.SUPERCLASS +DATE = OBJECT.CONST_GET('DATE'.DOWNCASE.CAPITALIZE) + +# CREATES A CALENDAR OF _YEAR_. RETURNS THIS CALENDAR AS A MULTI-LINE +# STRING FIT TO _COLUMNS_. +OBJECT.SEND(:DEFINE_METHOD, :CAL) {|_YEAR, _COLUMNS| + + # START AT JANUARY 1. + # + # DATE::ENGLAND MARKS THE SWITCH FROM JULIAN CALENDAR TO GREGORIAN + # CALENDAR AT 1752 SEPTEMBER 14. THIS REMOVES SEPTEMBER 3 TO 13 FROM + # YEAR 1752. (BY FORTUNE, IT KEEPS JANUARY 1.) + # + _DATE = DATE.NEW(_YEAR, 1, 1, DATE::ENGLAND) + + # COLLECT CALENDARS OF ALL 12 MONTHS. + _MONTHS = (1..12).COLLECT {|_MONTH| + _ROWS = [DATE::MONTHNAMES[_MONTH].UPCASE.CENTER(20), + "SU MO TU WE TH FR SA"] + + # MAKE ARRAY OF 42 DAYS, STARTING WITH SUNDAY. + _DAYS = [] + _DATE.WDAY.TIMES { _DAYS.PUSH " " } + CATCH(:BREAK) { + LOOP { + (_DATE.MONTH == _MONTH) || THROW(:BREAK) + _DAYS.PUSH("%2D".DOWNCASE % _DATE.MDAY) + _DATE += 1 }} + (42 - _DAYS.LENGTH).TIMES { _DAYS.PUSH " " } + + _DAYS.EACH_SLICE(7) {|_WEEK| _ROWS.PUSH(_WEEK.JOIN " ") } + _ROWS } + + # CALCULATE MONTHS PER ROW (MPR). + # 1. DIVIDE COLUMNS BY 22 COLUMNS PER MONTH, ROUNDED DOWN. (PRETEND + # TO HAVE 2 EXTRA COLUMNS; LAST MONTH USES ONLY 20 COLUMNS.) + # 2. DECREASE MPR IF 12 MONTHS WOULD FIT IN THE SAME MONTHS PER + # COLUMN (MPC). FOR EXAMPLE, IF WE CAN FIT 5 MPR AND 3 MPC, THEN + # WE USE 4 MPR AND 3 MPC. + _MPR = (_COLUMNS + 2).DIV 22 + _MPR = 12.DIV((12 + _MPR - 1).DIV _MPR) + + # USE 20 COLUMNS PER MONTH + 2 SPACES BETWEEN MONTHS. + _WIDTH = _MPR * 22 - 2 + + # JOIN MONTHS INTO CALENDAR. + _ROWS = ["[SNOOPY]".CENTER(_WIDTH), "#{_YEAR}".CENTER(_WIDTH)] + _MONTHS.EACH_SLICE(_MPR) {|_SLICE| + _SLICE[0].EACH_INDEX {|_I| + _ROWS.PUSH(_SLICE.MAP {|_A| _A[_I]}.JOIN " ") }} + _ROWS.JOIN("\012") } + + +(ARGV.LENGTH == 1) || ABORT("USAGE: #{$0} YEAR") + +# GUESS WIDTH OF TERMINAL. +# 1. OBEY ENVIRONMENT VARIABLE COLUMNS. +# 2. TRY TO REQUIRE 'IO/CONSOLE' FROM RUBY 1.9.3. +# 3. TRY TO RUN `TPUT CO`. +# 4. ASSUME 80 COLUMNS. +LOADERROR = OBJECT.CONST_GET('LOAD'.DOWNCASE.CAPITALIZE + + 'ERROR'.DOWNCASE.CAPITALIZE) +STANDARDERROR = OBJECT.CONST_GET('STANDARD'.DOWNCASE.CAPITALIZE + + 'ERROR'.DOWNCASE.CAPITALIZE) +_INTEGER = 'INTEGER'.DOWNCASE.CAPITALIZE +_TPUT_CO = 'TPUT CO'.DOWNCASE +_COLUMNS = RESCUE(PROC {SEND(_INTEGER, ENV["COLUMNS"] || "")}, + STANDARDERROR, + PROC { + RESCUE(PROC { + REQUIRE 'IO/CONSOLE'.DOWNCASE + IO.CONSOLE.WINSIZE[1] + }, LOADERROR, + PROC { + RESCUE(PROC { + SEND(_INTEGER, `#{_TPUT_CO}`) + }, STANDARDERROR, + PROC {80}) }) }) + +PUTS CAL(ARGV[0].TO_I, _COLUMNS) diff --git a/Task/Calendar---for-REAL-programmers/Seed7/calendar---for-real-programmers.seed7 b/Task/Calendar---for-REAL-programmers/Seed7/calendar---for-real-programmers.seed7 new file mode 100644 index 0000000000..7034b99f58 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Seed7/calendar---for-real-programmers.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + include "getf.s7i"; + include "progs.s7i"; + +const proc: main is func + local + var string: source is ""; + begin + source := lower(getf("CALENDAR.TXT")); + source := replace(source, "dayofweek", "dayOfWeek"); + source := replace(source, "daysinmonth", "daysInMonth"); + execute(parseStri(source)); + end func; diff --git a/Task/Calendar---for-REAL-programmers/Tcl/calendar---for-real-programmers.tcl b/Task/Calendar---for-REAL-programmers/Tcl/calendar---for-real-programmers.tcl new file mode 100644 index 0000000000..da368f1bb7 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Tcl/calendar---for-real-programmers.tcl @@ -0,0 +1,48 @@ +\146\157\162\145\141\143\150 42 [\151\156\146\157 \143\157\155\155\141\156\144\163] { + \145\166\141\154 " + \160\162\157\143 [\163\164\162\151\156\147 \164\157\165\160\160\145\162 $42] {\141\162\147\163} \{ + \163\145\164 \151 1 + \146\157\162\145\141\143\150 \141 \$\141\162\147\163 \{ + \151\146 \[\163\164\162\151\156\147 \155\141\164\143\150 _ \$\141\] \{\151\156\143\162 \151; \143\157\156\164\151\156\165\145\} + \151\146 \$\151%2 \{\154\141\160\160\145\156\144 \156\141\162\147\163 \[\163\164\162\151\156\147 \164\157\154\157\167\145\162 \$\141\]\} \{\154\141\160\160\145\156\144 \156\141\162\147\163 \$\141\} + \} + \165\160\154\145\166\145\154 \"$42 \$\156\141\162\147\163\" + \} + " + } + +PROC _ CPUTS {L S} { + UPVAR _ CAL CAL + APPEND _ CAL($L) $S + } +PROC _ CENTER {S LN} { + SET _ C [STRING LENGTH $S] + SET _ L [EXPR _ ($LN-$C)/2]; SET _ R [EXPR _ $LN-$L-$C] + FORMAT "%${L}S%${C}S%${R}S" _ "" $S "" + } +PROC _ CALENDAR {{YEAR 1969} {WIDTH 80}} { + ARRAY SET CAL "" + SET _ YRS [EXPR $YEAR-1584] + SET _ SDAY [EXPR (6+$YRS+(($YRS+3)/4)-(($YRS-17)/100+1)+(($YRS+383)/400))%7] + CPUTS 0 [CENTER "(SNOOPY)" [EXPR $WIDTH/25*25]]; CPUTS 1 "" + CPUTS 2 [CENTER "--- $YEAR ---" [EXPR $WIDTH/25*25]]; CPUTS 3 "" + FOR _ {SET _ NR 0} {$NR<=11} {INCR _ NR} { + SET _ LINE [EXPR ($NR/($WIDTH/25))*8+4] + SET _ NAME [LINDEX _ "JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER" $NR] + SET _ DAYS [EXPR 31-((($NR)%7)%2)-($NR==1)*(2-((($YEAR%4==0)&&($YEAR%100>0))||($YEAR%400==0)))] + CPUTS $LINE "[CENTER $NAME 20] " + CPUTS [INCR _ LINE] "MO TU WE TH FR SA SU "; INCR _ LINE + SET _ DAY [EXPR 1-$SDAY] + FOR _ {SET _ X 0} {$X<42} {INCR _ X} { + IF _ ($DAY>0)&&($DAY<=$DAYS) {CPUTS $LINE [FORMAT "%2d " $DAY]} {CPUTS $LINE " "} + IF _ (($X+1)%7)==0 {CPUTS $LINE " "; INCR _ LINE} + INCR _ DAY + } + SET _ SDAY [EXPR ($SDAY+($DAYS%7))%7] + } + FOR _ {SET _ X 0} {$X<[ARRAY SIZE _ CAL]} {INCR _ X} { + PUTS _ $CAL($X) + } + } + +CALENDAR diff --git a/Task/Calendar---for-REAL-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit b/Task/Calendar---for-REAL-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit new file mode 100644 index 0000000000..d621fe3a32 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit @@ -0,0 +1,65 @@ +BS(BF) +CFT(22) +#3 = 6 // NUMBER OF MONTHS PER LINE +#2 = 1969 // YEAR +#1 = 1 // STARTING MONTH +IC(' ', COUNT, #3*9) IT("[SNOOPY]") IN(2) +IC(' ', COUNT, #3*9+1) NI(#2) IN +REPEAT(12/#3) { + REPEAT (#3) { + BS(BF) + CALL("DRAW_CALENDAR") + RCB(10, 1, EOB_POS, COLSET, 1, 21) + BQ(OK) + #5 = CP + RI(10) + GP(#5) + EOL IC(9) + #1++ + } + EOF IN(2) +} +RETURN + +:DRAW_CALENDAR: +NUM_PUSH(4,20) +#20 = RF +BOF DC(ALL) + +NI(#1, LEFT+NOCR) IT("/1/") NI(#2, LEFT+NOCR) +RCB(#20, BOL_POS, EOL_POS, DELETE) +#10 = JDATE(@(#20)) + +#4 = #2+(#1==12) +NI(#1%12+1, LEFT+NOCR) IT("/1/") NI(#4, LEFT+NOCR) +RCB(#20, BOL_POS, CP, DELETE) +#11 = JDATE(@(#20)) - #10 +#7 = (#10-1) % 7 + +IF (#1==1) { RS(#20," JANUARY ") } +IF (#1==2) { RS(#20," FEBRUARY") } +IF (#1==3) { RS(#20," MARCH ") } +IF (#1==4) { RS(#20," APRIL ") } +IF (#1==5) { RS(#20," MAY ") } +IF (#1==6) { RS(#20," JUNE ") } +IF (#1==7) { RS(#20," JULY ") } +IF (#1==8) { RS(#20," AUGUST ") } +IF (#1==9) { RS(#20,"SEPTEMBER") } +IF (#1==10) { RS(#20," OCTOBER ") } +IF (#1==11) { RS(#20," NOVEMBER") } +IF (#1==12) { RS(#20," DECEMBER") } + +IT(" ") RI(#20) IN +IT(" MO TU WE TH FR SA SU") IN +IT(" --------------------") IN +IC(' ', COUNT, #7*3) +FOR (#8 = 1; #8 <= #11; #8++) { + NI(#8, COUNT, 3) + #5 = (#8+#10+5) % 7 + IF (#5 == 6) { IN } +} +IT(" ") + +REG_EMPTY(#20) +NUM_POP(4,20) +RETURN diff --git a/Task/Calendar---for-REAL-programmers/X86-Assembly/calendar---for-real-programmers.x86 b/Task/Calendar---for-REAL-programmers/X86-Assembly/calendar---for-real-programmers.x86 new file mode 100644 index 0000000000..b48eeae6ba --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/X86-Assembly/calendar---for-real-programmers.x86 @@ -0,0 +1,187 @@ + .MODEL TINY + .CODE + .486 + ORG 100H ;.COM FILES START HERE +YEAR EQU 1969 ;DISPLAY CALENDAR FOR SPECIFIED YEAR +START: MOV CX, 61 ;SPACE(61); TEXT(0, "[SNOOPY]"); CRLF(0) + CALL SPACE + MOV DX, OFFSET SNOOPY + CALL TEXT + MOV CL, 63 ;SPACE(63); INTOUT(0, YEAR); CRLF(0); CRLF(0) + CALL SPACE + MOV AX, YEAR + CALL INTOUT + CALL CRLF + CALL CRLF + + MOV DI, 1 ;FOR MONTH:= 1 TO 12 DO DI=MONTH +L22: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL +L23: MOV CL, 5 ; SPACE(5) + CALL SPACE + MOV DX, DI ; TEXT(0, MONAME(MONTH+COL-1)); SPACE(7); + DEC DX ; DX:= (MONTH+COL-1)*10+MONAME + ADD DX, SI + IMUL DX, 10 + ADD DX, OFFSET MONAME + CALL TEXT + MOV CL, 7 + CALL SPACE + CMP SI, 5 ; IF COL<5 THEN SPACE(1); + JGE L24 + MOV CL, 1 + CALL SPACE + INC SI + JMP L23 +L24: CALL CRLF + + MOV SI, 6 ; FOR COL:= 0 TO 6-1 DO +L25: MOV DX, OFFSET SUMO ; TEXT(0, "SU MO TU WE TH FR SA"); + CALL TEXT + DEC SI ; IF COL<5 THEN SPACE(2); + JE L27 + MOV CL, 2 + CALL SPACE + JMP L25 +L27: CALL CRLF + + XOR SI, SI ;FOR COL:= 0 TO 6-1 DO +L28: MOV BX, DI ;DAY OF FIRST SUNDAY OF MONTH (CAN BE NEGATIVE) + ADD BX, SI ;DAY(COL):= 1 - WEEKDAY(YEAR, MONTH+COL, 1); + MOV BP, YEAR + +;DAY OF WEEK FOR FIRST DAY OF THE MONTH (0=SUN 1=MON..6=SAT) + CMP BL, 2 ;IF MONTH<=2 THEN + JG L3 + ADD BL, 12 ; MONTH:= MONTH+12; + DEC BP ; YEAR:= YEAR-1; +L3: +;REM((1-1 + (MONTH+1)*26/10 + YEAR + YEAR/4 + YEAR/100*6 + YEAR/400)/7) + INC BX ;MONTH + IMUL AX, BX, 26 + MOV CL, 10 + CWD + IDIV CX + MOV BX, AX + MOV AX, BP ;YEAR + ADD BX, AX + SHR AX, 2 + ADD BX, AX + MOV CL, 25 + CWD + IDIV CX + IMUL DX, AX, 6 ;YEAR/100*6 + ADD BX, DX + SHR AX, 2 ;YEAR/400 + ADD AX, BX + MOV CL, 7 + CWD + IDIV CX + NEG DX + INC DX + MOV [SI+DAY], DL ;COL+DAY + INC SI + CMP SI, 5 + JLE L28 + + MOV BP, 6 ;FOR LINE:= 0 TO 6-1 DO BP=LINE +L29: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL +L30: MOV BX, DI ; DAYMAX:= DAYS(MONTH+COL); + MOV BL, [BX+SI+DAYS] + +;IF MONTH+COL=2 & (REM(YEAR/4)=0 & REM(YEAR/100)#0 ! REM(YEAR/400)=0) THEN + MOV AX, DI ;MONTH + ADD AX, SI + CMP AL, 2 + JNE L32 + MOV AX, YEAR + TEST AL, 03H + JNE L32 + MOV CL,100 + CWD + IDIV CX + TEST DX, DX + JNE L31 + TEST AL, 03H + JNE L32 +L31: INC BX ;IF FEBRUARY AND LEAP YEAR THEN ADD A DAY +L32: + MOV DX, 7 ;FOR WEEKDAY:= 0 TO 7-1 DO +L33: MOVZX AX, [SI+DAY] ; IF DAY(COL)>=1 & DAY(COL)<=DAYMAX THEN + CMP AL, 1 + JL L34 + CMP AL, BL + JG L34 + CALL INTOUT ; INTOUT(0, DAY(COL)); + CMP AL, 10 ; IF DAY(COL)<10 THEN SPACE(1); LEFT JUSTIFY + JGE L36 + MOV CL, 1 + CALL SPACE + JMP L36 +L34: MOV CL, 2 ; ELSE SPACE(2); + CALL SPACE ; SUPPRESS OUT OF RANGE DAYS +L36: MOV CL, 1 ; SPACE(1); + CALL SPACE + INC BYTE PTR [SI+DAY] ; DAY(COL):= DAY(COL)+1; + DEC DX ;NEXT WEEKDAY + JNE L33 + + CMP SI, 5 ;IF COL<5 THEN SPACE(1); + JGE L37 + MOV CL, 1 + CALL SPACE + INC SI + JMP L30 +L37: CALL CRLF + + DEC BP ;NEXT LINE DOWN + JNE L29 + CALL CRLF + + ADD DI, 6 ;NEXT 6 MONTHS + CMP DI, 12 + JLE L22 + RET + +;DISPLAY POSITIVE INTEGER IN AX +INTOUT: PUSHA + MOV BX, 10 + XOR CX, CX +NO10: CWD + IDIV BX + PUSH DX + INC CX + TEST AX, AX + JNE NO10 +NO20: MOV AH, 02H + POP DX + ADD DL, '0' + INT 21H + LOOP NO20 + POPA + RET + +;DISPLAY CX SPACE CHARACTERS +SPACE: PUSHA +SP10: MOV AH, 02H + MOV DL, 20H + INT 21H + LOOP SP10 + POPA + RET + +;START A NEW LINE +CRLF: MOV DX, OFFSET LCRLF + +;DISPLAY STRING AT DX +TEXT: MOV AH, 09H + INT 21H + RET + +SNOOPY DB "[SNOOPY]" +LCRLF DB 0DH, 0AH, '$' +MONAME DB " JANUARY $ FEBRUARY$ MARCH $ APRIL $ MAY $ JUNE $" + DB " JULY $ AUGUST $SEPTEMBER$ OCTOBER$ NOVEMBER$ DECEMBER$" +SUMO DB "SU MO TU WE TH FR SA$" +DAYS DB 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 +DAY DB ?, ?, ?, ?, ?, ? + END START diff --git a/Task/Casting-out-nines/00DESCRIPTION b/Task/Casting-out-nines/00DESCRIPTION new file mode 100644 index 0000000000..d643a652b0 --- /dev/null +++ b/Task/Casting-out-nines/00DESCRIPTION @@ -0,0 +1,20 @@ +A task in three parts: + +;Part 1 +Write a procedure (say \mathit{co9}(x)) which implements [http://mathforum.org/library/drmath/view/55926.html Casting Out Nines] as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky. + +;Part 2 +Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: +:Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]). +:note that 318682 has the same checksum as (101558 + 217124); +:note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); +:note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2. + +Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. + +;Part 3 +Considering [http://mathworld.wolfram.com/CastingOutNines.html this Mathworld page], produce a efficient algorithmn based on the more mathmatical treatment of Casting Out Nines, and realizing: +:\mathit{co9}(x) is the residual of x mod 9; +:the procedure can be extended to bases other than 9. + +Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. diff --git a/Task/Casting-out-nines/00META.yaml b/Task/Casting-out-nines/00META.yaml new file mode 100644 index 0000000000..397ec18e01 --- /dev/null +++ b/Task/Casting-out-nines/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Checksums diff --git a/Task/Casting-out-nines/C++/casting-out-nines-1.cpp b/Task/Casting-out-nines/C++/casting-out-nines-1.cpp new file mode 100644 index 0000000000..ca1de8dc75 --- /dev/null +++ b/Task/Casting-out-nines/C++/casting-out-nines-1.cpp @@ -0,0 +1,20 @@ +// Casting Out Nines +// +// Nigel Galloway. June 24th., 2012 +// +#include +int main() { + int Base = 10; + const int N = 2; + int c1 = 0; + int c2 = 0; + for (int k=1; k +#include +struct ran { + const int base; + std::vector rs; + ran(const int base) : base(base) { for (int nz=0; nzbase) + ,_next((_ran->base-1)*_x + _ran->rs[_r]) + { + while (operator*() < start) operator++(); + } + const co9& operator++() { + const int oldr = _r; + _r = ++_r%_ran->rs.size(); + if (_rbase-1)*_x + _ran->rs[_r]; + return *this; + } +}; + +int main() { + ran r(10); + for (int i : co9(1,99,&r)) { std::cout << i << ' '; } + return 0; +} diff --git a/Task/Casting-out-nines/C++/casting-out-nines-3.cpp b/Task/Casting-out-nines/C++/casting-out-nines-3.cpp new file mode 100644 index 0000000000..d2bccd8cf4 --- /dev/null +++ b/Task/Casting-out-nines/C++/casting-out-nines-3.cpp @@ -0,0 +1,5 @@ +struct ran { + const int base; + std::vector rs; + ran(const int base) : base(base) { for (int nz=0; nz x % (base - 1) == (x * x) % (base - 1)); + auto x = start / (base - 1); + immutable y = start % (base - 1); + + typeof(return) result; + while (true) { + foreach (immutable n; ran) { + immutable k = (base - 1) * x + n; + if (k < start) + continue; + if (k > end) + return result; + result ~= k; + } + x++; + } +} + +void main() { + castOut(16, 1, 255).writeln; + castOut(10, 1, 99).writeln; + castOut(17, 1, 288).writeln; +} diff --git a/Task/Casting-out-nines/Go/casting-out-nines.go b/Task/Casting-out-nines/Go/casting-out-nines.go new file mode 100644 index 0000000000..88b24f2a9e --- /dev/null +++ b/Task/Casting-out-nines/Go/casting-out-nines.go @@ -0,0 +1,168 @@ +package main + +import ( + "fmt" + "log" + "strconv" +) + +// A casting out nines algorithm. + +// Quoting from: http://mathforum.org/library/drmath/view/55926.html +/* +First, for any number we can get a single digit, which I will call the +"check digit," by repeatedly adding the digits. That is, we add the +digits of the number, then if there is more than one digit in the +result we add its digits, and so on until there is only one digit +left. + +... + +You may notice that when you add the digits of 6395, if you just +ignore the 9, and the 6+3 = 9, you still end up with 5 as your check +digit. This is because any 9's make no difference in the result. +That's why the process is called "casting out" nines. Also, at any +step in the process, you can add digits, not just at the end: to do +8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is +11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never +have to work with numbers bigger than 18. +*/ +// The twist is that co9Peterson returns a function to do casting out nines +// in any specified base from 2 to 36. +func co9Peterson(base int) (cob func(string) (byte, error), err error) { + if base < 2 || base > 36 { + return nil, fmt.Errorf("co9Peterson: %d invalid base", base) + } + // addDigits adds two digits in the specified base. + // People perfoming casting out nines by hand would usually have their + // addition facts memorized. In a program, a lookup table might be + // analogous, but we expediently use features of the programming language + // to add digits in the specified base. + addDigits := func(a, b byte) (string, error) { + ai, err := strconv.ParseInt(string(a), base, 64) + if err != nil { + return "", err + } + bi, err := strconv.ParseInt(string(b), base, 64) + if err != nil { + return "", err + } + return strconv.FormatInt(ai+bi, base), nil + } + // a '9' in the specified base. that is, the greatest digit. + s9 := strconv.FormatInt(int64(base-1), base) + b9 := s9[0] + // define result function. The result function may return an error + // if n is not a valid number in the specified base. + cob = func(n string) (r byte, err error) { + r = '0' + for i := 0; i < len(n); i++ { // for each digit of the number + d := n[i] + switch { + case d == b9: // if the digit is '9' of the base, cast it out + continue + // if the result so far is 0, the digit becomes the result + case r == '0': + r = d + continue + } + // otherwise, add the new digit to the result digit + s, err := addDigits(r, d) + if err != nil { + return 0, err + } + switch { + case s == s9: // if the sum is "9" of the base, cast it out + r = '0' + continue + // if the sum is a single digit, it becomes the result + case len(s) == 1: + r = s[0] + continue + } + // otherwise, reduce this two digit intermediate result before + // continuing. + r, err = cob(s) + if err != nil { + return 0, err + } + } + return + } + return +} + +// Subset code required by task. Given a base and a range specified with +// beginning and ending number in that base, return candidate Kaprekar numbers +// based on the observation that k%(base-1) must equal (k*k)%(base-1). +// For the % operation, rather than the language built-in operator, use +// the method of casting out nines, which in fact implements %(base-1). +func subset(base int, begin, end string) (s []string, err error) { + // convert begin, end to native integer types for easier iteration + begin64, err := strconv.ParseInt(begin, base, 64) + if err != nil { + return nil, fmt.Errorf("subset begin: %v", err) + } + end64, err := strconv.ParseInt(end, base, 64) + if err != nil { + return nil, fmt.Errorf("subset end: %v", err) + } + // generate casting out nines function for specified base + cob, err := co9Peterson(base) + if err != nil { + return + } + for k := begin64; k <= end64; k++ { + ks := strconv.FormatInt(k, base) + rk, err := cob(ks) + if err != nil { // assertion + panic(err) // this would indicate a bug in subset + } + rk2, err := cob(strconv.FormatInt(k*k, base)) + if err != nil { // assertion + panic(err) // this would indicate a bug in subset + } + // test for candidate Kaprekar number + if rk == rk2 { + s = append(s, ks) + } + } + return +} + +var testCases = []struct { + base int + begin, end string + kaprekar []string +}{ + {10, "1", "100", []string{"1", "9", "45", "55", "99"}}, + {17, "10", "gg", []string{"3d", "d4", "gg"}}, +} + +func main() { + for _, tc := range testCases { + fmt.Printf("\nTest case base = %d, begin = %s, end = %s:\n", + tc.base, tc.begin, tc.end) + s, err := subset(tc.base, tc.begin, tc.end) + if err != nil { + log.Fatal(err) + } + fmt.Println("Subset: ", s) + fmt.Println("Kaprekar:", tc.kaprekar) + sx := 0 + for _, k := range tc.kaprekar { + for { + if sx == len(s) { + fmt.Printf("Fail:", k, "not in subset") + return + } + if s[sx] == k { + sx++ + break + } + sx++ + } + } + fmt.Println("Valid subset.") + } +} diff --git a/Task/Casting-out-nines/J/casting-out-nines-1.j b/Task/Casting-out-nines/J/casting-out-nines-1.j new file mode 100644 index 0000000000..6fa35d0042 --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-1.j @@ -0,0 +1,3 @@ +castout=: 1 :0 + [: (#~ ] =&((m-1)&|) *:) <. + [: i. (+*)@-~ +) diff --git a/Task/Casting-out-nines/J/casting-out-nines-2.j b/Task/Casting-out-nines/J/casting-out-nines-2.j new file mode 100644 index 0000000000..215bcaf701 --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-2.j @@ -0,0 +1,2 @@ + 0 (10 castout) 100 +0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 diff --git a/Task/Casting-out-nines/J/casting-out-nines-3.j b/Task/Casting-out-nines/J/casting-out-nines-3.j new file mode 100644 index 0000000000..2fef19d683 --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-3.j @@ -0,0 +1,3 @@ +castout=: 1 :0 + [: (#~ 0 = (m-1) | 0 _1 1&p.) <. + [: i. (+*)@-~ +) diff --git a/Task/Casting-out-nines/J/casting-out-nines-4.j b/Task/Casting-out-nines/J/casting-out-nines-4.j new file mode 100644 index 0000000000..c50e99dce3 --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-4.j @@ -0,0 +1,4 @@ + (#~ 0=9|0 _1 1&p.) i.101 +0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 + (#~ ] =&(9&|) *:) i. 101 +0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 diff --git a/Task/Casting-out-nines/J/casting-out-nines-5.j b/Task/Casting-out-nines/J/casting-out-nines-5.j new file mode 100644 index 0000000000..24c69c9f4b --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-5.j @@ -0,0 +1,2 @@ + (#~ ] =&(co9=: 9&|) *:) i. 101 +0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 diff --git a/Task/Casting-out-nines/J/casting-out-nines-6.j b/Task/Casting-out-nines/J/casting-out-nines-6.j new file mode 100644 index 0000000000..14d3296d3c --- /dev/null +++ b/Task/Casting-out-nines/J/casting-out-nines-6.j @@ -0,0 +1,3 @@ +co9=: 9&| + (#~ ] =&co9 *:) i. 101 +0 1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100 diff --git a/Task/Casting-out-nines/Julia/casting-out-nines.julia b/Task/Casting-out-nines/Julia/casting-out-nines.julia new file mode 100644 index 0000000000..ee24e78045 --- /dev/null +++ b/Task/Casting-out-nines/Julia/casting-out-nines.julia @@ -0,0 +1,3 @@ +co9(x) = x == 9 ? 0 : + 1<=x<=8 ? x : + co9(sum(digits(x))) diff --git a/Task/Casting-out-nines/Objeck/casting-out-nines.objeck b/Task/Casting-out-nines/Objeck/casting-out-nines.objeck new file mode 100644 index 0000000000..9be8f1622b --- /dev/null +++ b/Task/Casting-out-nines/Objeck/casting-out-nines.objeck @@ -0,0 +1,20 @@ +class CastingNines { + function : Main(args : String[]) ~ Nil { + base := 10; + N := 2; + c1 := 0; + c2 := 0; + + for (k:=1; kAs(Float)->Power(N->As(Float)); k+=1;){ + c1+=1; + if (k%(base-1) = (k*k)%(base-1)){ + c2+=1; + IO.Console->Print(k)->Print(" "); + }; + }; + + IO.Console->Print("\nTrying ")->Print(c2)->Print(" numbers instead of ") + ->Print(c1)->Print(" numbers saves ")->Print(100 - (c2->As(Float)/c1 + ->As(Float)*100))->PrintLine("%"); + } +} diff --git a/Task/Casting-out-nines/PARI-GP/casting-out-nines.pari b/Task/Casting-out-nines/PARI-GP/casting-out-nines.pari new file mode 100644 index 0000000000..886d9e1146 --- /dev/null +++ b/Task/Casting-out-nines/PARI-GP/casting-out-nines.pari @@ -0,0 +1,11 @@ +{base=10; +N=2; +c1=c2=0; +for(k=1,base^N-1, + c1++; + if (k%(base-1) == k^2%(base-1), + c2++; + print1(k" ") + ); +); +print("\nTrying "c2" numbers instead of "c1" numbers saves " 100.-(c2/c1)*100 "%")} diff --git a/Task/Casting-out-nines/Perl-6/casting-out-nines.pl6 b/Task/Casting-out-nines/Perl-6/casting-out-nines.pl6 new file mode 100644 index 0000000000..8e97fcf8e6 --- /dev/null +++ b/Task/Casting-out-nines/Perl-6/casting-out-nines.pl6 @@ -0,0 +1,16 @@ +sub cast-out(\BASE = 10, \MIN = 1, \MAX = BASE**2 - 1) { + my \B9 = BASE - 1; + my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9); + my $x = MIN div B9; + gather loop { + for @ran -> \n { + my \k = B9 * $x + n; + take k if k >= MIN; + } + $x++; + } ...^ * > MAX; +} + +say cast-out; +say cast-out 16; +say cast-out 17; diff --git a/Task/Casting-out-nines/Perl/casting-out-nines.pl b/Task/Casting-out-nines/Perl/casting-out-nines.pl new file mode 100644 index 0000000000..3ac241d7bc --- /dev/null +++ b/Task/Casting-out-nines/Perl/casting-out-nines.pl @@ -0,0 +1,33 @@ +sub co9 { # Follows the simple procedure asked for in Part 1 + my $n = shift; + return $n if $n < 10; + my $sum = 0; $sum += $_ for split(//,$n); + co9($sum); +} + +sub showadd { + my($n,$m) = @_; + print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]", + " = ", $n+$m," [",co9($n+$m),"]\n"; +} + +sub co9filter { + my $base = shift; + die unless $base >= 2; + my($beg, $end, $basem1) = (1, $base*$base-1, $base-1); + my @list = grep { $_ % $basem1 == $_*$_ % $basem1 } $beg .. $end; + ($end, scalar(@list), @list); +} + +print "Part 1: Create a simple filter and demonstrate using simple example.\n"; +showadd(6395, 1259); + +print "\nPart 2: Use this to filter a range with co9(k) == co9(k^2).\n"; +print join(" ", grep { co9($_) == co9($_*$_) } 1..99), "\n"; + +print "\nPart 3: Use efficient method on range.\n"; +for my $base (10, 17) { + my($N, $n, @l) = co9filter($base); + printf "[@l]\nIn base %d, trying %d numbers instead of %d saves %.4f%%\n\n", + $base, $n, $N, 100-($n/$N)*100; +} diff --git a/Task/Casting-out-nines/PicoLisp/casting-out-nines.l b/Task/Casting-out-nines/PicoLisp/casting-out-nines.l new file mode 100644 index 0000000000..e82c7c9517 --- /dev/null +++ b/Task/Casting-out-nines/PicoLisp/casting-out-nines.l @@ -0,0 +1,36 @@ +(de kaprekar (N) + (let L (cons 0 (chop (* N N))) + (for ((I . R) (cdr L) R (cdr R)) + (NIL (gt0 (format R))) + (T (= N (+ @ (format (head I L)))) N) ) ) ) + +(de co9 (N) + (until + (> 9 + (setq N + (sum + '((N) (unless (= "9" N) (format N))) + (chop N) ) ) ) ) + N ) + +(println 'Part1:) +(println + (= + (co9 (+ 6395 1259)) + (co9 (+ (co9 6395) (co9 1259))) ) ) + +(println 'Part2:) +(println + (filter + '((N) (= (co9 N) (co9 (* N N)))) + (range 1 100) ) ) +(println + (filter kaprekar (range 1 100)) ) + +(println 'Part3 '- 'base17:) +(println + (filter + '((N) (= (% N 16) (% (* N N) 16))) + (range 1 100) ) ) + +(bye) diff --git a/Task/Casting-out-nines/Python/casting-out-nines.py b/Task/Casting-out-nines/Python/casting-out-nines.py new file mode 100644 index 0000000000..68d365627c --- /dev/null +++ b/Task/Casting-out-nines/Python/casting-out-nines.py @@ -0,0 +1,19 @@ +# Casting out Nines +# +# Nigel Galloway: June 27th., 2012, +# +def CastOut(Base=10, Start=1, End=999999): + ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)] + x,y = divmod(Start, Base-1) + while True: + for n in ran: + k = (Base-1)*x + n + if k < Start: + continue + if k > End: + return + yield k + x += 1 + +for V in CastOut(Base=16,Start=1,End=255): + print(V, end=' ') diff --git a/Task/Casting-out-nines/README b/Task/Casting-out-nines/README new file mode 100644 index 0000000000..3373438e77 --- /dev/null +++ b/Task/Casting-out-nines/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Casting_out_nines diff --git a/Task/Casting-out-nines/REXX/casting-out-nines.rexx b/Task/Casting-out-nines/REXX/casting-out-nines.rexx new file mode 100644 index 0000000000..d58cba831e --- /dev/null +++ b/Task/Casting-out-nines/REXX/casting-out-nines.rexx @@ -0,0 +1,43 @@ +/*REXX program to demonstrate casting-out-nines (with Kaprekar numbers).*/ +parse arg start stop base . /*get the user args (if any). */ +if base=='' then base=10 /*use base ten if not specified. */ +if start=='' then do; start=1; stop=1000; end /*use the defaults?*/ +if stop=='' then stop=start /*not specified? Use the default*/ +numbers=castOut(start,stop,base) /*generate a list of numbers. */ +@cast_out='cast-out-'||(base-1) "test" /*construct a text shortcut. */ +say 'For' start "through" stop', the following passed the' @cast_out":" +say numbers; say /*display the list of numbers. */ +q=stop-start+1 /*Q is the range of #s in list.*/ +p=words(numbers) /*P is the number of #s in list.*/ +pc=format(p/q*100,,2)/1 || '%' /*calculate the percentage (%). */ +say 'For' q "numbers," p 'passed the' @cast_out "("pc') for base' base"." +if base\==10 then exit /*if radix ¬ ten, then stop pgm. */ +Kaps=kaprekar(start,stop) /*generate a list of Kaprekar #s.*/ +say; say 'The Kaprekar numbers in the same range are:' Kaps +say + do i=1 for words(Kaps); x=word(Kaps,i) /*verify 'em in list. */ + if wordpos(x,numbers)\==0 then iterate /*OK so far ... */ + say 'Kaprekar number' x "isn't in the numbers list." /*oops!*/ + exit /*go spank the coder. */ + end + +say 'All Kaprekar numbers are in the' @cast_out "numbers list." /*ok*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CASTOUT subroutine──────────────────*/ +castOut: procedure; parse arg low,high,radix; $= + high=word(high low,1) /*use default of LOW for HIGH.*/ +radix=word(radix 10,1) /*use default ot 10 for RADIX.*/ +niner=radix-1 /*a fast way to use RADIX - 1. */ + do j=low to high /*traipse through the arg range. */ + if j//niner==j*j//niner then $=$ j /*pass the test?*/ + end /*j*/ +return strip($) /*strip leading blank from result*/ +/*──────────────────────────────────Kaprekar subroutine─────────────────*/ +kaprekar: procedure; parse arg L,H; #=0; $=; if L<=1 then $=1 +numeric digits max(10,2*length(H**2)) /*insure enough digits for H². */ + do j=max(2,L) to H; s=j*j /*slow way to find Kaprekar #'s. */ + do k=1 for length(s)%2 + if j==left(s,k)+substr(s,k+1) then $=$ j /*found a Kaprekar #.*/ + end /*k*/ + end /*j*/ +return strip($) /*return all the Kaprekar numbers*/ diff --git a/Task/Casting-out-nines/Racket/casting-out-nines.rkt b/Task/Casting-out-nines/Racket/casting-out-nines.rkt new file mode 100644 index 0000000000..4e55707913 --- /dev/null +++ b/Task/Casting-out-nines/Racket/casting-out-nines.rkt @@ -0,0 +1,11 @@ +#lang racket +(require math) + +(define (digits n) + (map (compose1 string->number string) + (string->list (number->string n)))) + +(define (cast-out-nines n) + (with-modulus 9 + (for/fold ([sum 0]) ([d (digits n)]) + (mod+ sum d)))) diff --git a/Task/Casting-out-nines/Seed7/casting-out-nines.seed7 b/Task/Casting-out-nines/Seed7/casting-out-nines.seed7 new file mode 100644 index 0000000000..72dc309157 --- /dev/null +++ b/Task/Casting-out-nines/Seed7/casting-out-nines.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + +const func bitset: castOut (in integer: base, in integer: start, in integer: ending) is func + result + var bitset: casted is {}; + local + var bitset: ran is {}; + var integer: x is 0; + var integer: n is 0; + var integer: k is 0; + var boolean: finished is FALSE; + begin + for x range 0 to base - 2 do + if x rem pred(base) = x ** 2 rem pred(base) then + incl(ran, x); + end if; + end for; + x := start div pred(base); + repeat + for n range ran until finished do + k := pred(base) * x + n; + if k >= start then + if k > ending then + finished := TRUE; + else + incl(casted, k); + end if; + end if; + end for; + incr(x); + until finished; + end func; + +const proc: main is func + begin + writeln(castOut(16, 1, 255)); + end func; diff --git a/Task/Casting-out-nines/Tcl/casting-out-nines.tcl b/Task/Casting-out-nines/Tcl/casting-out-nines.tcl new file mode 100644 index 0000000000..efdc3eaf37 --- /dev/null +++ b/Task/Casting-out-nines/Tcl/casting-out-nines.tcl @@ -0,0 +1,39 @@ +proc co9 {x} { + while {[string length $x] > 1} { + set x [tcl::mathop::+ {*}[split $x ""]] + } + return $x +} +# Extended to the general case +proc coBase {x {base 10}} { + while {$x >= $base} { + for {set digits {}} {$x} {set x [expr {$x / $base}]} { + lappend digits [expr {$x % $base}] + } + set x [tcl::mathop::+ {*}$digits] + } + return $x +} + +# Simple helper +proc percent {part whole} {format "%.2f%%" [expr {($whole - $part) * 100.0 / $whole}]} + +puts "In base 10..." +set satisfying {} +for {set i 1} {$i < 100} {incr i} { + if {[co9 $i] == [co9 [expr {$i*$i}]]} { + lappend satisfying $i + } +} +puts $satisfying +puts "Trying [llength $satisfying] numbers instead of 99 numbers saves [percent [llength $satisfying] 99]" + +puts "In base 16..." +set satisfying {} +for {set i 1} {$i < 256} {incr i} { + if {[coBase $i 16] == [coBase [expr {$i*$i}] 16]} { + lappend satisfying $i + } +} +puts $satisfying +puts "Trying [llength $satisfying] numbers instead of 255 numbers saves [percent [llength $satisfying] 255]" diff --git a/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION new file mode 100644 index 0000000000..0a0cc3e4a5 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION @@ -0,0 +1,4 @@ +The task is to print out the first 15 Catalan numbers by extracting them from Pascal's triangle, see [http://milan.milanovic.org/math/english/fibo/fibo4.html Catalan Numbers and the Pascal Triangle]. This enables calculation of Catalan Numbers using only addition and subtraction. See [http://mathworld.wolfram.com/CatalansTriangle.html Catalan's Triangle] for a Number Triangle that generates Catalan Numbers using only addition. + +Related Tasks: +[[Pascal's triangle]] diff --git a/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 new file mode 100644 index 0000000000..a0cc83dae1 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 @@ -0,0 +1,91 @@ +CATALAN CSECT + USING CATALAN,R13,R12 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'CATALAN' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + LA R12,4095(R13) + LA R12,1(R12) +* ---- CODE + LA R0,1 + ST R0,T t(1)=1 + LA R4,0 ix:i=1 + LA R6,1 by 1 + LH R7,N to n +LOOPI BXH R4,R6,ENDLOOPI loop i + LR R5,R4 ix:j=i+1 + LA R5,2(R5) i+2 + LA R8,0 + BCTR R8,0 by -1 + LA R9,1 to 2 +LOOP1J BXLE R5,R8,ENLOOP1J loop j + LR R10,R5 j + BCTR R10,0 + SLA R10,2 + L R2,T(R10) r2=t(j) + LR R1,R10 j + SH R1,=H'4' + L R3,T(R1) r3=t(j-1) + AR R2,R3 r2=r2+r3 + ST R2,T(R10) t(j)=t(j)+t(j-1) + B LOOP1J +ENLOOP1J EQU * + LR R1,R4 i + BCTR R1,0 + SLA R1,2 + L R3,T(R1) t(i) + LA R1,4(R1) + ST R3,T(R1) t(i+1) + LR R5,R4 ix:j=i+2 + LA R5,3(R5) i+3 + LA R8,0 + BCTR R8,0 by -1 + LA R9,1 to 2 +LOOP2J BXLE R5,R8,ENLOOP2J loop j + LR R10,R5 j + BCTR R10,0 + SLA R10,2 + L R2,T(R10) r2=t(j) + LR R1,R10 j + SH R1,=H'4' + L R3,T(R1) r3=t(j-1) + AR R2,R3 r2=r2+r3 + ST R2,T(R10) t(j)=t(j)+t(j-1) + B LOOP2J +ENLOOP2J EQU * + LR R1,R4 i + BCTR R1,0 + SLA R1,2 + L R2,T(R1) t(i) + LA R1,4(R1) + L R3,T(R1) t(i+1) + SR R3,R2 + CVD R3,P + UNPK Z,P + MVC C,Z + OI C+L'C-1,X'F0' + MVC WTOBUF(8),C+8 + WTO MF=(E,WTOMSG) + B LOOPI +ENDLOOPI EQU * +* ---- END CODE + CNOP 0,4 + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +* ---- DATA +N DC H'15' +T DC 17F'0' +P DS PL8 +Z DS ZL16 +C DS CL16 +WTOMSG DS 0F + DC H'80' + DC H'0' +WTOBUF DC CL80' ' + YREGS + END diff --git a/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada b/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada new file mode 100644 index 0000000000..477d3b78a9 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada @@ -0,0 +1,14 @@ +with Ada.Text_IO, Pascal; + +procedure Catalan is + + Last: Positive := 15; + Row: Pascal.Row := Pascal.First_Row(2*Last+1); + +begin + for I in 1 .. Last loop + Row := Pascal.Next_Row(Row); + Row := Pascal.Next_Row(Row); + Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2))); + end loop; +end Catalan; diff --git a/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk new file mode 100644 index 0000000000..4921c4ed98 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk @@ -0,0 +1,30 @@ +/* Generate Catalan Numbers +// +// smgs: 20th Feb, 2014 +*/ +Array := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pascal's triangle assigned +INI := 3 ; starts with calculating the 3rd row and as such the value +Loop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1 +{ + if ( A_index > 2 ) + { + Loop, % A_INDEX + { + old := ini-1, index := A_index, index_1 := A_index + 1 + Array[ini, index_1] := Array[old, index] + Array[old, index_1] + Array[ini, 1] := Array[ini, ini] := 1 + line .= Array[ini, A_index] " " + } + ;~ MsgBox % line ; gives rows of pascal's triangle + ; calculating every odd row starting from 1st so as to obtain catalan's numbers + if ( mod(ini,2) != 0) + { + StringSplit, res, line, %A_Space% + ans := res0//2, ans_1 := ans++ + result := result . res%ans_1% - res%ans% " " + } + line := + ini++ + } +} +MsgBox % result diff --git a/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat new file mode 100644 index 0000000000..707de0dc95 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat @@ -0,0 +1,22 @@ +@echo off +setlocal ENABLEDELAYEDEXPANSION +set n=15 +set /A nn=n+1 +for /L %%i in (0,1,%nn%) do set t.%%i=0 +set t.1=1 +for /L %%i in (1,1,%n%) do ( + set /A ip=%%i+1 + for /L %%j in (%%i,-1,1) do ( + set /A jm=%%j-1 + set /A t.%%j=t.%%j+t.!jm! + ) + set /A t.!ip!=t.%%i + for /L %%j in (!ip!,-1,1) do ( + set /A jm=%%j-1 + set /A t.%%j=t.%%j+t.!jm! + ) + set /A ci=t.!ip!-t.%%i + echo !ci! + ) +) +pause diff --git a/Task/Catalan-numbers-Pascals-triangle/C++/catalan-numbers-pascals-triangle.cpp b/Task/Catalan-numbers-Pascals-triangle/C++/catalan-numbers-pascals-triangle.cpp new file mode 100644 index 0000000000..ebe93400fe --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/C++/catalan-numbers-pascals-triangle.cpp @@ -0,0 +1,16 @@ +// Generate Catalan Numbers +// +// Nigel Galloway: June 9th., 2012 +// +#include +int main() { + const int N = 15; + int t[N+2] = {0,1}; + for(int i = 1; i<=N; i++){ + for(int j = i; j>1; j--) t[j] = t[j] + t[j-1]; + t[i+1] = t[i]; + for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1]; + std::cout << t[i+1] - t[i] << " "; + } + return 0; +} diff --git a/Task/Catalan-numbers-Pascals-triangle/D/catalan-numbers-pascals-triangle.d b/Task/Catalan-numbers-Pascals-triangle/D/catalan-numbers-pascals-triangle.d new file mode 100644 index 0000000000..b52111b17e --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/D/catalan-numbers-pascals-triangle.d @@ -0,0 +1,16 @@ +void main() { + import std.stdio; + + enum uint N = 15; + uint[N + 2] t; + t[1] = 1; + + foreach (immutable i; 1 .. N + 1) { + foreach_reverse (immutable j; 2 .. i + 1) + t[j] += t[j - 1]; + t[i + 1] = t[i]; + foreach_reverse (immutable j; 2 .. i + 2) + t[j] += t[j - 1]; + write(t[i + 1] - t[i], ' '); + } +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Icon/catalan-numbers-pascals-triangle.icon b/Task/Catalan-numbers-Pascals-triangle/Icon/catalan-numbers-pascals-triangle.icon new file mode 100644 index 0000000000..9dfc2abb14 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Icon/catalan-numbers-pascals-triangle.icon @@ -0,0 +1,6 @@ +link math + +procedure main(A) + limit := (integer(A[1])|15)+1 + every write(right(binocoef(i := 2*seq(0)\limit,i/2)-binocoef(i,i/2+1),30)) +end diff --git a/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-1.j b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-1.j new file mode 100644 index 0000000000..2840b18d2c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-1.j @@ -0,0 +1 @@ + Catalan=. }:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\@]^:[ #&1)@:(2&+) diff --git a/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-2.j b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-2.j new file mode 100644 index 0000000000..3c4559326a --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-2.j @@ -0,0 +1,2 @@ + Catalan 15 +1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 diff --git a/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-3.j b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-3.j new file mode 100644 index 0000000000..ce10b418ae --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/J/catalan-numbers-pascals-triangle-3.j @@ -0,0 +1,17 @@ + o=. @: NB. Composition of verbs (functions) + ( PascalTriangle=. i. ((+/\@]^:[)) #&1 ) 5 +1 1 1 1 1 +1 2 3 4 5 +1 3 6 10 15 +1 4 10 20 35 +1 5 15 35 70 + ( MiddleDiagonal=. (<0 1)&|: ) o PascalTriangle 5 +1 2 6 20 70 + ( AdjacentLeft=. MiddleDiagonal o (2&|.) ) o PascalTriangle 5 +1 4 15 1 5 + + ( Catalan=. }: o (}. o MiddleDiagonal - }: o AdjacentLeft) o PascalTriangle o (2&+) f. ) 5 +1 2 5 14 42 + + Catalan +}:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\@]^:[ #&1)@:(2&+) diff --git a/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m b/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m new file mode 100644 index 0000000000..1b5fe4428b --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m @@ -0,0 +1,2 @@ +p = pascal(17); +diag(p(2:end-1,2:end-1))-diag(p,2) diff --git a/Task/Catalan-numbers-Pascals-triangle/Mathematica/catalan-numbers-pascals-triangle.math b/Task/Catalan-numbers-Pascals-triangle/Mathematica/catalan-numbers-pascals-triangle.math new file mode 100644 index 0000000000..fb0fc1cdbf --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Mathematica/catalan-numbers-pascals-triangle.math @@ -0,0 +1,16 @@ +nextrow[lastrow_] := Module[{output}, + output = ConstantArray[1, Length[lastrow] + 1]; + Do[ + output[[i + 1]] = lastrow[[i]] + lastrow[[i + 1]]; + , {i, 1, Length[lastrow] - 1}]; + output + ] +pascaltriangle[size_] := NestList[nextrow, {1}, size] +catalannumbers[length_] := Module[{output, basetriangle}, + basetriangle = pascaltriangle[2 length]; + list1 = basetriangle[[# *2 + 1, # + 1]] & /@ Range[length]; + list2 = basetriangle[[# *2 + 1, # + 2]] & /@ Range[length]; + list1 - list2 + ] +(* testing *) +catalannumbers[15] diff --git a/Task/Catalan-numbers-Pascals-triangle/PARI-GP/catalan-numbers-pascals-triangle.pari b/Task/Catalan-numbers-Pascals-triangle/PARI-GP/catalan-numbers-pascals-triangle.pari new file mode 100644 index 0000000000..da4a89992c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/PARI-GP/catalan-numbers-pascals-triangle.pari @@ -0,0 +1 @@ +vector(15,n,binomial(2*n,n)-binomial(2*n,n+1)) diff --git a/Task/Catalan-numbers-Pascals-triangle/Pascal/catalan-numbers-pascals-triangle.pascal b/Task/Catalan-numbers-Pascals-triangle/Pascal/catalan-numbers-pascals-triangle.pascal new file mode 100644 index 0000000000..abf92bcde8 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Pascal/catalan-numbers-pascals-triangle.pascal @@ -0,0 +1,35 @@ +type + tElement = Uint64; +var + Catalan : array[0..50] of tElement; +procedure GetCatalan(L:longint); +var + PasTri : array[0..100] of tElement; + j,k: longInt; +begin + l := l*2; + PasTri[0] := 1; + j := 0; + while (j @p { [0, @p Z+ @p, 0] } ... *; + +constant @catalan = gather for 2, 4 ... * -> $ix { + my @row := @pascal[$ix]; + my $mid = +@row div 2; + take [-] @row[$mid, $mid+1] +} + +.say for @catalan[^20]; diff --git a/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-1.pl b/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-1.pl new file mode 100644 index 0000000000..35bd99f67a --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-1.pl @@ -0,0 +1,8 @@ +use constant N => 15; +my @t = (0, 1); +for(my $i = 1; $i <= N; $i++) { + for(my $j = $i; $j > 1; $j--) { $t[$j] += $t[$j-1] } + $t[$i+1] = $t[$i]; + for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] } + print $t[$i+1] - $t[$i], " "; +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-2.pl b/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-2.pl new file mode 100644 index 0000000000..e43addfd99 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Perl/catalan-numbers-pascals-triangle-2.pl @@ -0,0 +1,2 @@ +use ntheory qw/binomial/; +print join(" ", map { binomial( 2*$_, $_) / ($_+1) } 1 .. 1000), "\n"; diff --git a/Task/Catalan-numbers-Pascals-triangle/PicoLisp/catalan-numbers-pascals-triangle.l b/Task/Catalan-numbers-Pascals-triangle/PicoLisp/catalan-numbers-pascals-triangle.l new file mode 100644 index 0000000000..6c729b7c0c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/PicoLisp/catalan-numbers-pascals-triangle.l @@ -0,0 +1,14 @@ +(de bino (N K) + (let f + '((N) + (if (=0 N) 1 (apply * (range 1 N))) ) + (/ + (f N) + (* (f (- N K)) (f K)) ) ) ) + +(for N 15 + (println + (- + (bino (* 2 N) N) + (bino (* 2 N) (inc N)) ) ) ) +(bye) diff --git a/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py new file mode 100644 index 0000000000..8d350427f3 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py @@ -0,0 +1,12 @@ +>>> n = 15 +>>> t = [0] * (n + 2) +>>> t[1] = 1 +>>> for i in range(1, n + 1): + for j in range(i, 1, -1): t[j] += t[j - 1] + t[i + 1] = t[i] + for j in range(i + 1, 1, -1): t[j] += t[j - 1] + print(t[i+1] - t[i], end=' ') + + +1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 +>>> diff --git a/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-2.py b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-2.py new file mode 100644 index 0000000000..d9433c0b39 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-2.py @@ -0,0 +1,9 @@ +def catalan_number(n): + nm = dm = 1 + for k in range(2, n+1): + nm, dm = ( nm*(n+k), dm*k ) + return nm/dm + +print [catalan_number(n) for n in range(1, 16)] + +[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845] diff --git a/Task/Catalan-numbers-Pascals-triangle/README b/Task/Catalan-numbers-Pascals-triangle/README new file mode 100644 index 0000000000..575be07775 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Catalan_numbers/Pascal's_triangle diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx new file mode 100644 index 0000000000..2501989058 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx @@ -0,0 +1,10 @@ +/*REXX program obtains Catalan numbers from Pascal's triangle. */ +parse arg N .; if N=='' then N=15 /*Any args? No, then use default*/ +numeric digits max(9,N%2+N%8) /*can handle huge Catalan numbers*/ +@.=0; @.1=1 /*stem array default; 1st value.*/ + + do i=1 for N; ip=i+1 + do j=i by -1 for N; jm=j-1; @.j=@.j+@.jm; end /*j*/ + @.ip=@.i; do k=ip by -1 for N; km=k-1; @.k=@.k+@.km; end /*k*/ + say @.ip-@.i /*display the Ith Catalan number.*/ + end /*i*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx new file mode 100644 index 0000000000..50a8f6eb43 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx @@ -0,0 +1,14 @@ +/*REXX program obtains/displays Catalan numbers from Pascal's triangle.*/ +parse arg N .; if N=='' then N=15 /*Any args? No, then use default*/ +numeric digits max(9,N%2+N%8) /*can handle huge Catalan numbers*/ +@.=0; @.1=1 /*stem array default; 1st value.*/ + + do i=1 for N; ip=i+1 + do j=i by -1 for N; @.j=@.j+@(j-1); end /*j*/ + @.ip=@.i; do k=ip by -1 for N; @.k=@.k+@(k-1); end /*k*/ + say @.ip-@.i /*display the Ith Catalan number.*/ + end /*i*/ + +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────@ subroutine────────────────────────*/ +@: parse arg !; return @.! /*return the value of @.[arg(1)]*/ diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx new file mode 100644 index 0000000000..6029424bf7 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx @@ -0,0 +1,13 @@ +/*REXX program obtains/displays Catalan numbers from Pascal's triangle.*/ +parse arg N .; if N=='' then N=15 /*Any args? No, then use default*/ +numeric digits max(9,N*4) /*can handle huge Catalan numbers*/ + + do j=1 for N /* [↓] show N Catalan numbers*/ + say comb(j+j,j) % (j+1) /*display the Jth Catalan number.*/ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────! (factorial) function──────────────*/ +!: procedure; parse arg z; _=1; do j=1 for arg(1); _=_*j; end; return _ +/*──────────────────────────────────COMB (binomial coefficient) function*/ +comb: procedure; parse arg x,y; if x=y then return 1; if y>x then return 0 +if x-yx then return 0 +if x-y '(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 +;; 2674440 9694845) diff --git a/Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb b/Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb new file mode 100644 index 0000000000..fa0d6665b6 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb @@ -0,0 +1,11 @@ +def catalan(num) + t = [0, 1] #grows as needed + 1.upto(num).map do |i| + i.downto(1){|j| t[j] += t[j-1]} + t[i+1] = t[i] + (i+1).downto(1) {|j| t[j] += t[j-1]} + t[i+1] - t[i] + end +end + +puts catalan(15).join(", ") diff --git a/Task/Catalan-numbers-Pascals-triangle/Run-BASIC/catalan-numbers-pascals-triangle.run b/Task/Catalan-numbers-Pascals-triangle/Run-BASIC/catalan-numbers-pascals-triangle.run new file mode 100644 index 0000000000..bf3ec0093e --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Run-BASIC/catalan-numbers-pascals-triangle.run @@ -0,0 +1,9 @@ +n = 15 +dim t(n+2) +t(1) = 1 +for i = 1 to n + for j = i to 1 step -1 : t(j) = t(j) + t(j-1): next j + t(i+1) = t(i) + for j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j +print t(i+1) - t(i);" "; +next i diff --git a/Task/Catalan-numbers-Pascals-triangle/Scilab/catalan-numbers-pascals-triangle.scilab b/Task/Catalan-numbers-Pascals-triangle/Scilab/catalan-numbers-pascals-triangle.scilab new file mode 100644 index 0000000000..4ae8f5651a --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Scilab/catalan-numbers-pascals-triangle.scilab @@ -0,0 +1,13 @@ +n=15 +t=zeros(1,n+2) +t(1)=1 +for i=1:n + for j=i+1:-1:2 + t(j)=t(j)+t(j-1) + end + t(i+1)=t(i) + for j=i+2:-1:2 + t(j)=t(j)+t(j-1) + end + disp(t(i+1)-t(i)) +end diff --git a/Task/Catalan-numbers-Pascals-triangle/Seed7/catalan-numbers-pascals-triangle.seed7 b/Task/Catalan-numbers-Pascals-triangle/Seed7/catalan-numbers-pascals-triangle.seed7 new file mode 100644 index 0000000000..7e717c8254 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Seed7/catalan-numbers-pascals-triangle.seed7 @@ -0,0 +1,21 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const integer: N is 15; + var array integer: t is [] (1) & N times 0; + var integer: i is 0; + var integer: j is 0; + begin + for i range 1 to N do + for j range i downto 2 do + t[j] +:= t[j - 1]; + end for; + t[i + 1] := t[i]; + for j range i + 1 downto 2 do + t[j] +:= t[j - 1]; + end for; + write(t[i + 1] - t[i] <& " "); + end for; + writeln; + end func; diff --git a/Task/Catalan-numbers-Pascals-triangle/TI-83-BASIC/catalan-numbers-pascals-triangle.ti-83 b/Task/Catalan-numbers-Pascals-triangle/TI-83-BASIC/catalan-numbers-pascals-triangle.ti-83 new file mode 100644 index 0000000000..80a7ded826 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/TI-83-BASIC/catalan-numbers-pascals-triangle.ti-83 @@ -0,0 +1,14 @@ +"CATALAN +15→N +seq(0,I,1,N+2)→L1 +1→L1(1) +For(I,1,N) +For(J,I+1,2,-1) +L1(J)+L1(J-1)→L1(J) +End +L1(I)→L1(I+1) +For(J,I+2,2,-1) +L1(J)+L1(J-1)→L1(J) +End +Disp L1(I+1)-L1(I) +End diff --git a/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl b/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl new file mode 100644 index 0000000000..4af0c8f296 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl @@ -0,0 +1,13 @@ +proc catalan n { + set result {} + array set t {0 0 1 1} + for {set i 1} {[set k $i] <= $n} {incr i} { + for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])} + set t([incr k]) $t($i) + for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])} + lappend result [expr {$t($k) - $t($i)}] + } + return $result +} + +puts [catalan 15] diff --git a/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vb b/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vb new file mode 100644 index 0000000000..9483b61427 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vb @@ -0,0 +1,20 @@ +dim t() +if Wscript.arguments.count=1 then + n=Wscript.arguments.item(0) +else + n=15 +end if +redim t(n+1) +'t(*)=0 +t(1)=1 +for i=1 to n + ip=i+1 + for j = i to 1 step -1 + t(j)=t(j)+t(j-1) + next 'j + t(i+1)=t(i) + for j = i+1 to 1 step -1 + t(j)=t(j)+t(j-1) + next 'j + Wscript.echo t(i+1)-t(i) +next 'i diff --git a/Task/Catalan-numbers-Pascals-triangle/Visual-Basic/catalan-numbers-pascals-triangle.vb b/Task/Catalan-numbers-Pascals-triangle/Visual-Basic/catalan-numbers-pascals-triangle.vb new file mode 100644 index 0000000000..de9852961c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Visual-Basic/catalan-numbers-pascals-triangle.vb @@ -0,0 +1,16 @@ +Sub catalan() + Const n = 15 + Dim t(n + 2) As Long + Dim i As Integer, j As Integer + t(1) = 1 + For i = 1 To n + For j = i + 1 To 2 Step -1 + t(j) = t(j) + t(j - 1) + Next j + t(i + 1) = t(i) + For j = i + 2 To 2 Step -1 + t(j) = t(j) + t(j - 1) + Next j + Debug.Print i, t(i + 1) - t(i) + Next i +End Sub 'catalan diff --git a/Task/Catamorphism/00DESCRIPTION b/Task/Catamorphism/00DESCRIPTION new file mode 100644 index 0000000000..7733020350 --- /dev/null +++ b/Task/Catamorphism/00DESCRIPTION @@ -0,0 +1,7 @@ +''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. + +Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. + +;Cf. +* [[wp:Fold (higher-order function)|Fold]] +* [[wp:Catamorphism|Catamorphism]] diff --git a/Task/Catamorphism/Ada/catamorphism.ada b/Task/Catamorphism/Ada/catamorphism.ada new file mode 100644 index 0000000000..2c85c94544 --- /dev/null +++ b/Task/Catamorphism/Ada/catamorphism.ada @@ -0,0 +1,29 @@ +with Ada.Text_IO; + +procedure Catamorphism is + + type Fun is access function (Left, Right: Natural) return Natural; + type Arr is array(Natural range <>) of Natural; + + function Fold_Left (F: Fun; A: Arr) return Natural is + Result: Natural := A(A'First); + begin + for I in A'First+1 .. A'Last loop + Result := F(Result, A(I)); + end loop; + return Result; + end Fold_Left; + + function Max (L, R: Natural) return Natural is (if L > R then L else R); + function Min (L, R: Natural) return Natural is (if L < R then L else R); + function Add (Left, Right: Natural) return Natural is (Left + Right); + function Mul (Left, Right: Natural) return Natural is (Left * Right); + + package NIO is new Ada.Text_IO.Integer_IO(Natural); + +begin + NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3); + NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3); + NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3); + NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3); +end Catamorphism; diff --git a/Task/Catamorphism/Bracmat/catamorphism.bracmat b/Task/Catamorphism/Bracmat/catamorphism.bracmat new file mode 100644 index 0000000000..06ed87e08b --- /dev/null +++ b/Task/Catamorphism/Bracmat/catamorphism.bracmat @@ -0,0 +1,18 @@ +( ( fold + = f xs init first rest + . !arg:(?f.?xs.?init) + & ( !xs:&!init + | !xs:%?first ?rest + & !f$(!first.fold$(!f.!rest.!init)) + ) + ) +& out + $ ( fold + $ ( (=a b.!arg:(?a.?b)&!a+!b) + . 1 2 3 4 5 + . 0 + ) + ) +& (product=a b.!arg:(?a.?b)&!a*!b) +& out$(fold$(product.1 2 3 4 5.1)) +); diff --git a/Task/Catamorphism/C++/catamorphism.cpp b/Task/Catamorphism/C++/catamorphism.cpp new file mode 100644 index 0000000000..717d203a67 --- /dev/null +++ b/Task/Catamorphism/C++/catamorphism.cpp @@ -0,0 +1,14 @@ +#include +#include +#include +#include + +int main() { + std::vector nums = { 1, 2, 3, 4, 5 }; + auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus()); + auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) { + return a + 2 * b; + }); + std::cout << "nums_added: " << nums_added << std::endl; + std::cout << "nums_other: " << nums_other << std::endl; +} diff --git a/Task/Catamorphism/C-sharp/catamorphism.cs b/Task/Catamorphism/C-sharp/catamorphism.cs new file mode 100644 index 0000000000..c338f2cf68 --- /dev/null +++ b/Task/Catamorphism/C-sharp/catamorphism.cs @@ -0,0 +1,9 @@ +var nums = Enumerable.Range(1, 10); + +int summation = nums.Aggregate((a, b) => a + b); + +int product = nums.Aggregate((a, b) => a * b); + +string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString()); + +Console.WriteLine("{0} {1} {2}", summation, product, concatenation); diff --git a/Task/Catamorphism/C/catamorphism.c b/Task/Catamorphism/C/catamorphism.c new file mode 100644 index 0000000000..b138b4c500 --- /dev/null +++ b/Task/Catamorphism/C/catamorphism.c @@ -0,0 +1,24 @@ +#include + +typedef int (*intFn)(int, int); + +int reduce(intFn fn, int size, int *elms) +{ + int i, val = *elms; + for (i = 1; i < size; ++i) + val = fn(val, elms[i]); + return val; +} + +int add(int a, int b) { return a + b; } +int sub(int a, int b) { return a - b; } +int mul(int a, int b) { return a * b; } + +int main(void) +{ + int nums[] = {1, 2, 3, 4, 5}; + printf("%d\n", reduce(add, 5, nums)); + printf("%d\n", reduce(sub, 5, nums)); + printf("%d\n", reduce(mul, 5, nums)); + return 0; +} diff --git a/Task/Catamorphism/Clojure/catamorphism.clj b/Task/Catamorphism/Clojure/catamorphism.clj new file mode 100644 index 0000000000..16ef8a4941 --- /dev/null +++ b/Task/Catamorphism/Clojure/catamorphism.clj @@ -0,0 +1,6 @@ +; Basic usage +> (reduce * '(1 2 3 4 5)) +120 +; Using an initial value +> (reduce + 100 '(1 2 3 4 5)) +115 diff --git a/Task/Catamorphism/Common-Lisp/catamorphism.lisp b/Task/Catamorphism/Common-Lisp/catamorphism.lisp new file mode 100644 index 0000000000..e7588863c4 --- /dev/null +++ b/Task/Catamorphism/Common-Lisp/catamorphism.lisp @@ -0,0 +1,18 @@ +; Basic usage +> (reduce #'* '(1 2 3 4 5)) +120 +; Using an initial value +> (reduce #'+ '(1 2 3 4 5) :initial-value 100) +115 +; Using only a subsequence +> (reduce #'+ '(1 2 3 4 5) :start 1 :end 4) +9 +; Apply a function to each element first +> (reduce #'+ '((a 1) (b 2) (c 3)) :key #'cadr) +6 +; Right-associative reduction +> (reduce #'expt '(2 3 4) :from-end T) +2417851639229258349412352 +; Compare with +> (reduce #'expt '(2 3 4)) +4096 diff --git a/Task/Catamorphism/D/catamorphism.d b/Task/Catamorphism/D/catamorphism.d new file mode 100644 index 0000000000..b3250b1344 --- /dev/null +++ b/Task/Catamorphism/D/catamorphism.d @@ -0,0 +1,13 @@ +void main() { + import std.stdio, std.algorithm, std.range, std.numeric, + std.conv, std.typecons, std.typetuple; + + auto list = iota(1, 11); + alias ops = TypeTuple!(q{a + b}, q{a * b}, min, max, gcd); + + foreach (op; ops) + writeln(op.stringof, ": ", list.reduce!op); + + // std.algorithm.reduce supports multiple functions in parallel: + reduce!(ops[0], ops[3], text)(tuple(0, 0.0, ""), list).writeln; +} diff --git a/Task/Catamorphism/Deja-Vu/catamorphism.djv b/Task/Catamorphism/Deja-Vu/catamorphism.djv new file mode 100644 index 0000000000..ed4bf686b7 --- /dev/null +++ b/Task/Catamorphism/Deja-Vu/catamorphism.djv @@ -0,0 +1,8 @@ +reduce f lst init: + if lst: + f reduce @f lst init pop-from lst + else: + init + +!. reduce @+ [ 1 10 200 ] 4 +!. reduce @- [ 1 10 200 ] 4 diff --git a/Task/Catamorphism/Go/catamorphism.go b/Task/Catamorphism/Go/catamorphism.go new file mode 100644 index 0000000000..2ce2a1f3a5 --- /dev/null +++ b/Task/Catamorphism/Go/catamorphism.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" +) + +func main() { + n := []int{1, 2, 3, 4, 5} + + fmt.Println(reduce(add, n)) + fmt.Println(reduce(sub, n)) + fmt.Println(reduce(mul, n)) +} + +func add(a int, b int) int { return a + b } +func sub(a int, b int) int { return a - b } +func mul(a int, b int) int { return a * b } + +func reduce(rf func(int, int) int, m []int) int { + r := m[0] + for _, v := range m[1:] { + r = rf(r, v) + } + return r +} diff --git a/Task/Catamorphism/Haskell/catamorphism.hs b/Task/Catamorphism/Haskell/catamorphism.hs new file mode 100644 index 0000000000..ef45bac964 --- /dev/null +++ b/Task/Catamorphism/Haskell/catamorphism.hs @@ -0,0 +1,5 @@ +nums = [1..10] + +summation = foldl (+) 0 nums +product = foldl (*) 1 nums +concatenation = foldr (\num s -> show num ++ s) "" nums diff --git a/Task/Catamorphism/Icon/catamorphism.icon b/Task/Catamorphism/Icon/catamorphism.icon new file mode 100644 index 0000000000..df10619784 --- /dev/null +++ b/Task/Catamorphism/Icon/catamorphism.icon @@ -0,0 +1,9 @@ +procedure main(A) + write(A[1],": ",curry(A[1],A[2:0])) +end + +procedure curry(f,A) + r := A[1] + every r := f(r, !A[2:0]) + return r +end diff --git a/Task/Catamorphism/J/catamorphism-1.j b/Task/Catamorphism/J/catamorphism-1.j new file mode 100644 index 0000000000..815c566da1 --- /dev/null +++ b/Task/Catamorphism/J/catamorphism-1.j @@ -0,0 +1 @@ + / diff --git a/Task/Catamorphism/J/catamorphism-2.j b/Task/Catamorphism/J/catamorphism-2.j new file mode 100644 index 0000000000..55ceae8140 --- /dev/null +++ b/Task/Catamorphism/J/catamorphism-2.j @@ -0,0 +1,6 @@ + +/ 1 2 3 4 5 +15 + */ 1 2 3 4 5 +120 + !/ 1 2 3 4 5 NB. "n ! k" is "n choose k" +45 diff --git a/Task/Catamorphism/Java/catamorphism.java b/Task/Catamorphism/Java/catamorphism.java new file mode 100644 index 0000000000..37b969c292 --- /dev/null +++ b/Task/Catamorphism/Java/catamorphism.java @@ -0,0 +1,9 @@ +import java.util.stream.Stream; + +public class ReduceTask { + + public static void main(String[] args) { + System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum()); + System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b)); + } +} diff --git a/Task/Catamorphism/JavaScript/catamorphism.js b/Task/Catamorphism/JavaScript/catamorphism.js new file mode 100644 index 0000000000..14cd44d157 --- /dev/null +++ b/Task/Catamorphism/JavaScript/catamorphism.js @@ -0,0 +1,17 @@ +var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + +function add(a, b) { + return a + b; +} + +var summation = nums.reduce(add); + +function mul(a, b) { + return a * b; +} + +var product = nums.reduce(mul, 1); + +var concatenation = nums.reduce(add, ""); + +console.log(summation, product, concatenation); diff --git a/Task/Catamorphism/LOLCODE/catamorphism.lol b/Task/Catamorphism/LOLCODE/catamorphism.lol new file mode 100644 index 0000000000..9722693425 --- /dev/null +++ b/Task/Catamorphism/LOLCODE/catamorphism.lol @@ -0,0 +1,27 @@ +HAI 1.3 + +HOW IZ I reducin YR array AN YR size AN YR fn + I HAS A val ITZ array'Z SRS 0 + IM IN YR loop UPPIN YR i TIL BOTH SAEM i AN DIFF OF size AN 1 + val R I IZ fn YR val AN YR array'Z SRS SUM OF i AN 1 MKAY + IM OUTTA YR loop + FOUND YR val +IF U SAY SO + +O HAI IM array + I HAS A SRS 0 ITZ 1 + I HAS A SRS 1 ITZ 2 + I HAS A SRS 2 ITZ 3 + I HAS A SRS 3 ITZ 4 + I HAS A SRS 4 ITZ 5 +KTHX + +HOW IZ I add YR a AN YR b, FOUND YR SUM OF a AN b, IF U SAY SO +HOW IZ I sub YR a AN YR b, FOUND YR DIFF OF a AN b, IF U SAY SO +HOW IZ I mul YR a AN YR b, FOUND YR PRODUKT OF a AN b, IF U SAY SO + +VISIBLE I IZ reducin YR array AN YR 5 AN YR add MKAY +VISIBLE I IZ reducin YR array AN YR 5 AN YR sub MKAY +VISIBLE I IZ reducin YR array AN YR 5 AN YR mul MKAY + +KTHXBYE diff --git a/Task/Catamorphism/Logtalk/catamorphism.logtalk b/Task/Catamorphism/Logtalk/catamorphism.logtalk new file mode 100644 index 0000000000..a0fb336608 --- /dev/null +++ b/Task/Catamorphism/Logtalk/catamorphism.logtalk @@ -0,0 +1,14 @@ +:- object(folding_examples). + + :- public(show/0). + show :- + integer::sequence(1, 10, List), + write('List: '), write(List), nl, + meta::fold_left([Acc,N,Sum0]>>(Sum0 is Acc+N), 0, List, Sum), + write('Sum of all elements: '), write(Sum), nl, + meta::fold_left([Acc,N,Product0]>>(Product0 is Acc*N), 1, List, Product), + write('Product of all elements: '), write(Product), nl, + meta::fold_left([Acc,N,Concat0]>>(number_codes(N,NC), atom_codes(NA,NC), atom_concat(Acc,NA,Concat0)), '', List, Concat), + write('Concatenation of all elements: '), write(Concat), nl. + +:- end_object. diff --git a/Task/Catamorphism/Maple/catamorphism-1.maple b/Task/Catamorphism/Maple/catamorphism-1.maple new file mode 100644 index 0000000000..3bb4eb67e8 --- /dev/null +++ b/Task/Catamorphism/Maple/catamorphism-1.maple @@ -0,0 +1,8 @@ +> nums := seq( 1 .. 10 ); + nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 + +> foldl( `+`, 0, nums ); # compute sum using foldl + 55 + +> foldr( `*`, 1, nums ); # compute product using foldr + 3628800 diff --git a/Task/Catamorphism/Maple/catamorphism-2.maple b/Task/Catamorphism/Maple/catamorphism-2.maple new file mode 100644 index 0000000000..6063a01d6e --- /dev/null +++ b/Task/Catamorphism/Maple/catamorphism-2.maple @@ -0,0 +1,2 @@ +> foldl( (a,b) ->a*T+b, op(map2(op,1,[op( 72*T^5+37*T^4-23*T^3+87*T^2+44*T+29 )]))); + ((((72 T + 37) T - 23) T + 87) T + 44) T + 29 diff --git a/Task/Catamorphism/Mathematica/catamorphism.math b/Task/Catamorphism/Mathematica/catamorphism.math new file mode 100644 index 0000000000..41463b9cef --- /dev/null +++ b/Task/Catamorphism/Mathematica/catamorphism.math @@ -0,0 +1 @@ +Fold[f, x, {a, b, c, d}] diff --git a/Task/Catamorphism/Maxima/catamorphism-1.maxima b/Task/Catamorphism/Maxima/catamorphism-1.maxima new file mode 100644 index 0000000000..b9d07ca4da --- /dev/null +++ b/Task/Catamorphism/Maxima/catamorphism-1.maxima @@ -0,0 +1,2 @@ +lreduce(f, [a, b, c, d], x0); +/* (%o1) f(f(f(f(x0, a), b), c), d) */ diff --git a/Task/Catamorphism/Maxima/catamorphism-2.maxima b/Task/Catamorphism/Maxima/catamorphism-2.maxima new file mode 100644 index 0000000000..013e012425 --- /dev/null +++ b/Task/Catamorphism/Maxima/catamorphism-2.maxima @@ -0,0 +1,2 @@ +lreduce("+", [1, 2, 3, 4], 100); +/* (%o1) 110 */ diff --git a/Task/Catamorphism/Nemerle/catamorphism.nemerle b/Task/Catamorphism/Nemerle/catamorphism.nemerle new file mode 100644 index 0000000000..48bbff8f3b --- /dev/null +++ b/Task/Catamorphism/Nemerle/catamorphism.nemerle @@ -0,0 +1,2 @@ +def seq = [1, 4, 6, 3, 7]; +def sum = seq.Fold(0, _ + _); // Fold takes an initial value and a function, here the + operator diff --git a/Task/Catamorphism/OCaml/catamorphism.ocaml b/Task/Catamorphism/OCaml/catamorphism.ocaml new file mode 100644 index 0000000000..930dd01c5c --- /dev/null +++ b/Task/Catamorphism/OCaml/catamorphism.ocaml @@ -0,0 +1,6 @@ +# let nums = [1;2;3;4;5;6;7;8;9;10];; +val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] +# let sum = List.fold_left (+) 0 nums;; +val sum : int = 55 +# let product = List.fold_left ( * ) 1 nums;; +val product : int = 3628800 diff --git a/Task/Catamorphism/Oberon-2/catamorphism.oberon-2 b/Task/Catamorphism/Oberon-2/catamorphism.oberon-2 new file mode 100644 index 0000000000..0caad9dedd --- /dev/null +++ b/Task/Catamorphism/Oberon-2/catamorphism.oberon-2 @@ -0,0 +1,72 @@ +MODULE Catamorphism; +IMPORT + Object, + NPCT:Tools, + NPCT:Args, + IntStr, + Out; + +TYPE + BinaryFunc= PROCEDURE (x,y: LONGINT): LONGINT; + +VAR + data: POINTER TO ARRAY OF LONGINT; + i: LONGINT; + + PROCEDURE Sum(x,y: LONGINT): LONGINT; + BEGIN + RETURN x + y + END Sum; + + PROCEDURE Sub(x,y: LONGINT): LONGINT; + BEGIN + RETURN x - y; + END Sub; + + PROCEDURE Mul(x,y: LONGINT): LONGINT; + BEGIN + RETURN x * y; + END Mul; + + PROCEDURE Reduce(x: ARRAY OF LONGINT; f: BinaryFunc): LONGINT; + VAR + i,res: LONGINT; + BEGIN + res := x[0];i := 1; + WHILE (i < LEN(x)) DO; + res := f(res,x[i]); + INC(i) + END; + RETURN res + END Reduce; + + PROCEDURE InitData(VAR x: ARRAY OF LONGINT); + VAR + i, j: LONGINT; + res: IntStr.ConvResults; + aux: Object.CharsLatin1; + BEGIN + i := 0;j := 1; + WHILE (j <= LEN(x)) DO + aux := Tools.AsString(Args.Get(j)); + IntStr.StrToInt(aux^,x[i],res); + IF res # IntStr.strAllRight THEN + Out.String("Incorrect format for data at index ");Out.LongInt(j,0);Out.Ln; + HALT(1); + END; + INC(j);INC(i) + END + END InitData; + +BEGIN + IF Args.Number() = 1 THEN + Out.String("Invalid number of arguments. ");Out.Ln; + HALT(0) + ELSE + NEW(data,Args.Number() - 1); + InitData(data^); + Out.LongInt(Reduce(data^,Sum),0);Out.Ln; + Out.LongInt(Reduce(data^,Sub),0);Out.Ln; + Out.LongInt(Reduce(data^,Mul),0);Out.Ln + END +END Catamorphism. diff --git a/Task/Catamorphism/PARI-GP/catamorphism-1.pari b/Task/Catamorphism/PARI-GP/catamorphism-1.pari new file mode 100644 index 0000000000..63f5d0c78c --- /dev/null +++ b/Task/Catamorphism/PARI-GP/catamorphism-1.pari @@ -0,0 +1,6 @@ +reduce(f, v)={ + my(t=v[1]); + for(i=2,#v,t=f(t,v[i])); + t +}; +reduce((a,b)->a+b, [1,2,3,4,5,6,7,8,9,10]) diff --git a/Task/Catamorphism/PARI-GP/catamorphism-2.pari b/Task/Catamorphism/PARI-GP/catamorphism-2.pari new file mode 100644 index 0000000000..aeb75fd994 --- /dev/null +++ b/Task/Catamorphism/PARI-GP/catamorphism-2.pari @@ -0,0 +1 @@ +fold((a,b)->a+b, [1..10]) diff --git a/Task/Catamorphism/Pascal/catamorphism.pascal b/Task/Catamorphism/Pascal/catamorphism.pascal new file mode 100644 index 0000000000..8d7c91f179 --- /dev/null +++ b/Task/Catamorphism/Pascal/catamorphism.pascal @@ -0,0 +1,53 @@ +program reduce; + +type +// tmyArray = array of LongInt; + tmyArray = array[-5..5] of LongInt; + tmyFunc = function (a,b:LongInt):LongInt; + +function add(x,y:LongInt):LongInt; +begin + add := x+y; +end; + +function sub(k,l:LongInt):LongInt; +begin + sub := k-l; +end; + +function mul(r,t:LongInt):LongInt; +begin + mul := r*t; +end; + +function reduce(myFunc:tmyFunc;a:tmyArray):LongInt; +var + i,res : LongInt; +begin + res := a[low(a)]; + For i := low(a)+1 to high(a) do + res := myFunc(res,a[i]); + reduce := res; +end; + +procedure InitMyArray(var a:tmyArray); +var + i: LongInt; +begin + For i := low(a) to high(a) do + begin + //no a[i] = 0 + a[i] := i + ord(i=0); + write(a[i],','); + end; + writeln(#8#32); +end; + +var + ma : tmyArray; +BEGIN + InitMyArray(ma); + writeln(reduce(@add,ma)); + writeln(reduce(@sub,ma)); + writeln(reduce(@mul,ma)); +END. diff --git a/Task/Catamorphism/Perl-6/catamorphism-1.pl6 b/Task/Catamorphism/Perl-6/catamorphism-1.pl6 new file mode 100644 index 0000000000..dfe0921307 --- /dev/null +++ b/Task/Catamorphism/Perl-6/catamorphism-1.pl6 @@ -0,0 +1,7 @@ +my @list = 1..10; +say [+] @list; +say [*] @list; +say [~] @list; +say [min] @list; +say [max] @list; +say [lcm] @list; diff --git a/Task/Catamorphism/Perl-6/catamorphism-2.pl6 b/Task/Catamorphism/Perl-6/catamorphism-2.pl6 new file mode 100644 index 0000000000..f00c19588f --- /dev/null +++ b/Task/Catamorphism/Perl-6/catamorphism-2.pl6 @@ -0,0 +1,6 @@ +say reduce &infix:<+>, @list; +say reduce &infix:<*>, @list; +say reduce &infix:<~>, @list; +say reduce &infix:, @list; +say reduce &infix:, @list; +say reduce &infix:, @list; diff --git a/Task/Catamorphism/Perl/catamorphism.pl b/Task/Catamorphism/Perl/catamorphism.pl new file mode 100644 index 0000000000..2f02314d51 --- /dev/null +++ b/Task/Catamorphism/Perl/catamorphism.pl @@ -0,0 +1,8 @@ +use List::Util 'reduce'; + +# note the use of the odd $a and $b globals +print +(reduce {$a + $b} 1 .. 10), "\n"; + +# first argument is really an anon function; you could also do this: +sub func { $b & 1 ? "$a $b" : "$b $a" } +print +(reduce \&func, 1 .. 10), "\n" diff --git a/Task/Catamorphism/PicoLisp/catamorphism.l b/Task/Catamorphism/PicoLisp/catamorphism.l new file mode 100644 index 0000000000..0e94c058c7 --- /dev/null +++ b/Task/Catamorphism/PicoLisp/catamorphism.l @@ -0,0 +1,11 @@ +(de reduce ("Fun" "Lst") + (let "A" (car "Lst") + (for "N" (cdr "Lst") + (setq "A" ("Fun" "A" "N")) ) + "A" ) ) + +(println + (reduce + (1 2 3 4 5)) + (reduce * (1 2 3 4 5)) ) + +(bye) diff --git a/Task/Catamorphism/Prolog/catamorphism.pro b/Task/Catamorphism/Prolog/catamorphism.pro new file mode 100644 index 0000000000..51da2174d3 --- /dev/null +++ b/Task/Catamorphism/Prolog/catamorphism.pro @@ -0,0 +1,14 @@ +:- use_module(library(lambda)). + +% foldl is now a predicate of SWI-Prolog 6.3.1 +% +catamorphism :- + numlist(1,10,L), + foldl(\XS^YS^ZS^(ZS is XS+YS), L, 0, Sum), + format('Sum of ~w is ~w~n', [L, Sum]), + foldl(\XP^YP^ZP^(ZP is XP*YP), L, 1, Prod), + format('Prod of ~w is ~w~n', [L, Prod]), + string_to_list(LV, ""), + foldl(\XC^YC^ZC^(string_to_atom(XS, XC),string_concat(YC,XS,ZC)), + L, LV, Concat), + format('Concat of ~w is ~w~n', [L, Concat]). diff --git a/Task/Catamorphism/Python/catamorphism-1.py b/Task/Catamorphism/Python/catamorphism-1.py new file mode 100644 index 0000000000..bac5e8a046 --- /dev/null +++ b/Task/Catamorphism/Python/catamorphism-1.py @@ -0,0 +1,18 @@ +>>> from operator import add +>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']] +>>> help(reduce) +Help on built-in function reduce in module __builtin__: + +reduce(...) + reduce(function, sequence[, initial]) -> value + + Apply a function of two arguments cumulatively to the items of a sequence, + from left to right, so as to reduce the sequence to a single value. + For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates + ((((1+2)+3)+4)+5). If initial is present, it is placed before the items + of the sequence in the calculation, and serves as a default when the + sequence is empty. + +>>> reduce(add, listoflists, []) +['the', 'cat', 'sat', 'on', 'the', 'mat'] +>>> diff --git a/Task/Catamorphism/Python/catamorphism-2.py b/Task/Catamorphism/Python/catamorphism-2.py new file mode 100644 index 0000000000..543f12c042 --- /dev/null +++ b/Task/Catamorphism/Python/catamorphism-2.py @@ -0,0 +1,12 @@ +from functools import reduce +from operator import add, mul + +nums = range(1,11) + +summation = reduce(add, nums) + +product = reduce(mul, nums) + +concatenation = reduce(lambda a, b: str(a) + str(b), nums) + +print(summation, product, concatenation) diff --git a/Task/Catamorphism/README b/Task/Catamorphism/README new file mode 100644 index 0000000000..07c4e70add --- /dev/null +++ b/Task/Catamorphism/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Catamorphism diff --git a/Task/Catamorphism/REXX/catamorphism.rexx b/Task/Catamorphism/REXX/catamorphism.rexx new file mode 100644 index 0000000000..b3480e41f4 --- /dev/null +++ b/Task/Catamorphism/REXX/catamorphism.rexx @@ -0,0 +1,36 @@ +/*REXX pgm shows a method for catamorphism for some simple functions. */ +@list = 1 2 3 4 5 6 7 8 9 10 + say 'show:' fold(@list, 'show') + say ' sum:' fold(@list, '+') + say 'prod:' fold(@list, '*') + say ' cat:' fold(@list, '||') + say ' min:' fold(@list, 'min') + say ' max:' fold(@list, 'max') + say ' avg:' fold(@list, 'avg') + say ' GCD:' fold(@list, 'GCD') + say ' LCM:' fold(@list, 'LCM') +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────FOLD subroutine─────────────────────*/ +fold: procedure; parse arg z; arg ,f; z=space(z) /*F is uppercased.*/ +za=translate(z, f, " "); zf=f'('translate(z,',' ," ")')' +if f=='+' | f=='*' then interpret 'return' za +if f=='||' then return space(z,0) +if f=='AVG' then interpret 'return' fold(z,'+') "/" words(z) +if wordpos(f,'MIN MAX LCM GCD')\==0 then interpret 'return' zf +if f=='SHOW' then return z +return 'illegal function:' arg(2) +/*──────────────────────────────────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/Catamorphism/Racket/catamorphism.rkt b/Task/Catamorphism/Racket/catamorphism.rkt new file mode 100644 index 0000000000..9a38c13b05 --- /dev/null +++ b/Task/Catamorphism/Racket/catamorphism.rkt @@ -0,0 +1,8 @@ +#lang racket +(define (fold f xs init) + (if (empty? xs) + init + (f (first xs) + (fold f (rest xs) init)))) + +(fold + '(1 2 3) 0) ; the result is 6 diff --git a/Task/Catamorphism/Ruby/catamorphism-1.rb b/Task/Catamorphism/Ruby/catamorphism-1.rb new file mode 100644 index 0000000000..04047047f1 --- /dev/null +++ b/Task/Catamorphism/Ruby/catamorphism-1.rb @@ -0,0 +1,4 @@ +# sum: +p (1..10).inject(:+) +# smallest number divisible by all numbers from 1 to 20: +p (1..20).inject(:lcm) #lcm: lowest common multiple diff --git a/Task/Catamorphism/Ruby/catamorphism-2.rb b/Task/Catamorphism/Ruby/catamorphism-2.rb new file mode 100644 index 0000000000..da41819443 --- /dev/null +++ b/Task/Catamorphism/Ruby/catamorphism-2.rb @@ -0,0 +1,11 @@ +p row = [1] +10.times{p row = row.each_cons(2).inject([1,1]){|ar,(a,b)| ar.insert(-2, a+b)} } + +# [1] +# [1, 1] +# [1, 2, 1] +# [1, 3, 3, 1] +# [1, 4, 6, 4, 1] +# [1, 5, 10, 10, 5, 1] +# [1, 6, 15, 20, 15, 6, 1] +# etc diff --git a/Task/Catamorphism/Run-BASIC/catamorphism.run b/Task/Catamorphism/Run-BASIC/catamorphism.run new file mode 100644 index 0000000000..c36f06df37 --- /dev/null +++ b/Task/Catamorphism/Run-BASIC/catamorphism.run @@ -0,0 +1,28 @@ +for i = 1 to 10 :n(i) = i:next i + +print " +: ";" ";cat(10,"+") +print " -: ";" ";cat(10,"-") +print " *: ";" ";cat(10,"*") +print " /: ";" ";cat(10,"/") +print " ^: ";" ";cat(10,"^") +print "min: ";" ";cat(10,"min") +print "max: ";" ";cat(10,"max") +print "avg: ";" ";cat(10,"avg") +print "cat: ";" ";cat(10,"cat") + +function cat(count,op$) +cat = n(1) +for i = 2 to count + if op$ = "+" then cat = cat + n(i) + if op$ = "-" then cat = cat - n(i) + if op$ = "*" then cat = cat * n(i) + if op$ = "/" then cat = cat / n(i) + if op$ = "^" then cat = cat ^ n(i) + if op$ = "max" then cat = max(cat,n(i)) + if op$ = "min" then cat = min(cat,n(i)) + if op$ = "avg" then cat = cat + n(i) + if op$ = "cat" then cat$ = cat$ + str$(n(i)) +next i +if op$ = "avg" then cat = cat / count +if op$ = "cat" then cat = val(str$(n(1))+cat$) +end function diff --git a/Task/Catamorphism/Standard-ML/catamorphism.ml b/Task/Catamorphism/Standard-ML/catamorphism.ml new file mode 100644 index 0000000000..1e454a608d --- /dev/null +++ b/Task/Catamorphism/Standard-ML/catamorphism.ml @@ -0,0 +1,6 @@ +- val nums = [1,2,3,4,5,6,7,8,9,10]; +val nums = [1,2,3,4,5,6,7,8,9,10] : int list +- val sum = foldl op+ 0 nums; +val sum = 55 : int +- val product = foldl op* 1 nums; +val product = 3628800 : int diff --git a/Task/Catamorphism/Tcl/catamorphism-1.tcl b/Task/Catamorphism/Tcl/catamorphism-1.tcl new file mode 100644 index 0000000000..16e82080a4 --- /dev/null +++ b/Task/Catamorphism/Tcl/catamorphism-1.tcl @@ -0,0 +1,7 @@ +proc fold {lambda zero list} { + set accumulator $zero + foreach item $list { + set accumulator [apply $lambda $accumulator $item] + } + return $accumulator +} diff --git a/Task/Catamorphism/Tcl/catamorphism-2.tcl b/Task/Catamorphism/Tcl/catamorphism-2.tcl new file mode 100644 index 0000000000..b194e50e76 --- /dev/null +++ b/Task/Catamorphism/Tcl/catamorphism-2.tcl @@ -0,0 +1,5 @@ +set 1to5 {1 2 3 4 5} + +puts [fold {{a b} {expr {$a+$b}}} 0 $1to5] +puts [fold {{a b} {expr {$a*$b}}} 1 $1to5] +puts [fold {{a b} {return $a,$b}} x $1to5] diff --git a/Task/Catamorphism/Tcl/catamorphism-3.tcl b/Task/Catamorphism/Tcl/catamorphism-3.tcl new file mode 100644 index 0000000000..516b6407f2 --- /dev/null +++ b/Task/Catamorphism/Tcl/catamorphism-3.tcl @@ -0,0 +1,3 @@ +puts [::tcl::mathop::+ {*}$1to5] +puts [::tcl::mathop::* {*}$1to5] +puts x,[join $1to5 ,] diff --git a/Task/Character-matching/D/character-matching.d b/Task/Character-matching/D/character-matching.d deleted file mode 100644 index c0d3877c43..0000000000 --- a/Task/Character-matching/D/character-matching.d +++ /dev/null @@ -1,16 +0,0 @@ -import std.stdio: writeln; -import std.algorithm: startsWith, endsWith, find, countUntil; - -void main() { - writeln("abcd".startsWith("ab")); // true - writeln("abcd".endsWith("zn")); // false - writeln("abab".find("bb")); // empty array (no match) - writeln("abcd".find("bc")); // "bcd" (substring start - // at match) - writeln("abab".countUntil("bb")); // -1 (no match) - writeln("abab".countUntil("ba")); // 1 (index of 1st match) - - // std.algorithm.startsWith also works on arrays and ranges: - writeln([1, 2, 3].countUntil(3)); // 2 - writeln([1, 2, 3].countUntil([2, 3])); // 1 -} diff --git a/Task/Character-matching/Elena/character-matching.elena b/Task/Character-matching/Elena/character-matching.elena deleted file mode 100644 index 180bef46ce..0000000000 --- a/Task/Character-matching/Elena/character-matching.elena +++ /dev/null @@ -1,22 +0,0 @@ -#define std'dictionary'*. -#define std'routines'strings'*. - -// --- Program --- - -#symbol Program = -[ - #if "hello"~eliteralop starting_with'if:"hel" - [ - 'program'output << "hello starts with hel%n". - ]. - - #if "hello"~eliteralop ending_with'if:"llo" - [ - 'program'output << "hello ends with llo%n". - ]. - - #if (-1) ifequal:("hello"~eliteralop first_occ'find:"el") - | [ - 'program'output << "hello contains el%n". - ]. -]. diff --git a/Task/Character-matching/Perl/character-matching.pl b/Task/Character-matching/Perl/character-matching.pl deleted file mode 100644 index 419de1ebe2..0000000000 --- a/Task/Character-matching/Perl/character-matching.pl +++ /dev/null @@ -1,8 +0,0 @@ -# the first four examples use regular expressions, so make sure to escape any special regex characters in the substring -"abcd" =~ /^ab/ #returns true -"abcd" =~ /zn$/ #returns false -"abab" =~ /bb/ #returns false -"abab" =~ /ab/ #returns true -my $loc = index("abab", "bb") #returns -1 -$loc = index("abab", "ab") #returns 0 -$loc = index("abab", "ab", $loc+1) #returns 2 diff --git a/Task/Character-matching/README b/Task/Character-matching/README deleted file mode 100644 index fcd0faa2e9..0000000000 --- a/Task/Character-matching/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Character_matching diff --git a/Task/Character-matching/REXX/character-matching.rexx b/Task/Character-matching/REXX/character-matching.rexx deleted file mode 100644 index 910f0680d2..0000000000 --- a/Task/Character-matching/REXX/character-matching.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program demonstrates some basic character string testing. */ -parse arg a b -say 'string A=' a -say 'string B=' b -say - -if left(A,length(b))==b then say 'string A starts with string B' - else say "string A doesn't start with string B" -say - - /*another method, however a wee bit obtuse. */ -/*¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬ -if compare(a,b)==length(b) then say 'string A starts with string B' - else say "string A doesn't start with string B" -¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬*/ - -p=pos(b,a) -if p\==0 then say 'string A contains string B (starting in position' p")" - else say "string A doesn't contains string B" -say - -if right(A,length(b))==b then say 'string A ends with string B' - else say "string A doesn't end with string B" -say -Ps=''; p=0; do forever until p==0 - p = pos(b, a, p+1) - if p\==0 then Ps = Ps',' p - end /*forever until p==0*/ -Ps = space(strip(Ps,'L',",")) -times = words(Ps) -if times\==0 then say 'string A contains string B', - times 'time'left('s',times>1), - "(at position"left('s',times>1) Ps')' - else say "string A doesn't contains string B" - - /*stick a fork in it, we're done.*/ diff --git a/Task/Chinese-remainder-theorem/00DESCRIPTION b/Task/Chinese-remainder-theorem/00DESCRIPTION new file mode 100644 index 0000000000..63b863f244 --- /dev/null +++ b/Task/Chinese-remainder-theorem/00DESCRIPTION @@ -0,0 +1,30 @@ +Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise coprime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences. + +:\begin{align} + x &\equiv a_1 \pmod{n_1} \\ + x &\equiv a_2 \pmod{n_2} \\ + &{}\ \ \vdots \\ + x &\equiv a_k \pmod{n_k} +\end{align} + +Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. + +'''Your task''' is to write a program to solve a system of linear congruences by applying the [[wp:Chinese Remainder Theorem|Chinese Remainder Theorem]]. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. + +''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. + +'''Algorithm''': The following algorithm only applies if the n_i's are pairwise coprime. + +Suppose, as above, that a solution is required for the system of congruences: + +:x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k + +Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows. + +For each i, the integers n_i and N/n_i are coprime. Using the [[wp:Extended Euclidean algorithm|Extended Euclidean algorithm]] we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: + +:x = \sum_{i=1}^k a_i s_i N/n_i + +and the minimal solution, + +:x \pmod{N}. diff --git a/Task/Chinese-remainder-theorem/Ada/chinese-remainder-theorem.ada b/Task/Chinese-remainder-theorem/Ada/chinese-remainder-theorem.ada new file mode 100644 index 0000000000..e8f1ddb055 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Ada/chinese-remainder-theorem.ada @@ -0,0 +1,20 @@ +with Ada.Text_IO, Mod_Inv; + +procedure Chin_Rema is + N: array(Positive range <>) of Positive := (3, 5, 7); + A: array(Positive range <>) of Positive := (2, 3, 2); + Tmp: Positive; + Prod: Positive := 1; + Sum: Natural := 0; + +begin + for I in N'Range loop + Prod := Prod * N(I); + end loop; + + for I in A'Range loop + Tmp := Prod / N(I); + Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; + end loop; + Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); +end Chin_Rema; diff --git a/Task/Chinese-remainder-theorem/Bracmat/chinese-remainder-theorem.bracmat b/Task/Chinese-remainder-theorem/Bracmat/chinese-remainder-theorem.bracmat new file mode 100644 index 0000000000..33defe8c9d --- /dev/null +++ b/Task/Chinese-remainder-theorem/Bracmat/chinese-remainder-theorem.bracmat @@ -0,0 +1,38 @@ +( ( mul-inv + = a b b0 q x0 x1 + . !arg:(?a.?b:?b0) + & ( !b:1 + | 0:?x0 + & 1:?x1 + & whl + ' ( !a:>1 + & (!b.mod$(!a.!b):?q.!x1+-1*!q*!x0.!x0) + : (?a.?b.?x0.?x1) + ) + & ( !x1:<0&!b0+!x1 + | !x1 + ) + ) + ) +& ( chinese-remainder + = n a as p ns ni prod sum + . !arg:(?n.?a) + & 1:?prod + & 0:?sum + & !n:?ns + & whl'(!ns:%?ni ?ns&!prod*!ni:?prod) + & !n:?ns + & !a:?as + & whl + ' ( !ns:%?ni ?ns + & !as:%?ai ?as + & div$(!prod.!ni):?p + & !sum+!ai*mul-inv$(!p.!ni)*!p:?sum + ) + & mod$(!sum.!prod):?arg + & !arg + ) +& 3 5 7:?n +& 2 3 2:?a +& put$(str$(chinese-remainder$(!n.!a) \n)) +); diff --git a/Task/Chinese-remainder-theorem/C/chinese-remainder-theorem.c b/Task/Chinese-remainder-theorem/C/chinese-remainder-theorem.c new file mode 100644 index 0000000000..06023b2083 --- /dev/null +++ b/Task/Chinese-remainder-theorem/C/chinese-remainder-theorem.c @@ -0,0 +1,39 @@ +#include + +// returns x where (a * x) % b == 1 +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 chinese_remainder(int *n, int *a, int len) +{ + int p, i, prod = 1, sum = 0; + + for (i = 0; i < len; i++) prod *= n[i]; + + for (i = 0; i < len; i++) { + p = prod / n[i]; + sum += a[i] * mul_inv(p, n[i]) * p; + } + + return sum % prod; +} + +int main(void) +{ + int n[] = { 3, 5, 7 }; + int a[] = { 2, 3, 2 }; + + printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); + return 0; +} diff --git a/Task/Chinese-remainder-theorem/Common-Lisp/chinese-remainder-theorem.lisp b/Task/Chinese-remainder-theorem/Common-Lisp/chinese-remainder-theorem.lisp new file mode 100644 index 0000000000..fd11d31b77 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Common-Lisp/chinese-remainder-theorem.lisp @@ -0,0 +1,9 @@ +(defun chinese-remainder (am) +"Calculates the Chinese Remainder for the given set of integer modulo pairs. + Note: All the ni and the N must be coprimes." + (loop :for (a . m) :in am + :with mtot = (reduce #'* (mapcar #'(lambda(X) (cdr X)) am)) + :with sum = 0 + :finally (return (mod sum mtot)) + :do + (incf sum (* a (invmod (/ mtot m) m) (/ mtot m))))) diff --git a/Task/Chinese-remainder-theorem/D/chinese-remainder-theorem.d b/Task/Chinese-remainder-theorem/D/chinese-remainder-theorem.d new file mode 100644 index 0000000000..0a955ecfa4 --- /dev/null +++ b/Task/Chinese-remainder-theorem/D/chinese-remainder-theorem.d @@ -0,0 +1,40 @@ +import std.stdio, std.algorithm; + +T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc +in { + assert(n.length == a.length); +} body { + static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { + auto b0 = b; + T x0 = 0, x1 = 1; + if (b == 1) + return T(1); + while (a > 1) { + immutable q = a / b; + immutable amb = a % b; + a = b; + b = amb; + immutable xqx = x1 - q * x0; + x1 = x0; + x0 = xqx; + } + if (x1 < 0) + x1 += b0; + return x1; + } + + immutable prod = reduce!q{a * b}(T(1), n); + + T p = 1, sm = 0; + foreach (immutable i, immutable ni; n) { + p = prod / ni; + sm += a[i] * mulInv(p, ni) * p; + } + return sm % prod; +} + +void main() { + immutable n = [3, 5, 7], + a = [2, 3, 2]; + chineseRemainder(n, a).writeln; +} diff --git a/Task/Chinese-remainder-theorem/Erlang/chinese-remainder-theorem.erl b/Task/Chinese-remainder-theorem/Erlang/chinese-remainder-theorem.erl new file mode 100644 index 0000000000..d6a322b26e --- /dev/null +++ b/Task/Chinese-remainder-theorem/Erlang/chinese-remainder-theorem.erl @@ -0,0 +1,41 @@ +-module(crt). +-import(lists, [zip/2, unzip/1, foldl/3, sum/1]). +-export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). + +egcd(_, 0) -> {1, 0}; +egcd(A, B) -> + {S, T} = egcd(B, A rem B), + {T, S - (A div B)*T}. + +mod_inv(A, B) -> + {X, Y} = egcd(A, B), + if + A*X + B*Y =:= 1 -> X; + true -> undefined + end. + +mod(A, M) -> + X = A rem M, + if + X < 0 -> X + M; + true -> X + end. + +calc_inverses([], []) -> []; +calc_inverses([N | Ns], [M | Ms]) -> + case mod_inv(N, M) of + undefined -> undefined; + Inv -> [Inv | calc_inverses(Ns, Ms)] + end. + +chinese_remainder(Congruences) -> + {Residues, Modulii} = unzip(Congruences), + ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), + CRT_Modulii = [ModPI div M || M <- Modulii], + case calc_inverses(CRT_Modulii, Modulii) of + undefined -> undefined; + Inverses -> + Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, + [A*B || {A,B} <- zip(Residues, Inverses)])]), + mod(Solution, ModPI) + end. diff --git a/Task/Chinese-remainder-theorem/Forth/chinese-remainder-theorem.fth b/Task/Chinese-remainder-theorem/Forth/chinese-remainder-theorem.fth new file mode 100644 index 0000000000..4a410f1315 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Forth/chinese-remainder-theorem.fth @@ -0,0 +1,38 @@ +: egcd ( a b -- a b ) + dup 0= IF + 2drop 1 0 + ELSE + dup -rot /mod \ -- b r=a%b q=a/b + -rot recurse \ -- q (s,t) = egcd(b, r) + >r swap r@ * - r> swap \ -- t (s - q*t) + THEN ; + +: egcd>gcd ( a b x y -- n ) \ calculate gcd from egcd + rot * -rot * + ; + +: mod-inv ( a m -- a' ) \ modular inverse with coprime check + 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; + +: array-product ( adr count -- n ) + 1 -rot cells bounds ?DO i @ * cell +LOOP ; + +: crt-from-array ( adr1 adr2 count -- n ) + 2dup array-product locals| M count m[] a[] | + 0 \ result + count 0 DO + m[] i cells + @ + dup M swap / + dup rot mod-inv * + a[] i cells + @ * + + LOOP M mod ; + +create crt-residues[] 10 cells allot +create crt-moduli[] 10 cells allot + +: crt ( .... n -- n ) \ takes pairs of "n (mod m)" from stack. + 10 min locals| n | + n 0 DO + crt-moduli[] i cells + ! + crt-residues[] i cells + ! + LOOP + crt-residues[] crt-moduli[] n crt-from-array ; diff --git a/Task/Chinese-remainder-theorem/Go/chinese-remainder-theorem.go b/Task/Chinese-remainder-theorem/Go/chinese-remainder-theorem.go new file mode 100644 index 0000000000..f2c659dd9c --- /dev/null +++ b/Task/Chinese-remainder-theorem/Go/chinese-remainder-theorem.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "math/big" +) + +var one = big.NewInt(1) + +func crt(a, n []*big.Int) (*big.Int, error) { + p := new(big.Int).Set(n[0]) + for _, n1 := range n[1:] { + p.Mul(p, n1) + } + var x, q, s, z big.Int + for i, n1 := range n { + q.Div(p, n1) + z.GCD(nil, &s, n1, &q) + if z.Cmp(one) != 0 { + return nil, fmt.Errorf("%d not coprime", n1) + } + x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) + } + return x.Mod(&x, p), nil +} + +func main() { + n := []*big.Int{ + big.NewInt(3), + big.NewInt(5), + big.NewInt(7), + } + a := []*big.Int{ + big.NewInt(2), + big.NewInt(3), + big.NewInt(2), + } + fmt.Println(crt(a, n)) +} diff --git a/Task/Chinese-remainder-theorem/Haskell/chinese-remainder-theorem.hs b/Task/Chinese-remainder-theorem/Haskell/chinese-remainder-theorem.hs new file mode 100644 index 0000000000..99db8c3cbd --- /dev/null +++ b/Task/Chinese-remainder-theorem/Haskell/chinese-remainder-theorem.hs @@ -0,0 +1,22 @@ +module CRT ( chineseRemainder ) where + +egcd :: Integral a => a -> a -> (a, a) +egcd _ 0 = (1, 0) +egcd a b = (t, s - q * t) + where + (s, t) = egcd b r + (q, r) = a `quotRem` b + +modInv :: Integral a => a -> a -> Maybe a +modInv a b = case egcd a b of + (x, y) | a * x + b * y == 1 -> Just x + | otherwise -> Nothing + +chineseRemainder :: Integral a => [a] -> [a] -> Maybe a +chineseRemainder residues modulii = do + inverses <- sequence $ zipWith modInv crtModulii modulii + return . (`mod` modPI) . sum $ + zipWith (*) crtModulii (zipWith (*) residues inverses) + where + modPI = product modulii + crtModulii = map (modPI `div`) modulii diff --git a/Task/Chinese-remainder-theorem/Icon/chinese-remainder-theorem.icon b/Task/Chinese-remainder-theorem/Icon/chinese-remainder-theorem.icon new file mode 100644 index 0000000000..ca6e895c1b --- /dev/null +++ b/Task/Chinese-remainder-theorem/Icon/chinese-remainder-theorem.icon @@ -0,0 +1,24 @@ +link numbers # for gcd() + +procedure main() + write(cr([3,5,7],[2,3,2]) | "No solution!") + write(cr([10,4,9],[11,22,19]) | "No solution!") +end + +procedure cr(n,a) + if 1 ~= gcd(n[i := !*n],a[i]) then fail # Not pairwise coprime + (prod := 1, sm := 0) + every prod *:= !n + every p := prod/(ni := n[i := !*n]) do sm +:= a[i] * mul_inv(p,ni) * p + return sm%prod +end + +procedure mul_inv(a,b) + if b = 1 then return 1 + (b0 := b, x0 := 0, x1 := 1) + while q := (1 < a)/b do { + (t := a, a := b, b := t%b) + (t := x0, x0 := x1-q*t, x1 := t) + } + return if x1 < 0 then x1+b0 else x1 +end diff --git a/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-1.j b/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-1.j new file mode 100644 index 0000000000..c31d4b5a2b --- /dev/null +++ b/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-1.j @@ -0,0 +1 @@ + crt =: (1 + ] - {:@:[ -: {.@:[ | ])^:_&0@:,: diff --git a/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-2.j b/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-2.j new file mode 100644 index 0000000000..5dce8609f4 --- /dev/null +++ b/Task/Chinese-remainder-theorem/J/chinese-remainder-theorem-2.j @@ -0,0 +1,4 @@ + 3 5 7 crt 2 3 2 +23 + 11 12 13 crt 10 4 12 +1000 diff --git a/Task/Chinese-remainder-theorem/Maple/chinese-remainder-theorem.maple b/Task/Chinese-remainder-theorem/Maple/chinese-remainder-theorem.maple new file mode 100644 index 0000000000..3b07507328 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Maple/chinese-remainder-theorem.maple @@ -0,0 +1,2 @@ +> chrem( [2, 3, 2], [3, 5, 7] ); + 23 diff --git a/Task/Chinese-remainder-theorem/Mathematica/chinese-remainder-theorem.math b/Task/Chinese-remainder-theorem/Mathematica/chinese-remainder-theorem.math new file mode 100644 index 0000000000..acf33bf8e9 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Mathematica/chinese-remainder-theorem.math @@ -0,0 +1,2 @@ +ChineseRemainder[{2, 3, 2}, {3, 5, 7}] +23 diff --git a/Task/Chinese-remainder-theorem/OCaml/chinese-remainder-theorem.ocaml b/Task/Chinese-remainder-theorem/OCaml/chinese-remainder-theorem.ocaml new file mode 100644 index 0000000000..af19fbf0de --- /dev/null +++ b/Task/Chinese-remainder-theorem/OCaml/chinese-remainder-theorem.ocaml @@ -0,0 +1,40 @@ +open Core.Std +open Option.Monad_infix + +let rec egcd a b = + if b = 0 then (1, 0) + else + let q = a/b and r = a mod b in + let (s, t) = egcd b r in + (t, s - q*t) + + +let mod_inv a b = + let (x, y) = egcd a b in + if a*x + b*y = 1 then Some x else None + + +let calc_inverses ns ms = + let rec list_inverses ns ms l = + match (ns, ms) with + | ([], []) -> Some l + | ([], _) + | (_, []) -> assert false + | (n::ns, m::ms) -> + let inv = mod_inv n m in + match inv with + | None -> None + | Some v -> list_inverses ns ms (v::l) + in + list_inverses ns ms [] >>= fun l -> Some (List.rev l) + + +let chinese_remainder congruences = + let (residues, modulii) = List.unzip congruences in + let mod_pi = List.reduce_exn modulii ~f:( * ) in + let crt_modulii = List.map modulii ~f:(fun m -> mod_pi / m) in + calc_inverses crt_modulii modulii >>= + fun inverses -> + Some (List.map3_exn residues inverses crt_modulii ~f:(fun a b c -> a*b*c) + |> List.reduce_exn ~f:(+) + |> fun n -> let n' = n mod mod_pi in if n' < 0 then n' + mod_pi else n') diff --git a/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-1.pari b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-1.pari new file mode 100644 index 0000000000..c44274f24b --- /dev/null +++ b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-1.pari @@ -0,0 +1,8 @@ +chivec(residues, moduli)={ + my(m=Mod(0,1)); + for(i=1,#residues, + m=chinese(Mod(residues[i],moduli[i]),m) + ); + lift(m) +}; +chivec([2,3,2], [3,5,7]) diff --git a/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-2.pari b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-2.pari new file mode 100644 index 0000000000..53ac3a4dd0 --- /dev/null +++ b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-2.pari @@ -0,0 +1 @@ +lift( chinese([Mod(2,3),Mod(3,5),Mod(2,7)]) ) diff --git a/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-3.pari b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-3.pari new file mode 100644 index 0000000000..49ab755865 --- /dev/null +++ b/Task/Chinese-remainder-theorem/PARI-GP/chinese-remainder-theorem-3.pari @@ -0,0 +1,3 @@ +chivec(residues,moduli)={ + lift(chinese(vector(#residues,i,Mod(residues[i],moduli[i])))) +} diff --git a/Task/Chinese-remainder-theorem/Perl-6/chinese-remainder-theorem.pl6 b/Task/Chinese-remainder-theorem/Perl-6/chinese-remainder-theorem.pl6 new file mode 100644 index 0000000000..b39d106898 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Perl-6/chinese-remainder-theorem.pl6 @@ -0,0 +1,25 @@ +# returns x where (a * x) % b == 1 +sub mul-inv($a is copy, $b is copy) { + return 1 if $b == 1; + my ($b0, @x) = $b, 0, 1; + ($a, $b, @x) = ( + $b, + $a % $b, + @x[1] - ($a div $b)*@x[0], + @x[0] + ) while $a > 1; + @x[1] += $b0 if @x[1] < 0; + return @x[1]; +} + +sub chinese-remainder(*@n) { + my \N = [*] @n; + -> *@a { + N R% [+] map { + my \p = N div @n[$_]; + @a[$_] * mul-inv(p, @n[$_]) * p + }, ^@n + } +} + +say chinese-remainder(3, 5, 7)(2, 3, 2); diff --git a/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-1.pl b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-1.pl new file mode 100644 index 0000000000..8199293f63 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-1.pl @@ -0,0 +1,2 @@ +use ntheory qw/chinese/; +say chinese([2,3], [3,5], [2,7]); diff --git a/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-2.pl b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-2.pl new file mode 100644 index 0000000000..61918a5824 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-2.pl @@ -0,0 +1,3 @@ +use Math::ModInt qw(mod); +use Math::ModInt::ChineseRemainder qw(cr_combine); +say cr_combine(mod(2,3),mod(3,5),mod(2,7)); diff --git a/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl new file mode 100644 index 0000000000..d40636dc15 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Perl/chinese-remainder-theorem-3.pl @@ -0,0 +1,2 @@ +use ntheory qw/chinese/; +say chinese( [2328,16256], [410,5418] ), " mod ", lcm(16256,5418); diff --git a/Task/Chinese-remainder-theorem/PicoLisp/chinese-remainder-theorem.l b/Task/Chinese-remainder-theorem/PicoLisp/chinese-remainder-theorem.l new file mode 100644 index 0000000000..b6db620f67 --- /dev/null +++ b/Task/Chinese-remainder-theorem/PicoLisp/chinese-remainder-theorem.l @@ -0,0 +1,29 @@ +(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) ) ) + +(de chinrem (N A) + (let P (apply * N) + (% + (sum + '((N A) + (setq T1 (/ P N)) + (* A (modinv T1 N) T1) ) + N + A ) + P ) ) ) + +(println + (chinrem (3 5 7) (2 3 2)) + (chinrem (11 12 13) (10 4 12)) ) + +(bye) diff --git a/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py b/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py new file mode 100644 index 0000000000..4e74febffc --- /dev/null +++ b/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py @@ -0,0 +1,23 @@ +def mul_inv(a, b): + b0 = b + x0, x1 = 0, 1 + if b == 1: return 1 + while a > 1: + q = a / b + a, b = b, a%b + x0, x1 = x1 - q * x0, x0 + if x1 < 0: x1 += b0 + return x1 + +def chinese_remainder(n, a, lena): + p = i = prod = 1; sm = 0 + for i in range(lena): prod *= n[i] + for i in range(lena): + p = prod / n[i] + sm += a[i] * mul_inv(p, n[i]) * p + return sm % prod + +if __name__ == '__main__': + n = [3, 5, 7] + a = [2, 3, 2] + print(chinese_remainder(n, a, len(n))) diff --git a/Task/Chinese-remainder-theorem/R/chinese-remainder-theorem.r b/Task/Chinese-remainder-theorem/R/chinese-remainder-theorem.r new file mode 100644 index 0000000000..27beec5369 --- /dev/null +++ b/Task/Chinese-remainder-theorem/R/chinese-remainder-theorem.r @@ -0,0 +1,44 @@ +mul_inv <- function(a, b) +{ + b0 <- b + x0 <- 0L + x1 <- 1L + + if (b == 1) return(1L) + while(a > 1){ + q <- as.integer(a/b) + + t <- b + b <- a %% b + a <- t + + t <- x0 + x0 <- x1 - q*x0 + x1 <- t + } + + if (x1 < 0) x1 <- x1 + b0 + return(x1) +} + +chinese_remainder <- function(n, a) +{ + len <- length(n) + + prod <- 1L + sum <- 0L + + for (i in 1:len) prod <- prod * n[i] + + for (i in 1:len){ + p <- as.integer(prod / n[i]) + sum <- sum + a[i] * mul_inv(p, n[i]) * p + } + + return(sum %% prod) +} + +n <- c(3L, 5L, 7L) +a <- c(2L, 3L, 2L) + +chinese_remainder(n, a) diff --git a/Task/Chinese-remainder-theorem/README b/Task/Chinese-remainder-theorem/README new file mode 100644 index 0000000000..772238d8d6 --- /dev/null +++ b/Task/Chinese-remainder-theorem/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Chinese_remainder_theorem diff --git a/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx new file mode 100644 index 0000000000..fa5231dd71 --- /dev/null +++ b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx @@ -0,0 +1,24 @@ +/*REXX program uses the Chinese Remainder Theorem (Sun Tzu). */ +parse arg Ns As . /*get optional arguments from CL.*/ +if Ns=='' then Ns = '3,5,7' /*Ns not specified? Use default.*/ +if As=='' then As = '2,3,2' /*As " " " " */ +Ns=space(translate(Ns,,',')); #=words(Ns) /*elide superfluous blanks*/ +As=space(translate(As,,',')); _=words(As) /* " " " */ +if #\==_ then do; say "size of number sets don't match."; exit 131; end +if #==0 then do; say "size of the N set isn't valid."; exit 132; end +if _==0 then do; say "size of the A set isn't valid."; exit 133; end +N=1 /*the product─to─be for prod(n.j)*/ + do j=1 for # /*process each number for As, Ns.*/ + n.j=word(Ns,j); N=N*n.j /*get an N.j and calculate prod*/ + a.j=word(As,j) /* " " A.j from the As. */ + end /*j*/ + + do x=1 for N /*use a simple algebraic method. */ + do i=1 for # /*process each A.i number. */ + if x//n.i\==a.i then iterate x /*is the modulus correct for F ? */ + end /*i*/ /* [↑] limit solution to product*/ + say 'found a solution with x=' x /*announce a possible solution. */ + exit /*stick a fork in it, we're done.*/ + end /*x*/ + /*stick a fork in it, we're done.*/ +say 'no solution found.' /*oops, announce that ¬ found. */ diff --git a/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx new file mode 100644 index 0000000000..6be90a012f --- /dev/null +++ b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx @@ -0,0 +1,26 @@ +/*REXX program uses the Chinese Remainder Theorem (Sun Tzu). */ +parse arg Ns As . /*get optional arguments from CL.*/ +if Ns=='' then Ns = '3,5,7' /*Ns not specified? Use default.*/ +if As=='' then As = '2,3,2' /*As " " " " */ +Ns=space(translate(Ns,,',')); #=words(Ns) /*elide superfluous blanks*/ +As=space(translate(As,,',')); _=words(As) /* " " " */ +if #\==_ then do; say "size of number sets don't match."; exit 131; end +if #==0 then do; say "size of the N set isn't valid."; exit 132; end +if _==0 then do; say "size of the A set isn't valid."; exit 133; end +N=1 /*the product─to─be for prod(n.j)*/ + do j=1 for # /*process each number for As, Ns.*/ + n.j=word(Ns,j); N=N*n.j /*get an N.j and calculate prod*/ + a.j=word(As,j) /* " " A.j from the As. */ + end /*j*/ +@.= /* [↓] converts congruences─►sets*/ + do i=1 for #; _=a.i; @.i._=a.i; p=a.i + do N; p=p+n.i; @.i.p=p; end /*build a list of modulo values. */ + end /*i*/ + /* [↓] find common number in sets*/ + do x=1 for N; if @.1.x=='' then iterate /*find a number.*/ + do v=2 to #; if @.v.x=='' then iterate x; end /*In all sets ? */ + say 'found a solution with X=' x /*we found the lowest solution. */ + exit /*stick a fork in it, we're done.*/ + end /*x*/ + /*stick a fork in it, we're done.*/ +say 'no solution found.' /*oops, there's not a solution. */ diff --git a/Task/Chinese-remainder-theorem/Racket/chinese-remainder-theorem.rkt b/Task/Chinese-remainder-theorem/Racket/chinese-remainder-theorem.rkt new file mode 100644 index 0000000000..7d9496fee7 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Racket/chinese-remainder-theorem.rkt @@ -0,0 +1,5 @@ +#lang racket +(require (only-in math/number-theory solve-chinese)) +(define as '(2 3 2)) +(define ns '(3 5 7)) +(solve-chinese as ns) diff --git a/Task/Chinese-remainder-theorem/Ruby/chinese-remainder-theorem.rb b/Task/Chinese-remainder-theorem/Ruby/chinese-remainder-theorem.rb new file mode 100644 index 0000000000..2e2a54805a --- /dev/null +++ b/Task/Chinese-remainder-theorem/Ruby/chinese-remainder-theorem.rb @@ -0,0 +1,8 @@ +def chinese_remainder(mods, remainders) + max = mods.inject( :* ) + series = remainders.zip( mods ).map{|r,m| r.step( max, m ).to_a } + series.inject( :& ).first #returns nil when empty +end + +p chinese_remainder([3,5,7], [2,3,2]) #=> 23 +p chinese_remainder([10,4,9], [11,22,19]) #=> nil diff --git a/Task/Chinese-remainder-theorem/Seed7/chinese-remainder-theorem.seed7 b/Task/Chinese-remainder-theorem/Seed7/chinese-remainder-theorem.seed7 new file mode 100644 index 0000000000..c0c4416f14 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Seed7/chinese-remainder-theorem.seed7 @@ -0,0 +1,24 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const func integer: modInverse (in integer: a, in integer: b) is + return ord(modInverse(bigInteger conv a, bigInteger conv b)); + +const proc: main is func + local + const array integer: n is [] (3, 5, 7); + const array integer: a is [] (2, 3, 2); + var integer: num is 0; + var integer: prod is 1; + var integer: sum is 0; + var integer: index is 0; + begin + for num range n do + prod *:= num; + end for; + for key index range a do + num := prod div n[index]; + sum +:= a[index] * modInverse(num, n[index]) * num; + end for; + writeln(sum mod prod); + end func; diff --git a/Task/Chinese-remainder-theorem/Tcl/chinese-remainder-theorem.tcl b/Task/Chinese-remainder-theorem/Tcl/chinese-remainder-theorem.tcl new file mode 100644 index 0000000000..8b474fcc36 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Tcl/chinese-remainder-theorem.tcl @@ -0,0 +1,18 @@ +proc ::tcl::mathfunc::mulinv {a b} { + if {$b == 1} {return 1} + set b0 $b; set x0 0; set x1 1 + while {$a > 1} { + set x0 [expr {$x1 - ($a / $b) * [set x1 $x0]}] + set b [expr {$a % [set a $b]}] + } + incr x1 [expr {($x1 < 0) * $b0}] +} +proc chineseRemainder {nList aList} { + set sum 0; set prod [::tcl::mathop::* {*}$nList] + foreach n $nList a $aList { + set p [expr {$prod / $n}] + incr sum [expr {$a * mulinv($p, $n) * $p}] + } + expr {$sum % $prod} +} +puts [chineseRemainder {3 5 7} {2 3 2}] diff --git a/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION b/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION new file mode 100644 index 0000000000..c1d726bfb5 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION @@ -0,0 +1,19 @@ +Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. +;Exceptions: +# r==0.0 should be treated as never describing circles (except in the case where the points are coincident). +# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. +# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. +# If the points are too far apart then no circles can be drawn. + +;Task detail: +* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. +* Show here the output for the following inputs: +
      p1                p2           r
+0.1234, 0.9876    0.8765, 0.2345    2.0
+0.0000, 2.0000    0.0000, 0.0000    1.0
+0.1234, 0.9876    0.1234, 0.9876    2.0
+0.1234, 0.9876    0.8765, 0.2345    0.5
+0.1234, 0.9876    0.1234, 0.9876    0.0
+ +;Ref: +* [http://mathforum.org/library/drmath/view/53027.html Finding the Center of a Circle from 2 Points and Radius] from Math forum @ Drexel diff --git a/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-1.ahk b/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-1.ahk new file mode 100644 index 0000000000..44594f960e --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-1.ahk @@ -0,0 +1,17 @@ +CircleCenter(x1, y1, x2, y2, r){ + d := sqrt((x2-x1)**2 + (y2-y1)**2) + x3 := (x1+x2)/2 , y3 := (y1+y2)/2 + cx1 := x3 + sqrt(r**2-(d/2)**2)*(y1-y2)/d , cy1:= y3 + sqrt(r**2-(d/2)**2)*(x2-x1)/d + cx2 := x3 - sqrt(r**2-(d/2)**2)*(y1-y2)/d , cy2:= y3 - sqrt(r**2-(d/2)**2)*(x2-x1)/d + if (d = 0) + return "No circles can be drawn, points are identical" + if (d = r*2) + return "points are opposite ends of a diameter center = " cx1 "," cy1 + if (d = r*2) + return "points are too far" + if (r <= 0) + return "radius is not valid" + if !(cx1 && cy1 && cx2 && cy2) + return "no solution" + return cx1 "," cy1 " & " cx2 "," cy2 +} diff --git a/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-2.ahk b/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-2.ahk new file mode 100644 index 0000000000..fddff7aadc --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/AutoHotkey/circles-of-given-radius-through-two-points-2.ahk @@ -0,0 +1,14 @@ +data = +( +0.1234 0.9876 0.8765 0.2345 2.0 +0.0000 2.0000 0.0000 0.0000 1.0 +0.1234 0.9876 0.1234 0.9876 2.0 +0.1234 0.9876 0.8765 0.2345 0.5 +0.1234 0.9876 0.1234 0.9876 0.0 +) + +loop, parse, data, `n +{ + obj := StrSplit(A_LoopField, " ") + MsgBox, % CircleCenter(obj[1], obj[2], obj[3], obj[4], obj[5]) +} diff --git a/Task/Circles-of-given-radius-through-two-points/BASIC/circles-of-given-radius-through-two-points.basic b/Task/Circles-of-given-radius-through-two-points/BASIC/circles-of-given-radius-through-two-points.basic new file mode 100644 index 0000000000..8e19c57e0b --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/BASIC/circles-of-given-radius-through-two-points.basic @@ -0,0 +1,37 @@ +Type Point + As Double x,y + Declare Property length As Double +End Type + +Property point.length As Double +Return Sqr(x*x+y*y) +End Property + +Sub circles(p1 As Point,p2 As Point,radius As Double) + Print "Points ";"("&p1.x;","&p1.y;"),("&p2.x;","&p2.y;")";", Rad ";radius + Var ctr=Type((p1.x+p2.x)/2,(p1.y+p2.y)/2) + Var half=Type(p1.x-ctr.x,p1.y-ctr.y) + Var lenhalf=half.length + If radius(-dist*(p1.y-ctr.y) +ctr.x,dist*(p1.x-ctr.x) +ctr.y) + Print " -> Circle 1 ("&rot.x;","&rot.y;")" + rot= Type(-(rot.x-ctr.x) +ctr.x,-((rot.y-ctr.y)) +ctr.y) + Print" -> Circle 2 ("&rot.x;","&rot.y;")" + Print +End Sub + + +Dim As Point p1=(.1234,.9876),p2=(.8765,.2345) +circles(p1,p2,2) +p1=Type(0,2):p2=Type(0,0) +circles(p1,p2,1) +p1=Type(.1234,.9876):p2=p1 +circles(p1,p2,2) +p1=Type(.1234,.9876):p2=Type(.8765,.2345) +circles(p1,p2,.5) +p1=Type(.1234,.9876):p2=p1 +circles(p1,p2,0) + +Sleep diff --git a/Task/Circles-of-given-radius-through-two-points/C/circles-of-given-radius-through-two-points.c b/Task/Circles-of-given-radius-through-two-points/C/circles-of-given-radius-through-two-points.c new file mode 100644 index 0000000000..272090d961 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/C/circles-of-given-radius-through-two-points.c @@ -0,0 +1,63 @@ +#include +#include + +typedef struct{ + double x,y; + }point; + +double distance(point p1,point p2) +{ + return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); +} + +void findCircles(point p1,point p2,double radius) +{ + double separation = distance(p1,p2),mirrorDistance; + + if(separation == 0.0) + { + radius == 0.0 ? printf("\nNo circles can be drawn through (%.4f,%.4f)",p1.x,p1.y): + printf("\nInfinitely many circles can be drawn through (%.4f,%.4f)",p1.x,p1.y); + } + + else if(separation == 2*radius) + { + printf("\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius %.4f",(p1.x+p2.x)/2,(p1.y+p2.y)/2,radius); + } + + else if(separation > 2*radius) + { + printf("\nGiven points are farther away from each other than a diameter of a circle with radius %.4f",radius); + } + + else + { + mirrorDistance =sqrt(pow(radius,2) - pow(separation/2,2)); + + printf("\nTwo circles are possible."); + printf("\nCircle C1 with center (%.4f,%.4f), radius %.4f and Circle C2 with center (%.4f,%.4f), radius %.4f",(p1.x+p2.x)/2 + mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 + mirrorDistance*(p2.x-p1.x)/separation,radius,(p1.x+p2.x)/2 - mirrorDistance*(p1.y-p2.y)/separation,(p1.y+p2.y)/2 - mirrorDistance*(p2.x-p1.x)/separation,radius); + } +} + +int main() +{ +int i; + +point cases[] = +{ {0.1234, 0.9876}, {0.8765, 0.2345}, + {0.0000, 2.0000}, {0.0000, 0.0000}, + {0.1234, 0.9876}, {0.1234, 0.9876}, + {0.1234, 0.9876}, {0.8765, 0.2345}, + {0.1234, 0.9876}, {0.1234, 0.9876} +}; + +double radii[] = {2.0,1.0,2.0,0.5,0.0}; + +for(i=0;i<5;i++) +{ + printf("\nCase %d)",i+1); + findCircles(cases[2*i],cases[2*i+1],radii[i]); +} + +return 0; +} diff --git a/Task/Circles-of-given-radius-through-two-points/D/circles-of-given-radius-through-two-points.d b/Task/Circles-of-given-radius-through-two-points/D/circles-of-given-radius-through-two-points.d new file mode 100644 index 0000000000..2e04751a86 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/D/circles-of-given-radius-through-two-points.d @@ -0,0 +1,62 @@ +import std.stdio, std.typecons, std.math; + +class ValueException : Exception { + this(string msg_) pure { super(msg_); } +} + +struct V2 { double x, y; } +struct Circle { double x, y, r; } + +/**Following explanation at: +http://mathforum.org/library/drmath/view/53027.html +*/ +Tuple!(Circle, Circle) +circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r) +pure in { + assert(r >= 0, "radius can't be negative"); +} body { + enum nBits = 40; + + if (r.abs < (1.0 / (2.0 ^^ nBits))) + throw new ValueException("radius of zero"); + + if (feqrel(cast()p1.x, cast()p2.x) >= nBits && + feqrel(cast()p1.y, cast()p2.y) >= nBits) + throw new ValueException("coincident points give" ~ + " infinite number of Circles"); + + // Delta between points. + immutable d = V2(p2.x - p1.x, p2.y - p1.y); + + // Distance between points. + immutable q = sqrt(d.x ^^ 2 + d.y ^^ 2); + if (q > 2.0 * r) + throw new ValueException("separation of points > diameter"); + + // Halfway point. + immutable h = V2((p1.x + p2.x) / 2, (p1.y + p2.y) / 2); + + // Distance along the mirror line. + immutable dm = sqrt(r ^^ 2 - (q / 2) ^^ 2); + + return typeof(return)( + Circle(h.x - dm * d.y / q, h.y + dm * d.x / q, r.abs), + Circle(h.x + dm * d.y / q, h.y - dm * d.x / q, r.abs)); +} + +void main() { + foreach (immutable t; [ + tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0), + tuple(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0), + tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0), + tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5), + tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0)]) { + writefln("Through points:\n %s %s and radius %f\n" ~ + "You can construct the following circles:", t[]); + try { + writefln(" %s\n %s\n", + circlesFromTwoPointsAndRadius(t[])[]); + } catch (ValueException v) + writefln(" ERROR: %s\n", v.msg); + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f new file mode 100644 index 0000000000..074a027907 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f @@ -0,0 +1,104 @@ +! Implemented by Anant Dixit (Nov. 2014) +program circles +implicit none +double precision :: P1(2), P2(2), R + +P1 = (/0.1234d0, 0.9876d0/) +P2 = (/0.8765d0,0.2345d0/) +R = 2.0d0 +call print_centers(P1,P2,R) + +P1 = (/0.0d0, 2.0d0/) +P2 = (/0.0d0,0.0d0/) +R = 1.0d0 +call print_centers(P1,P2,R) + +P1 = (/0.1234d0, 0.9876d0/) +P2 = (/0.1234d0, 0.9876d0/) +R = 2.0d0 +call print_centers(P1,P2,R) + +P1 = (/0.1234d0, 0.9876d0/) +P2 = (/0.8765d0, 0.2345d0/) +R = 0.5d0 +call print_centers(P1,P2,R) + +P1 = (/0.1234d0, 0.9876d0/) +P2 = (/0.1234d0, 0.9876d0/) +R = 0.0d0 +call print_centers(P1,P2,R) +end program circles + +subroutine print_centers(P1,P2,R) +implicit none +double precision :: P1(2), P2(2), R, Center(2,2) +integer :: Res +call test_inputs(P1,P2,R,Res) +write(*,*) +write(*,'(A10,F7.4,A1,F7.4)') 'Point1 : ', P1(1), ' ', P1(2) +write(*,'(A10,F7.4,A1,F7.4)') 'Point2 : ', P2(1), ' ', P2(2) +write(*,'(A10,F7.4)') 'Radius : ', R +if(Res.eq.1) then + write(*,*) 'Same point because P1=P2 and r=0.' +elseif(Res.eq.2) then + write(*,*) 'No circles can be drawn because r=0.' +elseif(Res.eq.3) then + write(*,*) 'Infinite circles because P1=P2 for non-zero radius.' +elseif(Res.eq.4) then + write(*,*) 'No circles with given r can be drawn because points are far apart.' +elseif(Res.eq.0) then + call find_center(P1,P2,R,Center) + if(Center(1,1).eq.Center(2,1) .and. Center(1,2).eq.Center(2,2)) then + write(*,*) 'Points lie on the diameter. A single circle can be drawn.' + write(*,'(A10,F7.4,A1,F7.4)') 'Center : ', Center(1,1), ' ', Center(1,2) + else + write(*,*) 'Two distinct circles found.' + write(*,'(A10,F7.4,A1,F7.4)') 'Center1 : ', Center(1,1), ' ', Center(1,2) + write(*,'(A10,F7.4,A1,F7.4)') 'Center2 : ', Center(2,1), ' ', Center(2,2) + end if +elseif(Res.lt.0) then + write(*,*) 'Incorrect value for r.' +end if +write(*,*) +end subroutine print_centers + +subroutine test_inputs(P1,P2,R,Res) +implicit none +double precision :: P1(2), P2(2), R, dist +integer :: Res +if(R.lt.0.0d0) then + Res = -1 + return +elseif(R.eq.0.0d0 .and. P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then + Res = 1 + return +elseif(R.eq.0.0d0) then + Res = 2 + return +elseif(P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then + Res = 3 + return +else + dist = sqrt( (P1(1)-P2(1))**2 + (P1(2)-P2(2))**2 ) + if(dist.gt.2.0d0*R) then + Res = 4 + return + else + Res = 0 + return + end if +end if +end subroutine test_inputs + +subroutine find_center(P1,P2,R,Center) +implicit none +double precision :: P1(2), P2(2), MP(2), Center(2,2), R, dm +MP = (P1+P2)/2.0d0 +dm = sqrt( (P1(1)-P2(1))**2 + (P1(2)-P2(2))**2 ) + +Center(1,1) = MP(1) + sqrt(R**2 - (dm/2.0d0)**2)*(P2(2)-P1(2))/dm +Center(1,2) = MP(2) + sqrt(R**2 - (dm/2.0d0)**2)*(P2(1)-P1(1))/dm + +Center(2,1) = MP(1) - sqrt(R**2 - (dm/2.0d0)**2)*(P2(2)-P1(2))/dm +Center(2,2) = MP(2) - sqrt(R**2 - (dm/2.0d0)**2)*(P2(1)-P1(1))/dm +end subroutine find_center diff --git a/Task/Circles-of-given-radius-through-two-points/Go/circles-of-given-radius-through-two-points.go b/Task/Circles-of-given-radius-through-two-points/Go/circles-of-given-radius-through-two-points.go new file mode 100644 index 0000000000..675c3ddf9b --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Go/circles-of-given-radius-through-two-points.go @@ -0,0 +1,74 @@ +package main + +import ( + "fmt" + "math" +) + +var ( + Two = "Two circles." + R0 = "R==0.0 does not describe circles." + Co = "Coincident points describe an infinite number of circles." + CoR0 = "Coincident points with r==0.0 describe a degenerate circle." + Diam = "Points form a diameter and describe only a single circle." + Far = "Points too far apart to form circles." +) + +type point struct{ x, y float64 } + +func circles(p1, p2 point, r float64) (c1, c2 point, Case string) { + if p1 == p2 { + if r == 0 { + return p1, p1, CoR0 + } + Case = Co + return + } + if r == 0 { + return p1, p2, R0 + } + dx := p2.x - p1.x + dy := p2.y - p1.y + q := math.Hypot(dx, dy) + if q > 2*r { + Case = Far + return + } + m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2} + if q == 2*r { + return m, m, Diam + } + d := math.Sqrt(r*r - q*q/4) + ox := d * dx / q + oy := d * dy / q + return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two +} + +var td = []struct { + p1, p2 point + r float64 +}{ + {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0}, + {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0}, + {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0}, + {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5}, + {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0}, +} + +func main() { + for _, tc := range td { + fmt.Println("p1: ", tc.p1) + fmt.Println("p2: ", tc.p2) + fmt.Println("r: ", tc.r) + c1, c2, Case := circles(tc.p1, tc.p2, tc.r) + fmt.Println(" ", Case) + switch Case { + case CoR0, Diam: + fmt.Println(" Center: ", c1) + case Two: + fmt.Println(" Center 1: ", c1) + fmt.Println(" Center 2: ", c2) + } + fmt.Println() + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Haskell/circles-of-given-radius-through-two-points.hs b/Task/Circles-of-given-radius-through-two-points/Haskell/circles-of-given-radius-through-two-points.hs new file mode 100644 index 0000000000..0b6daf7e28 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Haskell/circles-of-given-radius-through-two-points.hs @@ -0,0 +1,36 @@ +add (a, b) (x, y) = (a + x, b + y) +sub (a, b) (x, y) = (a - x, b - y) +magSqr (a, b) = (a ^^ 2) + (b ^^ 2) +mag a = sqrt $ magSqr a +mul (a, b) c = (a * c, b * c) +div2 (a, b) c = (a / c, b / c) +perp (a, b) = (negate b, a) +norm a = a `div2` mag a + +circlePoints :: (Ord a, Floating a) => + (a, a) -> (a, a) -> a -> Maybe ((a, a), (a, a)) +circlePoints p q radius + | radius == 0 = Nothing + | p == q = Nothing + | diameter < magPQ = Nothing + | otherwise = Just (center1, center2) + where + diameter = radius * 2 + pq = p `sub` q + magPQ = mag pq + midpoint = (p `add` q) `div2` 2 + halfPQ = magPQ / 2 + magMidC = sqrt . abs $ (radius ^^ 2) - (halfPQ ^^ 2) + midC = (norm $ perp pq) `mul` magMidC + center1 = midpoint `add` midC + center2 = midpoint `sub` midC + +uncurry3 f (a, b, c) = f a b c + +main :: IO () +main = mapM_ (print . uncurry3 circlePoints) + [((0.1234, 0.9876), (0.8765, 0.2345), 2), + ((0 , 2 ), (0 , 0 ), 1), + ((0.1234, 0.9876), (0.1234, 0.9876), 2), + ((0.1234, 0.9876), (0.8765, 0.2345), 0.5), + ((0.1234, 0.9876), (0.1234, 0.1234), 0)] diff --git a/Task/Circles-of-given-radius-through-two-points/Icon/circles-of-given-radius-through-two-points.icon b/Task/Circles-of-given-radius-through-two-points/Icon/circles-of-given-radius-through-two-points.icon new file mode 100644 index 0000000000..a84c1ec440 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Icon/circles-of-given-radius-through-two-points.icon @@ -0,0 +1,22 @@ +procedure main() + A := [ [0.1234, 0.9876, 0.8765, 0.2345, 2.0], + [0.0000, 2.0000, 0.0000, 0.0000, 1.0], + [0.1234, 0.9876, 0.1234, 0.9876, 2.0], + [0.1234, 0.9876, 0.9765, 0.2345, 0.5], + [0.1234, 0.9876, 0.1234, 0.9876, 0.0] ] + every write(cCenter!!A) +end + +procedure cCenter(x1,y1, x2,y2, r) + if r <= 0 then return "Illegal radius" + r2 := r*2 + d := ((x2-x1)^2 + (y2-y1)^2)^0.5 + if d = 0 then return "Identical points, infinite number of circles" + if d > r2 then return "No circles possible" + z := (r^2-(d/2.0)^2)^0.5 + x3 := (x1+x2)/2.0; y3 := (y1+y2)/2.0 + cx1 := x3+z*(y1-y2)/d; cy1 := y3+z*(x2-x1)/d + cx2 := x3-z*(y1-y2)/d; cy2 := y3-z*(x2-x1)/d + if d = r2 then return "Single circle at ("||cx1||","||cy1||")" + return "("||cx1||","||cy1||") and ("||cx2||","||cy2||")" +end diff --git a/Task/Circles-of-given-radius-through-two-points/J/circles-of-given-radius-through-two-points.j b/Task/Circles-of-given-radius-through-two-points/J/circles-of-given-radius-through-two-points.j new file mode 100644 index 0000000000..cfa5d7f48b --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/J/circles-of-given-radius-through-two-points.j @@ -0,0 +1,38 @@ +[INPUT =: _5]\0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 + +average =: +/ % # + +circles =: verb define"1 + 'P0 P1 R' =. (j./"1)_2[\y NB. Use complex plane + C =. P0 average@:, P1 + BAD =: ":@:+. C + SEPARATION =. P0 |@- P1 + if. 0 = SEPARATION do. + if. 0 = R do. 'Degenerate point at ' , BAD + else. 'Any center at a distance ' , (":R) , ' from ' , BAD , ' works.' + end. + elseif. SEPARATION (> +:) R do. 'No solutions.' + elseif. SEPARATION (= +:) R do. 'Duplicate solutions with center at ' , BAD + elseif. 1 do. + ORTHOGONAL_DISTANCE =. R * 1 o. _2 o. R %~ | C - P0 + UNIT =: P1 *@:- P0 + OFFSETS =: ORTHOGONAL_DISTANCE * UNIT * j. _1 1 + C +.@:+ OFFSETS + end. +) + + ('x0 y0 x1 y1 r' ; 'center'),(;circles)"1 INPUT +┌───────────────────────────────┬────────────────────────────────────────────────────┐ +│x0 y0 x1 y1 r │center │ +├───────────────────────────────┼────────────────────────────────────────────────────┤ +│0.1234 0.9876 0.8765 0.2345 2 │_0.863212 _0.752112 │ +│ │ 1.86311 1.97421 │ +├───────────────────────────────┼────────────────────────────────────────────────────┤ +│0 2 0 0 1 │Duplicate solutions with center at 0 1 │ +├───────────────────────────────┼────────────────────────────────────────────────────┤ +│0.1234 0.9876 0.1234 0.9876 2 │Any center at a distance 2 from 0.1234 0.9876 works.│ +├───────────────────────────────┼────────────────────────────────────────────────────┤ +│0.1234 0.9876 0.8765 0.2345 0.5│No solutions. │ +├───────────────────────────────┼────────────────────────────────────────────────────┤ +│0.1234 0.9876 0.1234 0.9876 0 │Degenerate point at 0.1234 0.9876 │ +└───────────────────────────────┴────────────────────────────────────────────────────┘ diff --git a/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-1.maxima b/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-1.maxima new file mode 100644 index 0000000000..088e5f01a3 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-1.maxima @@ -0,0 +1,43 @@ +/* define helper function */ +vabs(a):= sqrt(a.a); +realp(e):=freeof(%i, e); + +/* get a general solution */ +sol: block( + [p1: [x1, y1], p2: [x2, y2], c: [x0, y0], eq], + local(r), + eq: [vabs(p1-c) = r, vabs(p2-c) = r], + load(to_poly_solve), + assume(r>0), + args(to_poly_solve(eq, c, use_grobner = true)))$ + +/* use general solution for concrete case */ +getsol(sol, x1, y1, x2, y2, r):=block([n, lsol], + if [x1, y1]=[x2, y2] then ( + print("infinity many solutions"), + return('infmany)), + lsol: sublist(''sol, 'realp), + n: length(lsol), + if n=0 then ( + print("no solutions"), + []) + else if n=1 then ( + print("single solution"), + lsol[1]) + else if [assoc('x0, lsol[1]), assoc('y0, lsol[1])]=[assoc('x0, lsol[2]), assoc('y0, lsol[2])] then ( + print("single solution"), + lsol[1]) + else ( + print("two solutions"), + lsol))$ + +/* [x1, y1, x2, y2, r] */ +d[1]: [0.1234, 0.9876, 0.8765, 0.2345, 2]; +d[2]: [0.0000, 2.0000, 0.0000, 0.0000, 1]; +d[3]: [0, 0, 0, 1, 0.4]; +d[4]: [0, 0, 0, 0, 0.4]; + +apply('getsol, cons(sol, d[1])); +apply('getsol, cons(sol, d[2])); +apply('getsol, cons(sol, d[3])); +apply('getsol, cons(sol, d[4])); diff --git a/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-2.maxima b/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-2.maxima new file mode 100644 index 0000000000..1e3c27c31c --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Maxima/circles-of-given-radius-through-two-points-2.maxima @@ -0,0 +1,13 @@ +apply('getsol, cons(sol, d[1])); +two solutions +(%o9) [[x0 = 1.86311180165819, y0 = 1.974211801658189], + [x0 = - 0.86321180165819, y0 = - 0.75211180165819]] +(%i10) apply('getsol, cons(sol, d[2])); +single solution +(%o10) [x0 = 0.0, y0 = 1.0] +(%i11) apply('getsol, cons(sol, d[3])); +no solutions +(%o11) [] +(%i12) apply('getsol, cons(sol, d[4])); +infinity many solutions +(%o12) infmany diff --git a/Task/Circles-of-given-radius-through-two-points/PARI-GP/circles-of-given-radius-through-two-points.pari b/Task/Circles-of-given-radius-through-two-points/PARI-GP/circles-of-given-radius-through-two-points.pari new file mode 100644 index 0000000000..f5d86a3289 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/PARI-GP/circles-of-given-radius-through-two-points.pari @@ -0,0 +1,10 @@ +circ(a, b, r)={ + if(a==b, return("impossible")); + my(h=(b-a)/2,t=sqrt(r^2-abs(h)^2)/abs(h)*h); + [a+h+t*I,a+h-t*I] +}; +circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, 2) +circ(0.0000 + 2.0000*I, 0.0000 + 0.0000*I, 1) +circ(0.1234 + 0.9876*I, 0.1234 + 0.9876*I, 2) +circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, .5) +circ(0.1234 + 0.9876*I, 0.1234 + 0.9876*I, 0) diff --git a/Task/Circles-of-given-radius-through-two-points/PL-I/circles-of-given-radius-through-two-points.pli b/Task/Circles-of-given-radius-through-two-points/PL-I/circles-of-given-radius-through-two-points.pli new file mode 100644 index 0000000000..b3d10ba617 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/PL-I/circles-of-given-radius-through-two-points.pli @@ -0,0 +1,42 @@ +twoci: Proc Options(main); + Dcl 1 *(5), + 2 m1x Dec Float Init(0.1234, 0,0.1234,0.1234,0.1234), + 2 m1y Dec Float Init(0.9876, 2,0.9876,0.9876,0.9876), + 2 m2x Dec Float Init(0.8765, 0,0.1234,0.8765,0.1234), + 2 m2y Dec Float Init(0.2345, 0,0.9876,0.2345,0.9876), + 2 r Dec Float Init( 2, 1, 2,0.5 , 0); + Dcl i Bin Fixed(31); + Put Edit(' x1 y1 x2 y2 r '|| + ' cir1x cir1y cir2x cir2y')(Skip,a); + Put Edit(' ====== ====== ====== ====== = '|| + ' ====== ====== ====== ======')(Skip,a); + Do i=1 To 5; + Put Edit(m1x(i),m1y(i),m2x(i),m2y(i),r(i)) + (Skip,4(f(7,4)),f(3)); + Put Edit(twocircles(m1x(i),m1y(i),m2x(i),m2y(i),r(i)))(a); + End; + + twoCircles: proc(m1x,m1y,m2x,m2y,r) Returns(Char(50) Var); + Dcl (m1x,m1y,m2x,m2y,r) Dec Float; + Dcl (cx,cy,bx,by,pb,x,y,x1,y1) Dec Float; + Dcl res Char(50) Var; + If r=0 then return(' radius of zero gives no circles.'); + x=(m2x-m1x)/2; + y=(m2y-m1y)/2; + bx=m1x+x; + by=m1y+y; + pb=sqrt(x**2+y**2); + cx=(m2x-m1x)/2; + cy=(m2y-m1y)/2; + bx=m1x+x; + by=m1y+y; + pb=sqrt(x**2+y**2) + if pb=0 then return(' coincident points give infinite circles'); + if pb>r then return(' points are too far apart for the given radius'); + cb=sqrt(r**2-pb**2); + x1=y*cb/pb; + y1=x*cb/pb + Put String(res) Edit((bx-x1),(by+y1),(bx+x1),(by-y1))(4(f(8,4))); + Return(res); + End; + End; diff --git a/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-1.pl6 b/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-1.pl6 new file mode 100644 index 0000000000..eb49b56577 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-1.pl6 @@ -0,0 +1,21 @@ +sub circles(@A, @B where (not [and] @A Z== @B), $radius where * > 0) { + my @middle = .5 X* (@A Z+ @B); + my @diff = @A Z- @B; + my @orth = -@diff[1], @diff[0] X/ + 2 * tan asin 2*$radius R/ sqrt [+] @diff X**2; + + return (@middle Z+ @orth).item, (@middle Z- @orth).item; +} + +my @input = +\([0.1234, 0.9876], [0.8765, 0.2345], 2.0), +\([0.0000, 2.0000], [0.0000, 0.0000], 1.0), +\([0.1234, 0.9876], [0.1234, 0.9876], 2.0), +\([0.1234, 0.9876], [0.8765, 0.2345], 0.5), +\([0.1234, 0.9876], [0.1234, 0.9876], 0.0), +; + +for @input -> $input { + say $input.perl, ": ", + try { say join " and ", circles(|$input) } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-2.pl6 b/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-2.pl6 new file mode 100644 index 0000000000..89c3f6264d --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Perl-6/circles-of-given-radius-through-two-points-2.pl6 @@ -0,0 +1,14 @@ +sub circles($a, $b where $b != $a, $r) { + my $h = ($b - $a)/2; + my $l = sqrt($r**2 - $h.abs**2); + return map { $a + $h + $l * $_ * $h/$h.abs }, + i, -i; +} + +my @input = +\(0.1234 + 0.9876i, 0.8765 + 0.2345i, 2.0), +\(0.0000 + 2.0000i, 0.0000 + 0.0000i, 1.0), +\(0.1234 + 0.9876i, 0.1234 + 0.9876i, 2.0), +\(0.1234 + 0.9876i, 0.8765 + 0.2345i, 0.5), +\(0.1234 + 0.9876i, 0.1234 + 0.9876i, 0.0), +; diff --git a/Task/Circles-of-given-radius-through-two-points/Python/circles-of-given-radius-through-two-points.py b/Task/Circles-of-given-radius-through-two-points/Python/circles-of-given-radius-through-two-points.py new file mode 100644 index 0000000000..1fde5e36c4 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Python/circles-of-given-radius-through-two-points.py @@ -0,0 +1,45 @@ +from collections import namedtuple +from math import sqrt + +Pt = namedtuple('Pt', 'x, y') +Circle = Cir = namedtuple('Circle', 'x, y, r') + +def circles_from_p1p2r(p1, p2, r): + 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' + if r == 0.0: + raise ValueError('radius of zero') + (x1, y1), (x2, y2) = p1, p2 + if p1 == p2: + raise ValueError('coincident points gives infinite number of Circles') + # delta x, delta y between points + dx, dy = x2 - x1, y2 - y1 + # dist between points + q = sqrt(dx**2 + dy**2) + if q > 2.0*r: + raise ValueError('separation of points > diameter') + # halfway point + x3, y3 = (x1+x2)/2, (y1+y2)/2 + # distance along the mirror line + d = sqrt(r**2-(q/2)**2) + # One answer + c1 = Cir(x = x3 - d*dy/q, + y = y3 + d*dx/q, + r = abs(r)) + # The other answer + c2 = Cir(x = x3 + d*dy/q, + y = y3 - d*dx/q, + r = abs(r)) + return c1, c2 + +if __name__ == '__main__': + for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0), + (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0), + (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0), + (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5), + (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]: + print('Through points:\n %r,\n %r\n and radius %f\nYou can construct the following circles:' + % (p1, p2, r)) + try: + print(' %r\n %r\n' % circles_from_p1p2r(p1, p2, r)) + except ValueError as v: + print(' ERROR: %s\n' % (v.args[0],)) diff --git a/Task/Circles-of-given-radius-through-two-points/README b/Task/Circles-of-given-radius-through-two-points/README new file mode 100644 index 0000000000..331d218935 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points diff --git a/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx new file mode 100644 index 0000000000..0f508944c8 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx @@ -0,0 +1,31 @@ +/*REXX pgm finds 2 circles with a specific radius given two (X,Y) points*/ +@. = +@.1 = 0.1234 0.9876 0.8765 0.2345 2 +@.2 = 0 2 0 0 1 +@.3 = 0.1234 0.9876 0.1234 0.9876 2 +@.4 = 0.1234 0.9876 0.8765 0.2345 0.5 +@.5 = 0.1234 0.9876 0.1234 0.9876 0 +say ' x1 y1 x2 y2 radius circle1x circle1y circle2x circle2y' +say ' ──────── ──────── ──────── ──────── ────── ──────── ──────── ──────── ────────' + do j=1 while @.j\=='' /*process all given points&radius*/ + do k=1 for 4; w.k=f(word(@.j,k)) /*format # with 4 dec digs*/ + end /*k*/ + say w.1 w.2 w.3 w.4 center(word(@.j,5)/1,9) "───► " twoCircles(@.j) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────F subroutine────────────────────────*/ +f: return right(format(arg(1),,4),9) /*format a # with 4 decimal digs.*/ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +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 +/*──────────────────────────────────TWOCIRCLES subroutine───────────────*/ +twoCircles: procedure; parse arg px py qx qy r . +x=(qx-px)/2; y=(qy-py)/2; bx=px+x; by=py+y; pb=sqrt(x**2+y**2) +if r=0 then return 'radius of zero gives no circles' +if pb=0 then return 'coincident points give infinite circles' +if pb>r then return 'points are too far apart for the given radius' +cb=sqrt(r**2-pb**2); x1=y*cb/pb; y1=x*cb/pb +return f(bx-x1) f(by+y1) f(bx+x1) f(by-y1) diff --git a/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-1.rkt b/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-1.rkt new file mode 100644 index 0000000000..5ed5c84a06 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-1.rkt @@ -0,0 +1,24 @@ +#lang racket +(require plot/utils) + +(define (circle-centers p1 p2 r) + (when (zero? r) (err "zero radius.")) + (when (equal? p1 p2) (err "the points coinside.")) + ; the midle point + (define m (v/ (v+ p1 p2) 2)) + ; the vector connecting given points + (define d (v/ (v- p1 p2) 2)) + ; the distance between the center of the circle and the middle point + (define ξ (- (sqr r) (vmag^2 d))) + (when (negative? ξ) (err "given radius is less then the distance between points.")) + ; the unit vector orthogonal to the delta + (define n (vnormalize (orth d))) + ; the shift along the direction orthogonal to the delta + (define x (v* n (sqrt ξ))) + (values (v+ m x) (v- m x))) + +;; error message +(define (err m) (error "Impossible to build a circle:" m)) + +;; returns a vector which is orthogonal to the geven one +(define orth (match-lambda [(vector x y) (vector y (- x))])) diff --git a/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-2.rkt b/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-2.rkt new file mode 100644 index 0000000000..fa840c2d1a --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Racket/circles-of-given-radius-through-two-points-2.rkt @@ -0,0 +1,15 @@ +(require 2htdp/image) + +(define/match (point v) + [{(vector x y)} (λ (s) (place-image (circle 2 "solid" "black") x y s))]) + +(define/match (circ v r) + [{(vector x y) r} (λ (s) (place-image (circle r "outline" "red") x y s))]) + +(define p1 #(40 50)) +(define p2 #(60 30)) +(define r 20) +(define-values (x1 x2) (circle-centers p1 p2 r)) + +((compose (point p1) (point p2) (circ x1 r) (circ x2 r)) + (empty-scene 100 100)) diff --git a/Task/Circles-of-given-radius-through-two-points/Ruby/circles-of-given-radius-through-two-points.rb b/Task/Circles-of-given-radius-through-two-points/Ruby/circles-of-given-radius-through-two-points.rb new file mode 100644 index 0000000000..28e96a035f --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Ruby/circles-of-given-radius-through-two-points.rb @@ -0,0 +1,37 @@ +Pt = Struct.new(:x, :y) +Circle = Struct.new(:x, :y, :r) + +def circles_from(pt1, pt2, r) + raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0 + # handle single point and r == 0 + return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0 + dx, dy = pt2.x - pt1.x, pt2.y - pt1.y + # distance between points + q = Math.hypot(dx, dy) + # Also catches pt1 != pt2 && r == 0 + raise ArgumentError, "Distance of points > diameter." if q > 2.0*r + # halfway point + x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0 + d = (r**2 - (q/2)**2)**0.5 + [Circle.new(x3 - d*dy/q, y3 + d*dx/q, r), + Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq +end + +# Demo: +ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0], + [Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0], + [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0], + [Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5], + [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]] + +ar.each do |p1, p2, r| + print "Given points:\n #{p1.values},\n #{p2.values}\n and radius #{r}\n" + begin + circles = circles_from(p1, p2, r) + puts "You can construct the following circles:" + circles.each{|c| puts " #{c}"} + rescue ArgumentError => e + puts e + end + puts +end diff --git a/Task/Circles-of-given-radius-through-two-points/Rust/circles-of-given-radius-through-two-points.rust b/Task/Circles-of-given-radius-through-two-points/Rust/circles-of-given-radius-through-two-points.rust new file mode 100644 index 0000000000..fc5787a302 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Rust/circles-of-given-radius-through-two-points.rust @@ -0,0 +1,58 @@ +use std::fmt; + +struct Point { + x: f64, + y: f64 +} + +impl Point { + fn new(x : f64, y : f64) -> Point{ + Point{x : x, y : y} + } + fn distance (&self, p : Point) -> f64{ + ( (self.x - p.x).powi(2) + (self.y - p.y).powi(2) ).sqrt() + } +} + +impl fmt::Show for Point { // a Point become printable in console + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({:.4f}, {:.4f})", self.x, self.y) + } +} + +fn is_circle(p1 : Point, p2 : Point, radius : f64){ + let separation = p1.distance(p2); + + if separation == 0.0 { + if radius == 0.0 { + println!("No circles can be drawn through {}", p1); + } else { + println!("Infinitely many circles can be drawn through {}", p1); + } + } else if separation == 2.0 * radius { + println!("Given points are opposite ends of a diameter of the circle with center ({:.4f},{:.4f}) and radius {:.4f}",(p1.x+p2.x) / 2.0, (p1.y+p2.y) / 2.0, radius); + } else if separation > 2.0 * radius { + println!("Given points are farther away from each other than a diameter of a circle with radius {:.4f}", radius); + } else { + let mirror_distance = (radius.powi(2) - (separation / 2.0).powi(2)).sqrt(); + + println!("Two circles are possible."); + println!("Circle C1 with center ({:.4f}, {:.4f}), radius {:.4f} and Circle C2 with center ({:.4f}, {:.4f}), radius {:.4f}", ((p1.x + p2.x) / 2.0) + mirror_distance * (p1.y-p2.y)/separation, (p1.y+p2.y) / 2.0 + mirror_distance*(p2.x-p1.x)/separation, radius, (p1.x+p2.x) / 2.0 - mirror_distance*(p1.y-p2.y)/separation, (p1.y+p2.y) / 2.0 - mirror_distance*(p2.x-p1.x)/separation, radius); + } +} + +fn main() { + let points : Vec<(Point, Point)> = vec!( + (Point::new(0.1234, 0.9876), Point::new(0.8765, 0.2345)), + (Point::new(0.0000, 2.0000), Point::new(0.0000, 0.0000)), + (Point::new(0.1234, 0.9876), Point::new(0.1234, 0.9876)), + (Point::new(0.1234, 0.9876), Point::new(0.8765, 0.2345)), + (Point::new(0.1234, 0.9876), Point::new(0.1234, 0.9876)) + ); + let radii : Vec = vec!(2.0, 1.0, 2.0, 0.5, 0.0); + + for (p, &r) in points.iter().zip(radii.iter()) { + println!("\nPoints : {} \t Radius : {:.4f}", p, r); + is_circle(p.val0(), p.val1(), r); + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Seed7/circles-of-given-radius-through-two-points.seed7 b/Task/Circles-of-given-radius-through-two-points/Seed7/circles-of-given-radius-through-two-points.seed7 new file mode 100644 index 0000000000..b6efafccd9 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Seed7/circles-of-given-radius-through-two-points.seed7 @@ -0,0 +1,70 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const type: point is new struct + var float: x is 0.0; + var float: y is 0.0; + end struct; + +const func point: point (in float: x, in float: y) is func + result + var point: aPoint is point.value; + begin + aPoint.x := x; + aPoint.y := y; + end func; + +const func float: distance (in point: p1, in point: p2) is + return sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2); + +const proc: findCircles (in point: p1, in point: p2, in float: radius) is func + local + var float: separation is 0.0; + var float: mirrorDistance is 0.0; + begin + separation := distance(p1, p2); + if separation = 0.0 then + if radius = 0.0 then + write("Radius of zero. No circles can be drawn through ("); + else + write("Infinitely many circles can be drawn through ("); + end if; + writeln(p1.x digits 4 <& ", " <& p1.y digits 4 <& ")"); + elsif separation = 2.0 * radius then + writeln("Given points are opposite ends of a diameter of the circle with center (" <& + (p1.x + p2.x) / 2.0 digits 4 <& ", " <& (p1.y + p2.y) / 2.0 digits 4 <& ") and radius " <& + radius digits 4); + elsif separation > 2.0 * radius then + writeln("Given points are farther away from each other than a diameter of a circle with radius " <& + radius digits 4); + else + mirrorDistance := sqrt(radius ** 2 - (separation / 2.0) ** 2); + writeln("Two circles are possible."); + writeln("Circle C1 with center (" <& + (p1.x + p2.x) / 2.0 + mirrorDistance*(p1.y - p2.y) / separation digits 4 <& ", " <& + (p1.y + p2.y) / 2.0 + mirrorDistance*(p2.x - p1.x) / separation digits 4 <& "), radius " <& + radius digits 4); + writeln("Circle C2 with center (" <& + (p1.x + p2.x) / 2.0 - mirrorDistance*(p1.y - p2.y) / separation digits 4 <& ", " <& + (p1.y + p2.y) / 2.0 - mirrorDistance*(p2.x - p1.x) / separation digits 4 <& "), radius " <& + radius digits 4); + end if; + end func; + +const proc: main is func + local + const array array float: cases is [] ( + [] (0.1234, 0.9876, 0.8765, 0.2345, 2.0), + [] (0.0000, 2.0000, 0.0000, 0.0000, 1.0), + [] (0.1234, 0.9876, 0.1234, 0.9876, 2.0), + [] (0.1234, 0.9876, 0.8765, 0.2345, 0.5), + [] (0.1234, 0.9876, 0.1234, 0.9876, 0.0)); + var integer: index is 0; + begin + for index range 1 to 5 do + writeln("Case " <& index <& ":"); + findCircles(point(cases[index][1], cases[index][2]), + point(cases[index][3], cases[index][4]), cases[index][5]); + end for; + end func; diff --git a/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-1.tcl b/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-1.tcl new file mode 100644 index 0000000000..45d23fbcaf --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-1.tcl @@ -0,0 +1,32 @@ +proc findCircles {p1 p2 r} { + lassign $p1 x1 y1 + lassign $p2 x2 y2 + # Special case: coincident & zero size + if {$x1 == $x2 && $y1 == $y2 && $r == 0.0} { + return [list [list $x1 $y1 0.0]] + } + if {$r <= 0.0} { + error "radius must be positive for sane results" + } + if {$x1 == $x2 && $y1 == $y2} { + error "no sane solution: points are coincident" + } + + # Calculate distance apart and separation vector + set dx [expr {$x2 - $x1}] + set dy [expr {$y2 - $y1}] + set q [expr {hypot($dx, $dy)}] + if {$q > 2*$r} { + error "no solution: points are further apart than required diameter" + } + + # Calculate midpoint + set x3 [expr {($x1+$x2)/2.0}] + set y3 [expr {($y1+$y2)/2.0}] + # Fractional distance along the mirror line + set f [expr {($r**2 - ($q/2.0)**2)**0.5 / $q}] + # The two answers + set c1 [list [expr {$x3 - $f*$dy}] [expr {$y3 + $f*$dx}] $r] + set c2 [list [expr {$x3 + $f*$dy}] [expr {$y3 - $f*$dx}] $r] + return [list $c1 $c2] +} diff --git a/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-2.tcl b/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-2.tcl new file mode 100644 index 0000000000..45d80c8c9a --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Tcl/circles-of-given-radius-through-two-points-2.tcl @@ -0,0 +1,16 @@ +foreach {p1 p2 r} { + {0.1234 0.9876} {0.8765 0.2345} 2.0 + {0.0000 2.0000} {0.0000 0.0000} 1.0 + {0.1234 0.9876} {0.1234 0.9876} 2.0 + {0.1234 0.9876} {0.8765 0.2345} 0.5 + {0.1234 0.9876} {0.1234 0.9876} 0.0 +} { + puts "p1:([join $p1 {, }]) p2:([join $p2 {, }]) r:$r =>" + if {[catch { + foreach c [findCircles $p1 $p2 $r] { + puts "\tCircle:([join $c {, }])" + } + } msg]} { + puts "\tERROR: $msg" + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/XPL0/circles-of-given-radius-through-two-points.xpl0 b/Task/Circles-of-given-radius-through-two-points/XPL0/circles-of-given-radius-through-two-points.xpl0 new file mode 100644 index 0000000000..0d3d3b71c4 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/XPL0/circles-of-given-radius-through-two-points.xpl0 @@ -0,0 +1,25 @@ +include c:\cxpl\codes; + +proc Circles; real Data; \Show centers of circles, given points P & Q and radius +real Px, Py, Qx, Qy, R, X, Y, X1, Y1, Bx, By, PB, CB; +[Px:= Data(0); Py:= Data(1); Qx:= Data(2); Qy:= Data(3); R:= Data(4); +if R = 0.0 then [Text(0, "Radius = zero gives no circles^M^J"); return]; +X:= (Qx-Px)/2.0; Y:= (Qy-Py)/2.0; +Bx:= Px+X; By:= Py+Y; +PB:= sqrt(X*X + Y*Y); +if PB = 0.0 then [Text(0, "Coincident points give infinite circles^M^J"); return]; +if PB > R then [Text(0, "Points are too far apart for radius^M^J"); return]; +CB:= sqrt(R*R - PB*PB); +X1:= Y*CB/PB; Y1:= X*CB/PB; +RlOut(0, Bx-X1); ChOut(0, ^,); RlOut(0, By+Y1); ChOut(0, 9\tab\); +RlOut(0, Bx+X1); ChOut(0, ^,); RlOut(0, By-Y1); CrLf(0); +]; + +real Tbl; int I; +[Tbl:=[[0.1234, 0.9876, 0.8765, 0.2345, 2.0], + [0.0000, 2.0000, 0.0000, 0.0000, 1.0], + [0.1234, 0.9876, 0.1234, 0.9876, 2.0], + [0.1234, 0.9876, 0.8765, 0.2345, 0.5], + [0.1234, 0.9876, 0.1234, 0.9876, 0.0]]; +for I:= 0 to 4 do Circles(Tbl(I)); +] diff --git a/Task/Closures-Value-capture/00DESCRIPTION b/Task/Closures-Value-capture/00DESCRIPTION new file mode 100644 index 0000000000..6a655de60d --- /dev/null +++ b/Task/Closures-Value-capture/00DESCRIPTION @@ -0,0 +1,11 @@ +'''Task:''' Create a list of 10 functions, in the simplest manner possible +(anonymous functions are encouraged), such that the function at index i +(you may choose to start i from either 0 or 1), when run, +should return the square of the index, that is, i^2. +Display the result of running any but the last function, +to demonstrate that the function indeed remembers its value. + +'''Goal:''' To demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. +In imperative languages, one would generally use a loop with a mutable counter variable. +For each function to maintain the correct number, it has to capture the ''value'' +of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. diff --git a/Task/Closures-Value-capture/ALGOL-68/closures-value-capture.alg b/Task/Closures-Value-capture/ALGOL-68/closures-value-capture.alg new file mode 100644 index 0000000000..bc3cfec73e --- /dev/null +++ b/Task/Closures-Value-capture/ALGOL-68/closures-value-capture.alg @@ -0,0 +1,11 @@ +[1:10]PROC(BOOL)INT squares; + +FOR i FROM 1 TO 10 DO + HEAP INT captured i := i; + squares[i] := ((REF INT by ref i, INT by val i,BOOL b)INT:(INT i = by ref i; (b|by ref i := 0); by val i*i)) + (captured i, captured i,) +OD; + +FOR i FROM 1 TO 8 DO print(squares[i](i MOD 2 = 0)) OD; +print(new line); +FOR i FROM 1 TO 10 DO print(squares[i](FALSE)) OD diff --git a/Task/Closures-Value-capture/Ada/closures-value-capture.ada b/Task/Closures-Value-capture/Ada/closures-value-capture.ada new file mode 100644 index 0000000000..5dcf0482e1 --- /dev/null +++ b/Task/Closures-Value-capture/Ada/closures-value-capture.ada @@ -0,0 +1,30 @@ +with Ada.Text_IO; + +procedure Value_Capture is + + protected type Fun is -- declaration of the type of a protected object + entry Init(Index: Natural); + function Result return Natural; + private + N: Natural := 0; + end Fun; + + protected body Fun is -- the implementation of a protected object + entry Init(Index: Natural) when N=0 is + begin -- after N has been set to a nonzero value, it cannot be changed any more + N := Index; + end Init; + function Result return Natural is (N*N); + end Fun; + + A: array (1 .. 10) of Fun; -- an array holding 10 protected objects + +begin + for I in A'Range loop -- initialize the protected objects + A(I).Init(I); + end loop; + + for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last + Ada.Text_IO.Put(Integer'Image(A(I).Result)); + end loop; +end Value_Capture; diff --git a/Task/Closures-Value-capture/Axiom/closures-value-capture-1.axiom b/Task/Closures-Value-capture/Axiom/closures-value-capture-1.axiom new file mode 100644 index 0000000000..5c8079d213 --- /dev/null +++ b/Task/Closures-Value-capture/Axiom/closures-value-capture-1.axiom @@ -0,0 +1,5 @@ +)abbrev package TESTP TestPackage +TestPackage() : with + test: () -> List((()->Integer)) + == add + test() == [(() +-> i^2) for i in 1..10] diff --git a/Task/Closures-Value-capture/Axiom/closures-value-capture-2.axiom b/Task/Closures-Value-capture/Axiom/closures-value-capture-2.axiom new file mode 100644 index 0000000000..6a7cbfa72f --- /dev/null +++ b/Task/Closures-Value-capture/Axiom/closures-value-capture-2.axiom @@ -0,0 +1 @@ +[x() for x in test()] diff --git a/Task/Closures-Value-capture/Axiom/closures-value-capture-3.axiom b/Task/Closures-Value-capture/Axiom/closures-value-capture-3.axiom new file mode 100644 index 0000000000..ea2f30a4b2 --- /dev/null +++ b/Task/Closures-Value-capture/Axiom/closures-value-capture-3.axiom @@ -0,0 +1,2 @@ +[1,4,9,16,25,36,49,64,81,100] + Type: List(Integer) diff --git a/Task/Closures-Value-capture/Babel/closures-value-capture-1.pb b/Task/Closures-Value-capture/Babel/closures-value-capture-1.pb new file mode 100644 index 0000000000..ae58d7158c --- /dev/null +++ b/Task/Closures-Value-capture/Babel/closures-value-capture-1.pb @@ -0,0 +1,10 @@ +((main { + { iter + 1 take bons 1 take + dup cp + {*} cp + 3 take + append } + 10 times + collect ! + {eval %d nl <<} each })) diff --git a/Task/Closures-Value-capture/Babel/closures-value-capture-2.pb b/Task/Closures-Value-capture/Babel/closures-value-capture-2.pb new file mode 100644 index 0000000000..27e71acb5d --- /dev/null +++ b/Task/Closures-Value-capture/Babel/closures-value-capture-2.pb @@ -0,0 +1,10 @@ +100 +81 +64 +49 +36 +25 +16 +9 +4 +1 diff --git a/Task/Closures-Value-capture/Bracmat/closures-value-capture.bracmat b/Task/Closures-Value-capture/Bracmat/closures-value-capture.bracmat new file mode 100644 index 0000000000..7c6d0f0b43 --- /dev/null +++ b/Task/Closures-Value-capture/Bracmat/closures-value-capture.bracmat @@ -0,0 +1,8 @@ +( -1:?i +& :?funcs +& whl + ' ( 1+!i:<10:?i + & !funcs ()'(.$i^2):?funcs + ) +& whl'(!funcs:%?func %?funcs&out$(!func$)) +); diff --git a/Task/Closures-Value-capture/C++/closures-value-capture.cpp b/Task/Closures-Value-capture/C++/closures-value-capture.cpp new file mode 100644 index 0000000000..8b6f55c89a --- /dev/null +++ b/Task/Closures-Value-capture/C++/closures-value-capture.cpp @@ -0,0 +1,12 @@ +#include +#include +#include + +int main() { + std::vector > funcs; + for (int i = 0; i < 10; i++) + funcs.push_back([=]() { return i * i; }); + for ( std::function f : funcs ) + std::cout << f( ) << std::endl ; + return 0; +} diff --git a/Task/Closures-Value-capture/C/closures-value-capture-1.c b/Task/Closures-Value-capture/C/closures-value-capture-1.c new file mode 100644 index 0000000000..135d32c466 --- /dev/null +++ b/Task/Closures-Value-capture/C/closures-value-capture-1.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +typedef int (*f_int)(); + +#define TAG 0xdeadbeef +int _tmpl() { + volatile int x = TAG; + return x * x; +} + +#define PROT (PROT_EXEC | PROT_WRITE) +#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) +f_int dupf(int v) +{ + size_t len = (void*)dupf - (void*)_tmpl; + f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0); + char *p; + if(ret == MAP_FAILED) { + perror("mmap"); + exit(-1); + } + memcpy(ret, _tmpl, len); + for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++) + if (*(int *)p == TAG) *(int *)p = v; + return ret; +} + +int main() +{ + f_int funcs[10]; + int i; + for (i = 0; i < 10; i++) funcs[i] = dupf(i); + + for (i = 0; i < 9; i++) + printf("func[%d]: %d\n", i, funcs[i]()); + + return 0; +} diff --git a/Task/Closures-Value-capture/C/closures-value-capture-2.c b/Task/Closures-Value-capture/C/closures-value-capture-2.c new file mode 100644 index 0000000000..b91877557d --- /dev/null +++ b/Task/Closures-Value-capture/C/closures-value-capture-2.c @@ -0,0 +1,9 @@ +func[0]: 0 +func[1]: 1 +func[2]: 4 +func[3]: 9 +func[4]: 16 +func[5]: 25 +func[6]: 36 +func[7]: 49 +func[8]: 64 diff --git a/Task/Closures-Value-capture/C/closures-value-capture-3.c b/Task/Closures-Value-capture/C/closures-value-capture-3.c new file mode 100644 index 0000000000..2f65c661bf --- /dev/null +++ b/Task/Closures-Value-capture/C/closures-value-capture-3.c @@ -0,0 +1,33 @@ +void init(void) +{ + t = intern(lit("t")); + x = intern(lit("x")); +} + +val square(val env) +{ + val xbind = assoc(env, x); /* look up binding of variable x in env */ + val xval = cdr(xbind); /* value is the cdr of the binding cell */ + return num(cnum(xval) * cnum(xval)); +} + +int main(void) +{ + int i; + val funlist = nil, iter; + + init(); + + for (i = 0; i < 10; i++) { + val closure_env = cons(cons(x, num(i)), nil); + funlist = cons(func_f0(closure_env, square), funlist); + } + + for (iter = funlist; iter != nil; iter = cdr(iter)) { + val fun = car(iter); + val square = funcall(fun, nao); + + printf("%d\n", cnum(square)); + } + return 0; +} diff --git a/Task/Closures-Value-capture/CoffeeScript/closures-value-capture.coffee b/Task/Closures-Value-capture/CoffeeScript/closures-value-capture.coffee new file mode 100644 index 0000000000..9d43c21332 --- /dev/null +++ b/Task/Closures-Value-capture/CoffeeScript/closures-value-capture.coffee @@ -0,0 +1,5 @@ +# Generate an array of functions. +funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i ) + +# Call each function to demonstrate value capture. +console.log func() for func in funcs diff --git a/Task/Closures-Value-capture/Common-Lisp/closures-value-capture.lisp b/Task/Closures-Value-capture/Common-Lisp/closures-value-capture.lisp new file mode 100644 index 0000000000..caae199592 --- /dev/null +++ b/Task/Closures-Value-capture/Common-Lisp/closures-value-capture.lisp @@ -0,0 +1,9 @@ +CL-USER> (defparameter alist + (loop for i from 1 to 10 + collect (cons i (let ((i i)) + (lambda () (* i i)))))) +ALIST +CL-USER> (funcall (cdr (assoc 2 alist))) +4 +CL-USER> (funcall (cdr (assoc 8 alist))) +64 diff --git a/Task/Closures-Value-capture/D/closures-value-capture-1.d b/Task/Closures-Value-capture/D/closures-value-capture-1.d new file mode 100644 index 0000000000..f5649cd0b0 --- /dev/null +++ b/Task/Closures-Value-capture/D/closures-value-capture-1.d @@ -0,0 +1,10 @@ +import std.stdio; + +void main() { + int delegate()[] funcs; + + foreach (i; 0 .. 10) + funcs ~= (i => () => i ^^ 2)(i); + + writeln(funcs[3]()); +} diff --git a/Task/Closures-Value-capture/D/closures-value-capture-2.d b/Task/Closures-Value-capture/D/closures-value-capture-2.d new file mode 100644 index 0000000000..ce13bfcc12 --- /dev/null +++ b/Task/Closures-Value-capture/D/closures-value-capture-2.d @@ -0,0 +1,5 @@ +void main() { + import std.stdio, std.range, std.algorithm; + + 10.iota.map!(i => () => i ^^ 2).map!q{ a() }.writeln; +} diff --git a/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi b/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi new file mode 100644 index 0000000000..6dad738f4f --- /dev/null +++ b/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi @@ -0,0 +1,19 @@ +program Project1; + +type + TFuncIntResult = reference to function : integer; + +var + Funcs : array [0..9] of TFuncIntResult; + i : integer; + +begin + // Create 10 anonymous functions + for i := Low(Funcs) to High(Funcs) do + Funcs[i] := function() : integer begin Result := i*i; end; + + // call all 10 functions + for i := Low(Funcs) to High(Funcs) do + writeln( Funcs[i]() ); + +end. diff --git a/Task/Closures-Value-capture/Emacs-Lisp/closures-value-capture.l b/Task/Closures-Value-capture/Emacs-Lisp/closures-value-capture.l new file mode 100644 index 0000000000..d08c2272ca --- /dev/null +++ b/Task/Closures-Value-capture/Emacs-Lisp/closures-value-capture.l @@ -0,0 +1,6 @@ +(require 'cl) +(mapcar 'funcall + (mapcar (lambda (x) + (lexical-let ((x x)) + (lambda () (* x x)))) [1 2 3 4 5 6 7 8 9 10])) +;; => (1 4 9 16 25 36 49 64 81 100) diff --git a/Task/Closures-Value-capture/Erlang/closures-value-capture.erl b/Task/Closures-Value-capture/Erlang/closures-value-capture.erl new file mode 100644 index 0000000000..81bdcb2603 --- /dev/null +++ b/Task/Closures-Value-capture/Erlang/closures-value-capture.erl @@ -0,0 +1,13 @@ +-module(capture_demo). +-export([demo/0]). + +demo() -> + Funs = lists:map(fun (X) -> + fun () -> + X * X + end + end, + lists:seq(1,10)), + lists:foreach(fun (F) -> + io:fwrite("~B~n",[F()]) + end, Funs). diff --git a/Task/Closures-Value-capture/Factor/closures-value-capture-1.factor b/Task/Closures-Value-capture/Factor/closures-value-capture-1.factor new file mode 100644 index 0000000000..a6d5262d63 --- /dev/null +++ b/Task/Closures-Value-capture/Factor/closures-value-capture-1.factor @@ -0,0 +1,14 @@ +USING: io kernel locals math prettyprint sequences ; + +[let + ! Create a sequence of 10 quotations + 10 iota [ + :> i ! Bind lexical variable i + [ i i * ] ! Push a quotation to calculate i squared + ] map :> seq + + { 3 8 } [ + dup pprint " squared is " write + seq nth call . + ] each +] diff --git a/Task/Closures-Value-capture/Factor/closures-value-capture-2.factor b/Task/Closures-Value-capture/Factor/closures-value-capture-2.factor new file mode 100644 index 0000000000..4d3e5ed2de --- /dev/null +++ b/Task/Closures-Value-capture/Factor/closures-value-capture-2.factor @@ -0,0 +1,12 @@ +USING: fry io kernel math prettyprint sequences ; + +! Push a sequence of 10 quotations +10 iota [ + '[ _ dup * ] ! Push a quotation ( i -- i*i ) +] map + +{ 3 8 } [ + dup pprint " squared is " write + over nth call . +] each +drop diff --git a/Task/Closures-Value-capture/Fantom/closures-value-capture.fantom b/Task/Closures-Value-capture/Fantom/closures-value-capture.fantom new file mode 100644 index 0000000000..bd4bf31863 --- /dev/null +++ b/Task/Closures-Value-capture/Fantom/closures-value-capture.fantom @@ -0,0 +1,17 @@ +class Closures +{ + Void main () + { + // define a list of functions, which take no arguments and return an Int + |->Int|[] functions := [,] + + // create and store a function which returns i*i for i in 0 to 10 + (0..10).each |Int i| + { + functions.add (|->Int| { i*i }) + } + + // show result of calling function at index position 7 + echo ("Function at index: " + 7 + " outputs " + functions[7].call) + } +} diff --git a/Task/Closures-Value-capture/Go/closures-value-capture.go b/Task/Closures-Value-capture/Go/closures-value-capture.go new file mode 100644 index 0000000000..55700b5ab0 --- /dev/null +++ b/Task/Closures-Value-capture/Go/closures-value-capture.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + fs := make([]func() int, 10) + for i := range fs { + i := i + fs[i] = func() int { + return i * i + } + } + fmt.Println("func #0:", fs[0]()) + fmt.Println("func #3:", fs[3]()) +} diff --git a/Task/Closures-Value-capture/Groovy/closures-value-capture-1.groovy b/Task/Closures-Value-capture/Groovy/closures-value-capture-1.groovy new file mode 100644 index 0000000000..bb784a81a5 --- /dev/null +++ b/Task/Closures-Value-capture/Groovy/closures-value-capture-1.groovy @@ -0,0 +1 @@ +def closures = (0..9).collect{ i -> { -> i*i } } diff --git a/Task/Closures-Value-capture/Groovy/closures-value-capture-2.groovy b/Task/Closures-Value-capture/Groovy/closures-value-capture-2.groovy new file mode 100644 index 0000000000..a31cd4e748 --- /dev/null +++ b/Task/Closures-Value-capture/Groovy/closures-value-capture-2.groovy @@ -0,0 +1,4 @@ +assert closures instanceof List +assert closures.size() == 10 +closures.each { assert it instanceof Closure } +println closures[7]() diff --git a/Task/Closures-Value-capture/Haskell/closures-value-capture-1.hs b/Task/Closures-Value-capture/Haskell/closures-value-capture-1.hs new file mode 100644 index 0000000000..d6708343d0 --- /dev/null +++ b/Task/Closures-Value-capture/Haskell/closures-value-capture-1.hs @@ -0,0 +1 @@ +fs = map (\i _ -> i * i) [1 .. 10] diff --git a/Task/Closures-Value-capture/Haskell/closures-value-capture-2.hs b/Task/Closures-Value-capture/Haskell/closures-value-capture-2.hs new file mode 100644 index 0000000000..3d070ae8df --- /dev/null +++ b/Task/Closures-Value-capture/Haskell/closures-value-capture-2.hs @@ -0,0 +1 @@ +fs = [const $ i * i | i <- [1 .. 10]] diff --git a/Task/Closures-Value-capture/Haskell/closures-value-capture-3.hs b/Task/Closures-Value-capture/Haskell/closures-value-capture-3.hs new file mode 100644 index 0000000000..74b705b81a --- /dev/null +++ b/Task/Closures-Value-capture/Haskell/closures-value-capture-3.hs @@ -0,0 +1 @@ +fs = take 10 coFs where coFs = [const $ i * i | i <- [1 ..]] diff --git a/Task/Closures-Value-capture/Haskell/closures-value-capture-4.hs b/Task/Closures-Value-capture/Haskell/closures-value-capture-4.hs new file mode 100644 index 0000000000..5da5a17e15 --- /dev/null +++ b/Task/Closures-Value-capture/Haskell/closures-value-capture-4.hs @@ -0,0 +1,8 @@ +> :t fs +fs :: [b -> Integer] +> map ($ ()) fs +[1,4,9,16,25,36,49,64,81,100] +> fs !! 9 $ () +100 +> fs !! 8 $ undefined +81 diff --git a/Task/Closures-Value-capture/Icon/closures-value-capture.icon b/Task/Closures-Value-capture/Icon/closures-value-capture.icon new file mode 100644 index 0000000000..8cdefdbe8e --- /dev/null +++ b/Task/Closures-Value-capture/Icon/closures-value-capture.icon @@ -0,0 +1,15 @@ +procedure main(args) # Closure/Variable Capture + every put(L := [], vcapture(1 to 10)) # build list of index closures + write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure +end + +# The anonymous 'function', as a co-expression. Most of the code is standard +# boilerplate needed to use a co-expression as an anonymous function. + +procedure vcapture(x) # vcapture closes over its argument + return makeProc { repeat { (x[1]^2) @ &source } } +end + +procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package + return (@A[1], A[1]) +end diff --git a/Task/Closures-Value-capture/J/closures-value-capture-1.j b/Task/Closures-Value-capture/J/closures-value-capture-1.j new file mode 100644 index 0000000000..b3d85d6b2e --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-1.j @@ -0,0 +1,3 @@ +constF=:3 :0 + {.''`(y "_) +) diff --git a/Task/Closures-Value-capture/J/closures-value-capture-2.j b/Task/Closures-Value-capture/J/closures-value-capture-2.j new file mode 100644 index 0000000000..69aefa05f0 --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-2.j @@ -0,0 +1,2 @@ +flist=: constF"0 i.10 +slist=: constF"0 *:i.10 diff --git a/Task/Closures-Value-capture/J/closures-value-capture-3.j b/Task/Closures-Value-capture/J/closures-value-capture-3.j new file mode 100644 index 0000000000..dcb3e949e4 --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-3.j @@ -0,0 +1,4 @@ + flist @.3 +3"_ + slist @.3 +9"_ diff --git a/Task/Closures-Value-capture/J/closures-value-capture-4.j b/Task/Closures-Value-capture/J/closures-value-capture-4.j new file mode 100644 index 0000000000..4e6e5b4873 --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-4.j @@ -0,0 +1,4 @@ + flist @.4'' +4 + slist @.4'' +16 diff --git a/Task/Closures-Value-capture/J/closures-value-capture-5.j b/Task/Closures-Value-capture/J/closures-value-capture-5.j new file mode 100644 index 0000000000..6aa06b7bad --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-5.j @@ -0,0 +1,4 @@ + flist@.(?9) '' +7 + slist@.(?9) '' +25 diff --git a/Task/Closures-Value-capture/J/closures-value-capture-6.j b/Task/Closures-Value-capture/J/closures-value-capture-6.j new file mode 100644 index 0000000000..2c09797edb --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-6.j @@ -0,0 +1,9 @@ + ( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions) +┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐ +│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│ +└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘ + + {::&VL 5 NB. Evoking the 6th verb (function) +25"_ + {::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('') +25 diff --git a/Task/Closures-Value-capture/Java/closures-value-capture-1.java b/Task/Closures-Value-capture/Java/closures-value-capture-1.java new file mode 100644 index 0000000000..61bf9ab904 --- /dev/null +++ b/Task/Closures-Value-capture/Java/closures-value-capture-1.java @@ -0,0 +1,15 @@ +import java.util.function.Supplier; +import java.util.ArrayList; + +public class ValueCapture { + public static void main(String[] args) { + ArrayList> funcs = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + int j = i; + funcs.add(() -> j * j); + } + + Supplier foo = funcs.get(3); + System.out.println(foo.get()); // prints "9" + } +} diff --git a/Task/Closures-Value-capture/Java/closures-value-capture-2.java b/Task/Closures-Value-capture/Java/closures-value-capture-2.java new file mode 100644 index 0000000000..7e41ce7d73 --- /dev/null +++ b/Task/Closures-Value-capture/Java/closures-value-capture-2.java @@ -0,0 +1,17 @@ +import java.util.List; +import java.util.function.IntSupplier; +import java.util.stream.IntStream; + +import static java.util.stream.Collectors.toList; + +public interface ValueCapture { + public static void main(String... arguments) { + List closures = IntStream.rangeClosed(0, 10) + .mapToObj(i -> () -> i * i) + .collect(toList()) + ; + + IntSupplier closure = closures.get(3); + System.out.println(closure.getAsInt()); // prints "9" + } +} diff --git a/Task/Closures-Value-capture/JavaScript/closures-value-capture-1.js b/Task/Closures-Value-capture/JavaScript/closures-value-capture-1.js new file mode 100644 index 0000000000..c92abdc70c --- /dev/null +++ b/Task/Closures-Value-capture/JavaScript/closures-value-capture-1.js @@ -0,0 +1,7 @@ +var funcs = []; +for (var i = 0; i < 10; i++) { + funcs.push( (function(i) { + return function() { return i * i; } + })(i) ); +} +window.alert(funcs[3]()); // alerts "9" diff --git a/Task/Closures-Value-capture/JavaScript/closures-value-capture-2.js b/Task/Closures-Value-capture/JavaScript/closures-value-capture-2.js new file mode 100644 index 0000000000..0fa99ebc0e --- /dev/null +++ b/Task/Closures-Value-capture/JavaScript/closures-value-capture-2.js @@ -0,0 +1,9 @@ + diff --git a/Task/Closures-Value-capture/Julia/closures-value-capture.julia b/Task/Closures-Value-capture/Julia/closures-value-capture.julia new file mode 100644 index 0000000000..c7c50d4b01 --- /dev/null +++ b/Task/Closures-Value-capture/Julia/closures-value-capture.julia @@ -0,0 +1 @@ +funcs = [ () -> i^2 for i = 1:10 ] diff --git a/Task/Closures-Value-capture/Logtalk/closures-value-capture-1.logtalk b/Task/Closures-Value-capture/Logtalk/closures-value-capture-1.logtalk new file mode 100644 index 0000000000..6caea29b06 --- /dev/null +++ b/Task/Closures-Value-capture/Logtalk/closures-value-capture-1.logtalk @@ -0,0 +1,15 @@ +:- object(value_capture). + + :- public(show/0). + show :- + integer::sequence(1, 10, List), + meta::map(create_closure, List, Closures), + meta::map(call_closure, List, Closures). + + create_closure(Index, [Double]>>(Double is Index*Index)). + + call_closure(Index, Closure) :- + call(Closure, Result), + write('Closure '), write(Index), write(' : '), write(Result), nl. + +:- end_object. diff --git a/Task/Closures-Value-capture/Logtalk/closures-value-capture-2.logtalk b/Task/Closures-Value-capture/Logtalk/closures-value-capture-2.logtalk new file mode 100644 index 0000000000..38cdb0ff2d --- /dev/null +++ b/Task/Closures-Value-capture/Logtalk/closures-value-capture-2.logtalk @@ -0,0 +1,12 @@ +| ?- value_capture::show. +Closure 1 : 1 +Closure 2 : 4 +Closure 3 : 9 +Closure 4 : 16 +Closure 5 : 25 +Closure 6 : 36 +Closure 7 : 49 +Closure 8 : 64 +Closure 9 : 81 +Closure 10 : 100 +yes diff --git a/Task/Closures-Value-capture/Lua/closures-value-capture.lua b/Task/Closures-Value-capture/Lua/closures-value-capture.lua new file mode 100644 index 0000000000..9432f8df50 --- /dev/null +++ b/Task/Closures-Value-capture/Lua/closures-value-capture.lua @@ -0,0 +1,6 @@ +funcs={} +for i=1,10 do + table.insert(funcs, function() return i*i end) +end +funcs[2]() +funcs[3]() diff --git a/Task/Closures-Value-capture/Maple/closures-value-capture.maple b/Task/Closures-Value-capture/Maple/closures-value-capture.maple new file mode 100644 index 0000000000..7c794edae7 --- /dev/null +++ b/Task/Closures-Value-capture/Maple/closures-value-capture.maple @@ -0,0 +1,5 @@ +> L := map( i -> (() -> i^2), [seq](1..10) ): +> seq( L[i](),i=1..10); + 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 +> L[4](); + 16 diff --git a/Task/Closures-Value-capture/Mathematica/closures-value-capture.math b/Task/Closures-Value-capture/Mathematica/closures-value-capture.math new file mode 100644 index 0000000000..dba47eb377 --- /dev/null +++ b/Task/Closures-Value-capture/Mathematica/closures-value-capture.math @@ -0,0 +1,5 @@ +Function[i, i^2 &] /@ Range@10 +->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &} + +%[[2]][] +->4 diff --git a/Task/Closures-Value-capture/Nemerle/closures-value-capture.nemerle b/Task/Closures-Value-capture/Nemerle/closures-value-capture.nemerle new file mode 100644 index 0000000000..ae78aa99ef --- /dev/null +++ b/Task/Closures-Value-capture/Nemerle/closures-value-capture.nemerle @@ -0,0 +1,13 @@ +using System.Console; + +module Closures +{ + Main() : void + { + def f(x) { fun() { x ** 2 } } + def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing + + WriteLine($"$(funcs[4]())"); + WriteLine($"$(funcs[2]())"); + } +} diff --git a/Task/Closures-Value-capture/OCaml/closures-value-capture.ocaml b/Task/Closures-Value-capture/OCaml/closures-value-capture.ocaml new file mode 100644 index 0000000000..4d0a462098 --- /dev/null +++ b/Task/Closures-Value-capture/OCaml/closures-value-capture.ocaml @@ -0,0 +1,7 @@ +let () = + let cls = Array.init 10 (fun i -> (function () -> i * i)) in + Random.self_init (); + for i = 1 to 6 do + let x = Random.int 9 in + Printf.printf " fun.(%d) = %d\n" x (cls.(x) ()); + done diff --git a/Task/Closures-Value-capture/Objective-C/closures-value-capture.m b/Task/Closures-Value-capture/Objective-C/closures-value-capture.m new file mode 100644 index 0000000000..b447c4b171 --- /dev/null +++ b/Task/Closures-Value-capture/Objective-C/closures-value-capture.m @@ -0,0 +1,7 @@ +NSMutableArray *funcs = [[NSMutableArray alloc] init]; +for (int i = 0; i < 10; i++) { + [funcs addObject:[^ { return i * i; } copy]]; +} + +int (^foo)(void) = funcs[3]; +NSLog(@"%d", foo()); // logs "9" diff --git a/Task/Closures-Value-capture/PARI-GP/closures-value-capture.pari b/Task/Closures-Value-capture/PARI-GP/closures-value-capture.pari new file mode 100644 index 0000000000..c4a85e1f06 --- /dev/null +++ b/Task/Closures-Value-capture/PARI-GP/closures-value-capture.pari @@ -0,0 +1 @@ +vector(10,i,()->i^2)[5]() diff --git a/Task/Closures-Value-capture/PHP/closures-value-capture-1.php b/Task/Closures-Value-capture/PHP/closures-value-capture-1.php new file mode 100644 index 0000000000..1da9f27bb6 --- /dev/null +++ b/Task/Closures-Value-capture/PHP/closures-value-capture-1.php @@ -0,0 +1,7 @@ + diff --git a/Task/Closures-Value-capture/PHP/closures-value-capture-2.php b/Task/Closures-Value-capture/PHP/closures-value-capture-2.php new file mode 100644 index 0000000000..47b78121a0 --- /dev/null +++ b/Task/Closures-Value-capture/PHP/closures-value-capture-2.php @@ -0,0 +1,7 @@ + diff --git a/Task/Closures-Value-capture/Perl-6/closures-value-capture-1.pl6 b/Task/Closures-Value-capture/Perl-6/closures-value-capture-1.pl6 new file mode 100644 index 0000000000..a247303b98 --- /dev/null +++ b/Task/Closures-Value-capture/Perl-6/closures-value-capture-1.pl6 @@ -0,0 +1,5 @@ +my @c = gather for ^10 -> $i { + take { $i * $i } +} + +.().say for @c.pick(*); # call them in random order diff --git a/Task/Closures-Value-capture/Perl-6/closures-value-capture-2.pl6 b/Task/Closures-Value-capture/Perl-6/closures-value-capture-2.pl6 new file mode 100644 index 0000000000..33975b5c3a --- /dev/null +++ b/Task/Closures-Value-capture/Perl-6/closures-value-capture-2.pl6 @@ -0,0 +1 @@ +say .() for pick *, map -> $i { -> {$i * $i} }, ^10 diff --git a/Task/Closures-Value-capture/Perl/closures-value-capture.pl b/Task/Closures-Value-capture/Perl/closures-value-capture.pl new file mode 100644 index 0000000000..7b06c31476 --- /dev/null +++ b/Task/Closures-Value-capture/Perl/closures-value-capture.pl @@ -0,0 +1,2 @@ +my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs +print $f[$_](), "\n" for (0 .. 8); # call and print all but last diff --git a/Task/Closures-Value-capture/PicoLisp/closures-value-capture.l b/Task/Closures-Value-capture/PicoLisp/closures-value-capture.l new file mode 100644 index 0000000000..a3ae76bd47 --- /dev/null +++ b/Task/Closures-Value-capture/PicoLisp/closures-value-capture.l @@ -0,0 +1,4 @@ +(setq FunList + (make + (for @N 10 + (link (curry (@N) () (* @N @N))) ) ) ) diff --git a/Task/Closures-Value-capture/Pike/closures-value-capture.pike b/Task/Closures-Value-capture/Pike/closures-value-capture.pike new file mode 100644 index 0000000000..a342c567f8 --- /dev/null +++ b/Task/Closures-Value-capture/Pike/closures-value-capture.pike @@ -0,0 +1,13 @@ +array funcs = ({}); +foreach(enumerate(10);; int i) +{ + funcs+= ({ + lambda(int j) + { + return lambda() + { + return j*j; + }; + }(i) + }); +} diff --git a/Task/Closures-Value-capture/Prolog/closures-value-capture.pro b/Task/Closures-Value-capture/Prolog/closures-value-capture.pro new file mode 100644 index 0000000000..80a9261ba5 --- /dev/null +++ b/Task/Closures-Value-capture/Prolog/closures-value-capture.pro @@ -0,0 +1,14 @@ +:-use_module(library(lambda)). + + +closure :- + numlist(1,10, Lnum), + maplist(make_func, Lnum, Lfunc), + maplist(call_func, Lnum, Lfunc). + + +make_func(I, \X^(X is I*I)). + +call_func(N, F) :- + call(F, R), + format('Func ~w : ~w~n', [N, R]). diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-1.py b/Task/Closures-Value-capture/Python/closures-value-capture-1.py new file mode 100644 index 0000000000..f50305fa89 --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-1.py @@ -0,0 +1,4 @@ +funcs = [] +for i in range(10): + funcs.append(lambda: i * i) +print funcs[3]() # prints 81 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-2.py b/Task/Closures-Value-capture/Python/closures-value-capture-2.py new file mode 100644 index 0000000000..2c7db354e2 --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-2.py @@ -0,0 +1,4 @@ +funcs = [] +for i in range(10): + funcs.append(lambda i=i: i * i) +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-3.py b/Task/Closures-Value-capture/Python/closures-value-capture-3.py new file mode 100644 index 0000000000..93865fa232 --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-3.py @@ -0,0 +1,2 @@ +funcs = [lambda i=i: i * i for i in range(10)] +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-4.py b/Task/Closures-Value-capture/Python/closures-value-capture-4.py new file mode 100644 index 0000000000..dbe245ce36 --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-4.py @@ -0,0 +1,4 @@ +funcs = [] +for i in range(10): + funcs.append((lambda i: lambda: i * i)(i)) +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-5.py b/Task/Closures-Value-capture/Python/closures-value-capture-5.py new file mode 100644 index 0000000000..7ad05afe2b --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-5.py @@ -0,0 +1,2 @@ +funcs = [(lambda i: lambda: i)(i * i) for i in range(10)] +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-6.py b/Task/Closures-Value-capture/Python/closures-value-capture-6.py new file mode 100644 index 0000000000..4997b6d163 --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-6.py @@ -0,0 +1,2 @@ +funcs = map(lambda i: lambda: i * i, range(10)) +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/Python/closures-value-capture-7.py b/Task/Closures-Value-capture/Python/closures-value-capture-7.py new file mode 100644 index 0000000000..eae252555e --- /dev/null +++ b/Task/Closures-Value-capture/Python/closures-value-capture-7.py @@ -0,0 +1,2 @@ +funcs=[eval("lambda:%s"%i**2)for i in range(10)] +print funcs[3]() # prints 9 diff --git a/Task/Closures-Value-capture/R/closures-value-capture-1.r b/Task/Closures-Value-capture/R/closures-value-capture-1.r new file mode 100644 index 0000000000..47858eb854 --- /dev/null +++ b/Task/Closures-Value-capture/R/closures-value-capture-1.r @@ -0,0 +1,9 @@ +# assign 's' a list of ten functions +s <- sapply (1:10, # integers 1..10 become argument 'x' below + function (x) { + x # force evaluation of promise x + function (i=x) i*i # this *function* is the return value + }) + +s[[5]]() # call the fifth function in the list of returned functions +[1] 25 # returns vector of length 1 with the value 25 diff --git a/Task/Closures-Value-capture/R/closures-value-capture-2.r b/Task/Closures-Value-capture/R/closures-value-capture-2.r new file mode 100644 index 0000000000..386e7acd3a --- /dev/null +++ b/Task/Closures-Value-capture/R/closures-value-capture-2.r @@ -0,0 +1,2 @@ +s[[5]](10) +[1] 100 diff --git a/Task/Closures-Value-capture/R/closures-value-capture-3.r b/Task/Closures-Value-capture/R/closures-value-capture-3.r new file mode 100644 index 0000000000..82a9f56efd --- /dev/null +++ b/Task/Closures-Value-capture/R/closures-value-capture-3.r @@ -0,0 +1,18 @@ +s <- sapply (1:10, + function (x) { + x # force evaluation of promise x + function () { + R <- x*x + # evaluate the language expression "x <- x + 1" in the persistent parent environment + evalq (x <- x + 1, parent.env(environment())) + R # return squared value + }}) + +s[[5]]() +[1] 25 # 5^2 +s[[5]]() +[1] 36 # now 6^2 +s[[1]]() +[1] 1 # 1^2 +s[[1]]() +[1] 4 # now 2^2 diff --git a/Task/Closures-Value-capture/README b/Task/Closures-Value-capture/README new file mode 100644 index 0000000000..3f5130906b --- /dev/null +++ b/Task/Closures-Value-capture/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Closures/Value_capture diff --git a/Task/Closures-Value-capture/REXX/closures-value-capture.rexx b/Task/Closures-Value-capture/REXX/closures-value-capture.rexx new file mode 100644 index 0000000000..1c3162e3be --- /dev/null +++ b/Task/Closures-Value-capture/REXX/closures-value-capture.rexx @@ -0,0 +1,14 @@ +/*REXX pgm has a list of 10 functions, each returns its invocation(idx)²*/ + + do j=1 for 9 /*invoke random functions 9 times.*/ + interpret 'CALL .'random(0,9) /*invoke a randomly selected func.*/ + end /*j*/ /* [↑] the random func has no args*/ + +say 'The tenth invocation of .0 ───► ' .0() +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────list of 10 functions─────────────────*/ +/*[Below is the closest thing to anonymous functions in the REXX lang.] */ + .0:return .(); .1:return .(); .2:return .(); .3:return .(); .4:return .() + .5:return .(); .6:return .(); .7:return .(); .8:return .(); .9:return .() +/*─────────────────────────────────. function───────────────────────────*/ +.: if symbol('@')=='LIT' then @=0 /*handle 1st invoke*/; @=@+1; return @*@ diff --git a/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt b/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt new file mode 100644 index 0000000000..90874c61ba --- /dev/null +++ b/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt @@ -0,0 +1,3 @@ +#lang racket +(map (λ(f) (f)) + (for/list ([i 10]) (λ () (* i i)))) diff --git a/Task/Closures-Value-capture/Racket/closures-value-capture-2.rkt b/Task/Closures-Value-capture/Racket/closures-value-capture-2.rkt new file mode 100644 index 0000000000..f9f0ced0b8 --- /dev/null +++ b/Task/Closures-Value-capture/Racket/closures-value-capture-2.rkt @@ -0,0 +1 @@ +'(0 1 4 9 16 25 36 49 64 81) diff --git a/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb b/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb new file mode 100644 index 0000000000..5f5c50450b --- /dev/null +++ b/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb @@ -0,0 +1,6 @@ +list = {} +(1..10).each {|i| list[i] = proc {i * i}} +p list[3].call #=> 9 +p list[7][] #=> 49 +i = 5 +p list[3].call #=> 9 diff --git a/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb b/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb new file mode 100644 index 0000000000..15500756e0 --- /dev/null +++ b/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb @@ -0,0 +1,5 @@ +list = {} +for i in 1..10 do list[i] = proc {i * i} end +p list[3][] #=> 100 +i = 5 +p list[3][] #=> 25 diff --git a/Task/Closures-Value-capture/Rust/closures-value-capture.rust b/Task/Closures-Value-capture/Rust/closures-value-capture.rust new file mode 100644 index 0000000000..ef171bd5d6 --- /dev/null +++ b/Task/Closures-Value-capture/Rust/closures-value-capture.rust @@ -0,0 +1,4 @@ +fn main() { + let fs: ~[proc() -> uint] = range(0u,10).map(|i| {proc() i*i}).collect(); + println!("7th val: {}", fs[7]()); +} diff --git a/Task/Closures-Value-capture/Scala/closures-value-capture.scala b/Task/Closures-Value-capture/Scala/closures-value-capture.scala new file mode 100644 index 0000000000..8554bc0a5c --- /dev/null +++ b/Task/Closures-Value-capture/Scala/closures-value-capture.scala @@ -0,0 +1,3 @@ +val closures=for(i <- 0 to 9) yield (()=>i*i) +0 to 8 foreach (i=> println(closures(i)())) +println("---\n"+closures(7)()) diff --git a/Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss b/Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss new file mode 100644 index 0000000000..7b183257b5 --- /dev/null +++ b/Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss @@ -0,0 +1,11 @@ +;;; Collecting lambdas in a tail-recursive function. +(define (build-list-of-functions n i list) + (if (< i n) + (build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list)) + list)) + +(define list-of-functions (build-list-of-functions 11 1 '())) + +(map (lambda (f) (f)) list-of-functions) + +((list-ref list-of-functions 8)) diff --git a/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss b/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss new file mode 100644 index 0000000000..1e275f67a9 --- /dev/null +++ b/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss @@ -0,0 +1,2 @@ +(1 4 9 16 25 36 49 64 81 100) +81 diff --git a/Task/Closures-Value-capture/Smalltalk/closures-value-capture.st b/Task/Closures-Value-capture/Smalltalk/closures-value-capture.st new file mode 100644 index 0000000000..dfd552f729 --- /dev/null +++ b/Task/Closures-Value-capture/Smalltalk/closures-value-capture.st @@ -0,0 +1,2 @@ +funcs := (1 to: 10) collect: [ :i | [ i * i ] ] . +(funcs at: 3) value displayNl . diff --git a/Task/Closures-Value-capture/Tcl/closures-value-capture.tcl b/Task/Closures-Value-capture/Tcl/closures-value-capture.tcl new file mode 100644 index 0000000000..cbc63f31e7 --- /dev/null +++ b/Task/Closures-Value-capture/Tcl/closures-value-capture.tcl @@ -0,0 +1,36 @@ +package require Tcl 8.6; # Just for tailcall command +# Builds a value-capturing closure; does NOT couple variables +proc closure {script} { + set valuemap {} + foreach v [uplevel 1 {info vars}] { + lappend valuemap [list $v [uplevel 1 [list set $v]]] + } + set body [list $valuemap $script [uplevel 1 {namespace current}]] + # Wrap, to stop untoward argument passing + return [list apply [list {} [list tailcall apply $body]]] + # A version of the previous line compatible with Tcl 8.5 would be this + # code, but the closure generated is more fragile: + ### return [list apply $body] +} + +# Simple helper, to avoid capturing unwanted variable +proc collectFor {var from to body} { + upvar 1 $var v + set result {} + for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]} + return $result +} +# Build a list of closures +proc buildList {} { + collectFor i 0 10 { + closure { + # This is the body of the closure + return [expr $i*$i] + } + } +} +set theClosures [buildList] +foreach i {a b c d e} {# Do 5 times; demonstrates no variable leakage + set idx [expr {int(rand()*9)}]; # pick random int from [0..9) + puts $idx=>[{*}[lindex $theClosures $idx]] +} diff --git a/Task/Combinations-and-permutations/00DESCRIPTION b/Task/Combinations-and-permutations/00DESCRIPTION new file mode 100644 index 0000000000..52c100beb5 --- /dev/null +++ b/Task/Combinations-and-permutations/00DESCRIPTION @@ -0,0 +1,15 @@ +{{wikipedia|Combination}} {{wikipedia|Permutation}} + +;Task: +Implement the [[wp:Combination|combination]] (nCk) and [[wp:Permutation|permutation]] (nPk) operators in the target language: +* ^n\operatorname C_k =\binom nk = \frac{n(n-1)\ldots(n-k+1)}{k(k-1)\dots1} +* ^n\operatorname P_k = n\cdot(n-1)\cdot(n-2)\cdots(n-k+1) +See the wikipedia articles for a more detailed description. + +'''To test''', generate and print examples of: +* A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic. +* A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
This 'floating point' code could be implemented using an approximation, e.g., by calling the [[Gamma function]]. + +'''See Also:''' +* [[Evaluate binomial coefficients]] +{{Template:Combinations and permutations}} diff --git a/Task/Combinations-and-permutations/00META.yaml b/Task/Combinations-and-permutations/00META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Combinations-and-permutations/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-1.alg b/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-1.alg new file mode 100644 index 0000000000..40a81d364d --- /dev/null +++ b/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-1.alg @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- # + +COMMENT REQUIRED by "prelude_combinations_and_permutations.a68" CO + MODE CPINT = #LONG# ~; + MODE CPOUT = #LONG# ~; # the answer, can be REAL # + MODE CPREAL = ~; # the answer, can be REAL # + PROC cp fix value error = (#REF# CPARGS args)BOOL: ~; +#PROVIDES:# +# OP C = (CP~,CP~)CP~: ~ # +# OP P = (CP~,CP~)CP~: ~ # +END COMMENT + +MODE CPARGS = STRUCT(CHAR name, #REF# CPINT n,k); + +PRIO C = 8, P = 8; # should be 7.5, a priority between *,/ and **,SHL,SHR etc # + +# I suspect there is a more reliable way of doing this using the Gamma Function approx # + +OP P = (CPINT n, r)CPOUT: ( + IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS("P",n,r)) THEN stop FI FI; + CPOUT out := 1; +# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! # + FOR i FROM n-r+1 TO n DO out *:= i OD; + out +); + +OP P = (CPREAL n, r)CPREAL: # 'ln gamma' requires GSL library # + exp(ln gamma(n+1)-ln gamma(n-r+1)); + +# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! # +COMMENT # alternate slower version # +OP P = (CPREAL n, r)CPREAL: ( # alternate slower version # + IF n < r ORF r < 0 THEN IF NOT cp fix value error(CPARGS("P",ENTIER n,ENTIER r)) THEN stop FI FI; + CPREAL out := 1; +# basically nPk = (n-r+1)(n-r+2)...(n-2)(n-1)n = n!/(n-r)! # + CPREAL i := n-r+1; + WHILE i <= n DO + out*:= i; +# a crude check for underflow # + IF i = i + 1 THEN IF NOT cp fix value error(CPARGS("P",ENTIER n,ENTIER r)) THEN stop FI FI; + i+:=1 + OD; + out +); +END COMMENT + +# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! # +OP C = (CPINT n, r)CPOUT: ( + IF n < r ORF r < 0 THEN IF NOT cp fix value error(("C",n,r)) THEN stop FI FI; + CPINT largest = ( r > n - r | r | n - r ); + CPINT smallest = n - largest; + CPOUT out := 1; + INT smaller fact := 2; + FOR larger fact FROM largest+1 TO n DO +# try and prevent overflow, p.s. there must be a smarter way to do this # +# Problems: loop stalls when 'smaller fact' is a largeish co prime # + out *:= larger fact; + WHILE smaller fact <= smallest ANDF out MOD smaller fact = 0 DO + out OVERAB smaller fact; + smaller fact +:= 1 + OD + OD; + out # EXIT with: n P r OVER r P r # +); + +OP C = (CPREAL n, CPREAL r)CPREAL: # 'ln gamma' requires GSL library # + exp(ln gamma(n+1)-ln gamma(n-r+1)-ln gamma(r+1)); + +# basically C(n,r) = nCk = nPk/r! = n!/(n-r)!/r! # +COMMENT # alternate slower version # +OP C = (CPREAL n, REAL r)CPREAL: ( + IF n < r ORF r < 0 THEN IF NOT cp fix value error(("C",ENTIER n,ENTIER r)) THEN stop FI FI; + CPREAL largest = ( r > n - r | r | n - r ); + CPREAL smallest = n - largest; + CPREAL out := 1; + REAL smaller fact := 2; + REAL larger fact := largest+1; + WHILE larger fact <= n DO # todo: check underflow here # +# try and prevent overflow, p.s. there must be a smarter way to do this # + out *:= larger fact; + WHILE smaller fact <= smallest ANDF out > smaller fact DO + out /:= smaller fact; + smaller fact +:= 1 + OD; + larger fact +:= 1 + OD; + out # EXIT with: n P r OVER r P r # +); +END COMMENT + +SKIP diff --git a/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-2.alg b/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-2.alg new file mode 100644 index 0000000000..1b0a3dd606 --- /dev/null +++ b/Task/Combinations-and-permutations/ALGOL-68/combinations-and-permutations-2.alg @@ -0,0 +1,50 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +CO REQUIRED by "prelude_combinations_and_permutations.a68" CO + MODE CPINT = #LONG# INT; + MODE CPOUT = #LONG# INT; # the answer, can be REAL # + MODE CPREAL = REAL; # the answer, can be REAL # + PROC cp fix value error = (#REF# CPARGS args)BOOL: ( + putf(stand error, ($"Value error: "g(0)gg(0)"arg out of range"l$, + n OF args, name OF args, k OF args)); + FALSE # unfixable # + ); +#PROVIDES:# +# OP C = (CP~,CP~)CP~: ~ # +# OP P = (CP~,CP~)CP~: ~ # +PR READ "prelude_combinations_and_permutations.a68" PR; + +printf($"A sample of Permutations from 1 to 12:"l$); +FOR i FROM 4 BY 1 TO 12 DO + INT first = i - 2, + second = i - ENTIER sqrt(i); + printf(($g(0)" P "g(0)" = "g(0)$, i, first, i P first, $", "$)); + printf(($g(0)" P "g(0)" = "g(0)$, i, second, i P second, $l$)) +OD; + +printf($l"A sample of Combinations from 10 to 60:"l$); +FOR i FROM 10 BY 10 TO 60 DO + INT first = i - 2, + second = i - ENTIER sqrt(i); + printf(($"("g(0)" C "g(0)") = "g(0)$, i, first, i C first, $", "$)); + printf(($"("g(0)" C "g(0)") = "g(0)$, i, second, i C second, $l$)) +OD; + +printf($l"A sample of Permutations from 5 to 15000:"l$); +FOR i FROM 5 BY 10 TO 150 DO + REAL r = i, + first = r - 2, + second = r - ENTIER sqrt(r); + printf(($g(0)" P "g(0)" = "g(-real width,real width-5,-1)$, r, first, r P first, $", "$)); + printf(($g(0)" P "g(0)" = "g(-real width,real width-5,-1)$, r, second, r P second, $l$)) +OD; + +printf($l"A sample of Combinations from 10 to 190:"l$); +FOR i FROM 100 BY 100 TO 1000 DO + REAL r = i, + first = r - 2, + second = r - ENTIER sqrt(r); + printf(($"("g(0)" C "g(0)") = "g(0,1)$, r, first, r C first, $", "$)); + printf(($"("g(0)" C "g(0)") = "g(0,1)$, r, second, r C second, $l$)) +OD diff --git a/Task/Combinations-and-permutations/Bracmat/combinations-and-permutations.bracmat b/Task/Combinations-and-permutations/Bracmat/combinations-and-permutations.bracmat new file mode 100644 index 0000000000..147c7c5917 --- /dev/null +++ b/Task/Combinations-and-permutations/Bracmat/combinations-and-permutations.bracmat @@ -0,0 +1,56 @@ +( ( C + = n k coef + . !arg:(?n,?k) + & (!n+-1*!k:0 + & !coef*!n*!k^-1:?coef + & !k+-1:?k + & !n+-1:?n + ) + & !coef + ) +& ( P + = n k result + . !arg:(?n,?k) + & !n+-1*!k:?k + & 1:?result + & whl + ' ( !n:>!k + & !n*!result:?result + & !n+-1:?n + ) + & !result + ) +& 0:?i +& whl + ' ( 1+!i:~>12:?i + & div$(!i.3):?k + & out$(!i P !k "=" P$(!i,!k)) + ) +& 0:?i +& whl + ' ( 10+!i:~>60:?i + & div$(!i.3):?k + & out$(!i C !k "=" C$(!i,!k)) + ) +& ( displayBig + = + . @(!arg:?show [50 ? [?length) + & !show "... (" !length+-50 " more digits)" + | !arg + ) +& 5 50 500 1000 5000 15000:?is +& whl + ' ( !is:%?i ?is + & div$(!i.3):?k + & out$(str$(!i " P " !k " = " displayBig$(P$(!i,!k)))) + ) +& 0:?i +& whl + ' ( 100+!i:~>1000:?i + & div$(!i.3):?k + & out$(str$(!i " C " !k " = " displayBig$(C$(!i,!k)))) + ) +); diff --git a/Task/Combinations-and-permutations/C/combinations-and-permutations.c b/Task/Combinations-and-permutations/C/combinations-and-permutations.c new file mode 100644 index 0000000000..18a213c179 --- /dev/null +++ b/Task/Combinations-and-permutations/C/combinations-and-permutations.c @@ -0,0 +1,27 @@ +#include + +void perm(mpz_t out, int n, int k) +{ + mpz_set_ui(out, 1); + k = n - k; + while (n > k) mpz_mul_ui(out, out, n--); +} + +void comb(mpz_t out, int n, int k) +{ + perm(out, n, k); + while (k) mpz_divexact_ui(out, out, k--); +} + +int main(void) +{ + mpz_t x; + mpz_init(x); + + perm(x, 1000, 969); + gmp_printf("P(1000,969) = %Zd\n", x); + + comb(x, 1000, 969); + gmp_printf("C(1000,969) = %Zd\n", x); + return 0; +} diff --git a/Task/Combinations-and-permutations/D/combinations-and-permutations.d b/Task/Combinations-and-permutations/D/combinations-and-permutations.d new file mode 100644 index 0000000000..6f33a88c76 --- /dev/null +++ b/Task/Combinations-and-permutations/D/combinations-and-permutations.d @@ -0,0 +1,26 @@ +import std.stdio, std.mathspecial, std.range, std.algorithm, + std.bigint, std.conv; + +enum permutation = (in uint n, in uint k) pure => + reduce!q{a * b}(1.BigInt, iota(n - k + 1, n + 1)); + +enum combination = (in uint n, in uint k) pure => + n.permutation(k) / reduce!q{a * b}(1.BigInt, iota(1, k + 1)); + +enum bigPermutation = (in uint n, in uint k) => + exp(logGamma(n + 1) - logGamma(n - k + 1)); + +enum bigCombination = (in uint n, in uint k) => + exp(logGamma(n + 1) - logGamma(n - k + 1) - logGamma(k + 1)); + +void main() { + 12.permutation(9).writeln; + 12.bigPermutation(9).writeln; + 60.combination(53).writeln; + 145.bigPermutation(133).writeln; + 900.bigCombination(450).writeln; + 1_000.bigCombination(969).writeln; + 15_000.bigPermutation(73).writeln; + 15_000.bigPermutation(1185).writeln; + writefln("%(%s\\\n%)", 15_000.permutation(74).text.chunks(50)); +} diff --git a/Task/Combinations-and-permutations/Icon/combinations-and-permutations.icon b/Task/Combinations-and-permutations/Icon/combinations-and-permutations.icon new file mode 100644 index 0000000000..1412dcc0f3 --- /dev/null +++ b/Task/Combinations-and-permutations/Icon/combinations-and-permutations.icon @@ -0,0 +1,25 @@ +procedure main() + write("P(4,2) = ",P(4,2)) + write("P(8,2) = ",P(8,2)) + write("P(10,8) = ",P(10,8)) + write("C(10,8) = ",C(10,8)) + write("C(20,8) = ",C(20,8)) + write("C(60,58) = ",C(60,58)) + write("P(1000,10) = ",P(1000,10)) + write("P(1000,20) = ",P(1000,20)) + write("P(15000,2) = ",P(15000,2)) + write("C(1000,10) = ",C(1000,10)) + write("C(1000,999) = ",C(1000,999)) + write("C(1000,1000) = ",C(1000,1000)) + write("C(15000,14998) = ",C(15000,14998)) +end + +procedure C(n,k) + every (d:=1) *:= 2 to k + return P(n,k)/d +end + +procedure P(n,k) + every (p:=1) *:= (n-k+1) to n + return p +end diff --git a/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j b/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j new file mode 100644 index 0000000000..c6b4481312 --- /dev/null +++ b/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j @@ -0,0 +1,2 @@ +C=: ! +P=: (<: * (*/@}. 1+i.))"0 diff --git a/Task/Combinations-and-permutations/J/combinations-and-permutations-2.j b/Task/Combinations-and-permutations/J/combinations-and-permutations-2.j new file mode 100644 index 0000000000..3750f80db5 --- /dev/null +++ b/Task/Combinations-and-permutations/J/combinations-and-permutations-2.j @@ -0,0 +1,47 @@ + P table 1+i.12 +┌──┬─────────────────────────────────────────────────────────────┐ +│P │1 2 3 4 5 6 7 8 9 10 11 12│ +├──┼─────────────────────────────────────────────────────────────┤ +│ 1│1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600│ +│ 2│0 1 3 12 60 360 2520 20160 181440 1814400 19958400 239500800│ +│ 3│0 0 1 4 20 120 840 6720 60480 604800 6652800 79833600│ +│ 4│0 0 0 1 5 30 210 1680 15120 151200 1663200 19958400│ +│ 5│0 0 0 0 1 6 42 336 3024 30240 332640 3991680│ +│ 6│0 0 0 0 0 1 7 56 504 5040 55440 665280│ +│ 7│0 0 0 0 0 0 1 8 72 720 7920 95040│ +│ 8│0 0 0 0 0 0 0 1 9 90 990 11880│ +│ 9│0 0 0 0 0 0 0 0 1 10 110 1320│ +│10│0 0 0 0 0 0 0 0 0 1 11 132│ +│11│0 0 0 0 0 0 0 0 0 0 1 12│ +│12│0 0 0 0 0 0 0 0 0 0 0 1│ +└──┴─────────────────────────────────────────────────────────────┘ + + C table 10+10*i.6x +┌──┬─────────────────────────────────────────────────────────────────┐ +│C │10 20 30 40 50 60│ +├──┼─────────────────────────────────────────────────────────────────┤ +│10│ 1 184756 30045015 847660528 10272278170 75394027566│ +│20│ 0 1 30045015 137846528820 47129212243960 4191844505805495│ +│30│ 0 0 1 847660528 47129212243960 118264581564861424│ +│40│ 0 0 0 1 10272278170 4191844505805495│ +│50│ 0 0 0 0 1 75394027566│ +│60│ 0 0 0 0 0 1│ +└──┴─────────────────────────────────────────────────────────────────┘ + + 5 P 100 +7.77718e155 + 100 P 200 +8.45055e216 + 300 P 400 +2.09224e254 + 700 P 800 +3.18349e287 + + 5 C 100 +75287520 + 100 C 200 +9.05485e58 + 300 C 400 +2.24185e96 + 700 C 800 +3.41114e129 diff --git a/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-1.math b/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-1.math new file mode 100644 index 0000000000..de51d2ab7b --- /dev/null +++ b/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-1.math @@ -0,0 +1,8 @@ +ClearAll[Combination,Permutation] +Combination[n_,k_]:=Binomial[n,k] +Permutation[n_,k_]:=Binomial[n,k]k! + +TableForm[Array[Permutation,{12,12}],TableHeadings->{Range[12],Range[12]}] +TableForm[Array[Combination,{6,6},{{10,60},{10,60}}],TableHeadings->{Range[10,60,10],Range[10,60,10]}] +{Row[{#,"P",#-2}," "],N@Permutation[#,#-2]}&/@{5,1000,5000,10000,15000}//Grid +{Row[{#,"C",#/2}," "],N@Combination[#,#/2]}&/@Range[100,1000,100]//Grid diff --git a/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-2.math b/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-2.math new file mode 100644 index 0000000000..73e169b943 --- /dev/null +++ b/Task/Combinations-and-permutations/Mathematica/combinations-and-permutations-2.math @@ -0,0 +1 @@ +Permutation[200000, 100000] diff --git a/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 b/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 new file mode 100644 index 0000000000..6b0e49fe9e --- /dev/null +++ b/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 @@ -0,0 +1,45 @@ +multi P($n, $k) { [*] $n - $k + 1 .. $n } +multi C($n, $k) { P($n, $k) / [*] 1 .. $k } + +sub lstirling(\n) { + n < 10 ?? lstirling(n+1) - log(n+1) !! + .5*log(2*pi*n)+ n*log(n/e+1/(12*e*n)) +} + +role Logarithm { + method gist { + my $e = (self/10.log).Int; + sprintf "%.8fE%+d", exp(self - $e*10.log), $e; + } +} +multi P($n, $k, :$float!) { + (lstirling($n) - lstirling($n -$k)) + but Logarithm +} +multi C($n, $k, :$float!) { + (lstirling($n) - lstirling($n -$k) - lstirling($k)) + but Logarithm +} + +say "Exact results:"; +for 1..12 -> $n { + my $p = $n div 3; + say "P($n, $p) = ", P($n, $p); +} + +for 10, 20 ... 60 -> $n { + my $p = $n div 3; + say "C($n, $p) = ", C($n, $p); +} + +say; +say "Floating point approximations:"; +for 5, 50, 500, 1000, 5000, 15000 -> $n { + my $p = $n div 3; + say "P($n, $p) = ", P($n, $p, :float); +} + +for 100, 200 ... 1000 -> $n { + my $p = $n div 3; + say "C($n, $p) = ", C($n, $p, :float); +} diff --git a/Task/Combinations-and-permutations/Perl/combinations-and-permutations.pl b/Task/Combinations-and-permutations/Perl/combinations-and-permutations.pl new file mode 100644 index 0000000000..c443f92eea --- /dev/null +++ b/Task/Combinations-and-permutations/Perl/combinations-and-permutations.pl @@ -0,0 +1,50 @@ +use strict; +use warnings; + +showoff( "Permutations", \&P, "P", 1 .. 12 ); +showoff( "Combinations", \&C, "C", map $_*10, 1..6 ); +showoff( "Permutations", \&P_big, "P", 5, 50, 500, 1000, 5000, 15000 ); +showoff( "Combinations", \&C_big, "C", map $_*100, 1..10 ); + +sub showoff { + my ($text, $code, $fname, @n) = @_; + print "\nA sample of $text from $n[0] to $n[-1]\n"; + for my $n ( @n ) { + my $k = int( $n / 3 ); + print $n, " $fname $k = ", $code->($n, $k), "\n"; + } +} + +sub P { + my ($n, $k) = @_; + my $x = 1; + $x *= $_ for $n - $k + 1 .. $n ; + $x; +} + +sub P_big { + my ($n, $k) = @_; + my $x = 0; + $x += log($_) for $n - $k + 1 .. $n ; + eshow($x); +} + +sub C { + my ($n, $k) = @_; + my $x = 1; + $x *= ($n - $_ + 1) / $_ for 1 .. $k; + $x; +} + +sub C_big { + my ($n, $k) = @_; + my $x = 0; + $x += log($n - $_ + 1) - log($_) for 1 .. $k; + exp($x); +} + +sub eshow { + my ($x) = @_; + my $e = int( $x / log(10) ); + sprintf "%.8Fe%+d", exp($x - $e * log(10)), $e; +} diff --git a/Task/Combinations-and-permutations/Python/combinations-and-permutations.py b/Task/Combinations-and-permutations/Python/combinations-and-permutations.py new file mode 100644 index 0000000000..487a9dd304 --- /dev/null +++ b/Task/Combinations-and-permutations/Python/combinations-and-permutations.py @@ -0,0 +1,29 @@ +from __future__ import print_function + +from scipy.misc import factorial as fact +from scipy.misc import comb + +def perm(N, k, exact=0): + return comb(N, k, exact) * fact(k, exact) + +exact=True +print('Sample Perms 1..12') +for N in range(1, 13): + k = max(N-2, 1) + print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n') + +print('\n\nSample Combs 10..60') +for N in range(10, 61, 10): + k = N-2 + print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n') + +exact=False +print('\n\nSample Perms 5..1500 Using FP approximations') +for N in [5, 15, 150, 1500, 15000]: + k = N-2 + print('%iP%i =' % (N, k), perm(N, k, exact)) + +print('\nSample Combs 100..1000 Using FP approximations') +for N in range(100, 1001, 100): + k = N-2 + print('%iC%i =' % (N, k), comb(N, k, exact)) diff --git a/Task/Combinations-and-permutations/README b/Task/Combinations-and-permutations/README new file mode 100644 index 0000000000..11db10bcac --- /dev/null +++ b/Task/Combinations-and-permutations/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Combinations_and_permutations diff --git a/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx b/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx new file mode 100644 index 0000000000..4c74d830af --- /dev/null +++ b/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx @@ -0,0 +1,46 @@ +/*REXX program to compute a sampling of combinations and permutations. */ +numeric digits 100 /*use hundred digits of precision*/ + + do j=1 to 12 /*show permutations from 1──► 12 */ + _=; do k=1 to j /*step through all J permutations*/ + _=_ 'P('j","k')='perm(j,k)" " /*add an extra blank between #s. */ + end /*k*/ + say strip(_) /*show a horizontal line of PERMs*/ + end /*j*/ +say + do j=10 to 60 by 10 /*show some combinations 10──► 60*/ + _=; do k=1 to j by j%5 /*step through some combinations.*/ + _=_ 'C('j","k')='comb(j,k)" " /*add an extra blank between #s. */ + end /*k*/ + say strip(_) /*show a horizontal line of COMBs*/ + end /*j*/ +say +numeric digits 20 /*force floating point for big #s*/ + + do j=5 to 15000 by 1000 /*show a few permutations, big #s*/ + _=; do k=1 to j by j%10 for 5 /*go through some J permutations.*/ + _=_ 'P('j","k')='perm(j,k)" " /*add an extra blank between #s. */ + end /*k*/ + say strip(_) /*show a horizontal line of PERMs*/ + end /*j*/ +say + do j=100 to 1000 by 100 /*show a few combinations, big #s*/ + _=; do k=1 to j by j%5 /*step through some combinations.*/ + _=_ 'C('j","k')='comb(j,k)" " /*add an extra blank between #s. */ + end /*k*/ + say strip(_) /*show a horizontal line of COMBs*/ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────COMB subroutine─────────────────────*/ +comb: procedure; parse arg x,y /*args: X things, Y at-a-time.*/ +if y>x then return 0 /*oops-say, to big a chunk. */ +if x=y then return 1 /* X things same as chunk size. */ +if x-y 263409560461970212832400 +(P 1000 10) ; -> 955860613004397508326213120000 diff --git a/Task/Combinations-and-permutations/Ruby/combinations-and-permutations.rb b/Task/Combinations-and-permutations/Ruby/combinations-and-permutations.rb new file mode 100644 index 0000000000..74d0ce0512 --- /dev/null +++ b/Task/Combinations-and-permutations/Ruby/combinations-and-permutations.rb @@ -0,0 +1,38 @@ +include Math + +class Integer + + def permutation(k) + (self-k+1 .. self).inject( :*) + end + + def combination(k) + self.permutation(k) / (1 .. k).inject( :*) + end + + def big_permutation(k) + exp( lgamma_plus(self) - lgamma_plus(self -k)) + end + + def big_combination(k) + exp( lgamma_plus(self) - lgamma_plus(self - k) - lgamma_plus(k)) + end + + private + def lgamma_plus(n) + lgamma(n+1)[0] #lgamma is the natural log of gamma + end + +end + +p 12.permutation(9) #=> 79833600 +p 12.big_permutation(9) #=> 79833600.00000021 +p 60.combination(53) #=> 386206920 +p 145.big_permutation(133) #=> 1.6801459655817956e+243 +p 900.big_combination(450) #=> 2.247471882064647e+269 +p 1000.big_combination(969) #=> 7.602322407770517e+58 +p 15000.big_permutation(73) #=> 6.004137561717704e+304 +#That's about the maximum of Float: +p 15000.big_permutation(74) #=> Infinity +# Integer has no maximum: +p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000 diff --git a/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-1.tcl b/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-1.tcl new file mode 100644 index 0000000000..f347bc0928 --- /dev/null +++ b/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-1.tcl @@ -0,0 +1,25 @@ +# Exact integer versions +proc tcl::mathfunc::P {n k} { + set t 1 + for {set i $n} {$i > $n-$k} {incr i -1} { + set t [expr {$t * $i}] + } + return $t +} +proc tcl::mathfunc::C {n k} { + set t [P $n $k] + for {set i $k} {$i > 1} {incr i -1} { + set t [expr {$t / $i}] + } + return $t +} + +# Floating point versions using the Gamma function +package require math +proc tcl::mathfunc::lnGamma n {math::ln_Gamma $n} +proc tcl::mathfunc::fP {n k} { + expr {exp(lnGamma($n+1) - lnGamma($n-$k+1))} +} +proc tcl::mathfunc::fC {n k} { + expr {exp(lnGamma($n+1) - lnGamma($n-$k+1) - lnGamma($k+1))} +} diff --git a/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-2.tcl b/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-2.tcl new file mode 100644 index 0000000000..af86f16dbb --- /dev/null +++ b/Task/Combinations-and-permutations/Tcl/combinations-and-permutations-2.tcl @@ -0,0 +1,26 @@ +# Using the exact integer versions +puts "A sample of Permutations from 1 to 12:" +for {set i 4} {$i <= 12} {incr i} { + set ii [expr {$i - 2}] + set iii [expr {$i - int(sqrt($i))}] + puts "$i P $ii = [expr {P($i,$ii)}], $i P $iii = [expr {P($i,$iii)}]" +} +puts "A sample of Combinations from 10 to 60:" +for {set i 10} {$i <= 60} {incr i 10} { + set ii [expr {$i - 2}] + set iii [expr {$i - int(sqrt($i))}] + puts "$i C $ii = [expr {C($i,$ii)}], $i C $iii = [expr {C($i,$iii)}]" +} +# Using the approximate floating point versions +puts "A sample of Permutations from 5 to 15000:" +for {set i 5} {$i <= 150} {incr i 10} { + set ii [expr {$i - 2}] + set iii [expr {$i - int(sqrt($i))}] + puts "$i P $ii = [expr {fP($i,$ii)}], $i P $iii = [expr {fP($i,$iii)}]" +} +puts "A sample of Combinations from 100 to 1000:" +for {set i 100} {$i <= 1000} {incr i 100} { + set ii [expr {$i - 2}] + set iii [expr {$i - int(sqrt($i))}] + puts "$i C $ii = [expr {fC($i,$ii)}], $i C $iii = [expr {fC($i,$iii)}]" +} diff --git a/Task/Comma-quibbling/00DESCRIPTION b/Task/Comma-quibbling/00DESCRIPTION new file mode 100644 index 0000000000..8745fef3c3 --- /dev/null +++ b/Task/Comma-quibbling/00DESCRIPTION @@ -0,0 +1,15 @@ +Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog]. + +'''The task''' is to write a function to generate a string output which is the concatenation of input words from a list/sequence where: +# An input of no words produces the output string of just the two brace characters "{}". +# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". +# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". +# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". + +Test your function with the following series of inputs showing your output here on this page: +* [] # (No input words). +* ["ABC"] +* ["ABC", "DEF"] +* ["ABC", "DEF", "G", "H"] + +Note: Assume words are non-empty strings of uppercase characters for this task. diff --git a/Task/Comma-quibbling/AWK/comma-quibbling.awk b/Task/Comma-quibbling/AWK/comma-quibbling.awk new file mode 100644 index 0000000000..70980d8cfe --- /dev/null +++ b/Task/Comma-quibbling/AWK/comma-quibbling.awk @@ -0,0 +1,13 @@ +function quibble(a, n, i, s) { + for (i = 1; i < n - 1; i++) s = s a[i] ", " + i = n - 1; if (i > 0) s = s a[i] " and " + if (n > 0) s = s a[n] + return "{" s "}" +} + +BEGIN { + print quibble(a, 0) + n = split("ABC", b); print quibble(b, n) + n = split("ABC DEF", c); print quibble(c, n) + n = split("ABC DEF G H", d); print quibble(d, n) +} diff --git a/Task/Comma-quibbling/Ada/comma-quibbling.ada b/Task/Comma-quibbling/Ada/comma-quibbling.ada new file mode 100644 index 0000000000..576096d47e --- /dev/null +++ b/Task/Comma-quibbling/Ada/comma-quibbling.ada @@ -0,0 +1,17 @@ +with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line; + +procedure Comma_Quibble is + +begin + case Argument_Count is + when 0 => Ada.Text_IO.Put_Line("{}"); + when 1 => Ada.Text_IO.Put_Line("{" & Argument(1) & "}"); + when others => + Ada.Text_IO.Put("{"); + for I in 1 .. Argument_Count-2 loop + Ada.Text_IO.Put(Argument(I) & ", "); + end loop; + Ada.Text_IO.Put(Argument(Argument_Count-1) & " and " & + Argument(Argument_Count) & "}"); + end case; +end Comma_Quibble; diff --git a/Task/Comma-quibbling/AutoHotkey/comma-quibbling.ahk b/Task/Comma-quibbling/AutoHotkey/comma-quibbling.ahk new file mode 100644 index 0000000000..89d292dead --- /dev/null +++ b/Task/Comma-quibbling/AutoHotkey/comma-quibbling.ahk @@ -0,0 +1,18 @@ +MsgBox % quibble([]) +MsgBox % quibble(["ABC"]) +MsgBox % quibble(["ABC", "DEF"]) +MsgBox % quibble(["ABC", "DEF", "G", "H"]) + +quibble(d) { + s:="" + for i, e in d + { + if (i + +template +void quibble(std::ostream& o, T i, T e) { + o << "{"; + if (e != i) { + T n = i++; + const char* more = ""; + while (e != i) { + o << more << *n; + more = ", "; + n = i++; + } + o << (*more?" and ":"") << *n; + } + o << "}"; +} + +int main(int argc, char** argv) { + char const* a[] = {"ABC","DEF","G","H"}; + for (int i=0; i<5; i++) { + quibble(std::cout, a, a+i); + std::cout << std::endl; + } + return 0; +} diff --git a/Task/Comma-quibbling/C/comma-quibbling.c b/Task/Comma-quibbling/C/comma-quibbling.c new file mode 100644 index 0000000000..79310fb8c9 --- /dev/null +++ b/Task/Comma-quibbling/C/comma-quibbling.c @@ -0,0 +1,53 @@ +#include +#include +#include + +char *quib(const char **strs, size_t size) +{ + + size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0); + size_t i; + + for (i = 0; i < size; i++) + len += strlen(strs[i]); + + char *s = malloc(len * sizeof(*s)); + if (!s) + { + perror("Can't allocate memory!\n"); + exit(EXIT_FAILURE); + } + + strcpy(s, "{"); + switch (size) { + case 0: break; + case 1: strcat(s, strs[0]); + break; + default: for (i = 0; i < size - 1; i++) + { + strcat(s, strs[i]); + if (i < size - 2) + strcat(s, ", "); + else + strcat(s, " and "); + } + strcat(s, strs[i]); + break; + } + strcat(s, "}"); + return s; +} + +int main(void) +{ + const char *test[] = {"ABC", "DEF", "G", "H"}; + char *s; + + for (size_t i = 0; i < 5; i++) + { + s = quib(test, i); + printf("%s\n", s); + free(s); + } + return EXIT_SUCCESS; +} diff --git a/Task/Comma-quibbling/COBOL/comma-quibbling.cobol b/Task/Comma-quibbling/COBOL/comma-quibbling.cobol new file mode 100644 index 0000000000..bd757e95d4 --- /dev/null +++ b/Task/Comma-quibbling/COBOL/comma-quibbling.cobol @@ -0,0 +1,75 @@ + >>SOURCE FORMAT IS FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. comma-quibbling-test. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION comma-quibbling + . +DATA DIVISION. +WORKING-STORAGE SECTION. +01 strs-area. + 03 strs-len PIC 9. + 03 strs PIC X(5) + OCCURS 0 TO 9 TIMES + DEPENDING ON strs-len. + +PROCEDURE DIVISION. + MOVE "ABC" TO strs (1) + MOVE "DEF" TO strs (2) + MOVE "G" TO strs (3) + MOVE "H" TO strs (4) + + PERFORM VARYING strs-len FROM 0 BY 1 UNTIL strs-len > 4 + DISPLAY FUNCTION comma-quibbling(strs-area) + END-PERFORM + . +END PROGRAM comma-quibbling-test. + + +IDENTIFICATION DIVISION. +FUNCTION-ID. comma-quibbling. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 i PIC 9. + +01 num-extra-words PIC 9. + +LINKAGE SECTION. +01 strs-area. + 03 strs-len PIC 9. + 03 strs PIC X(5) + OCCURS 0 TO 9 TIMES + DEPENDING ON strs-len. + +01 str PIC X(50). + +PROCEDURE DIVISION USING strs-area RETURNING str. + EVALUATE strs-len + WHEN ZERO + MOVE "{}" TO str + GOBACK + + WHEN 1 + MOVE FUNCTION CONCATENATE("{", FUNCTION TRIM(strs (1)), "}") + TO str + GOBACK + END-EVALUATE + + MOVE FUNCTION CONCATENATE(FUNCTION TRIM(strs (strs-len - 1)), + " and ", FUNCTION TRIM(strs (strs-len)), "}") + TO str + + IF strs-len > 2 + SUBTRACT 2 FROM strs-len GIVING num-extra-words + PERFORM VARYING i FROM num-extra-words BY -1 UNTIL i = 0 + MOVE FUNCTION CONCATENATE(FUNCTION TRIM(strs (i)), ", ", str) + TO str + END-PERFORM + END-IF + + MOVE FUNCTION CONCATENATE("{", str) TO str + . +END FUNCTION comma-quibbling. diff --git a/Task/Comma-quibbling/Clojure/comma-quibbling.clj b/Task/Comma-quibbling/Clojure/comma-quibbling.clj new file mode 100644 index 0000000000..d39a9f8378 --- /dev/null +++ b/Task/Comma-quibbling/Clojure/comma-quibbling.clj @@ -0,0 +1,18 @@ +(defn quibble [sq] + (let [sep (if (pos? (count sq)) " and " "")] + (apply str + (concat "{" (interpose ", " (butlast sq)) [sep (last sq)] "}")))) + +; Or, using clojure.pprint's cl-format, which implements common lisp's format: +(defn quibble-f [& args] + (clojure.pprint/cl-format nil "{~{~a~#[~; and ~:;, ~]~}}" args)) + +(def test + #(doseq [sq [[] + ["ABC"] + ["ABC", "DEF"] + ["ABC", "DEF", "G", "H"]]] + ((comp println %) sq))) + +(test quibble) +(test quibble-f) diff --git a/Task/Comma-quibbling/CoffeeScript/comma-quibbling.coffee b/Task/Comma-quibbling/CoffeeScript/comma-quibbling.coffee new file mode 100644 index 0000000000..1692e47c9d --- /dev/null +++ b/Task/Comma-quibbling/CoffeeScript/comma-quibbling.coffee @@ -0,0 +1,9 @@ +quibble = ([most..., last]) -> + '{' + + (most.join ', ') + + (if most.length then ' and ' else '') + + (last or '') + + '}' + +console.log quibble(s) for s in [ [], ["ABC"], ["ABC", "DEF"], + ["ABC", "DEF", "G", "H" ] ] diff --git a/Task/Comma-quibbling/Common-Lisp/comma-quibbling.lisp b/Task/Comma-quibbling/Common-Lisp/comma-quibbling.lisp new file mode 100644 index 0000000000..3d1bb71d59 --- /dev/null +++ b/Task/Comma-quibbling/Common-Lisp/comma-quibbling.lisp @@ -0,0 +1,7 @@ +(defun quibble (&rest args) + (format t "{~{~a~#[~; and ~:;, ~]~}}" args)) + +(quibble) +(quibble "ABC") +(quibble "ABC" "DEF") +(quibble "ABC" "DEF" "G" "H") diff --git a/Task/Comma-quibbling/D/comma-quibbling-1.d b/Task/Comma-quibbling/D/comma-quibbling-1.d new file mode 100644 index 0000000000..7aba574a24 --- /dev/null +++ b/Task/Comma-quibbling/D/comma-quibbling-1.d @@ -0,0 +1,17 @@ +import std.stdio, std.string; + +string quibbler(in string[] seq) pure /*nothrow*/ { + if (seq.length <= 1) + return format("{%-(%s, %)}", seq); + else + return format("{%-(%s, %) and %s}", seq[0 .. $-1], seq[$-1]); +} + +void main() { + //foreach (immutable test; [[], + foreach (const test; [[], + ["ABC"], + ["ABC", "DEF"], + ["ABC", "DEF", "G", "H"]]) + test.quibbler.writeln; +} diff --git a/Task/Comma-quibbling/D/comma-quibbling-2.d b/Task/Comma-quibbling/D/comma-quibbling-2.d new file mode 100644 index 0000000000..465d9ba2f2 --- /dev/null +++ b/Task/Comma-quibbling/D/comma-quibbling-2.d @@ -0,0 +1,10 @@ +import std.stdio, std.string, std.algorithm, std.conv, std.array; + +enum quibbler = (in string[] a) pure => + "{%-(%s and %)}".format(a.length < 2 ? a : + [a[0 .. $-1].join(", "), a.back]); + +void main() { + [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] + .map!quibbler.writeln; +} diff --git a/Task/Comma-quibbling/Deja-Vu/comma-quibbling.djv b/Task/Comma-quibbling/Deja-Vu/comma-quibbling.djv new file mode 100644 index 0000000000..fa4e3e36b3 --- /dev/null +++ b/Task/Comma-quibbling/Deja-Vu/comma-quibbling.djv @@ -0,0 +1,15 @@ +comma-quibble lst: + "}" ) + if lst: + pop-from lst + if lst: + " and " + pop-from lst + for item in lst: + item ", " + concat( "{" + +!. comma-quibble [] +!. comma-quibble [ "ABC" ] +!. comma-quibble [ "ABC" "DEF" ] +!. comma-quibble [ "ABC" "DEF" "G" "H" ] diff --git a/Task/Comma-quibbling/Erlang/comma-quibbling.erl b/Task/Comma-quibbling/Erlang/comma-quibbling.erl new file mode 100644 index 0000000000..16ee770562 --- /dev/null +++ b/Task/Comma-quibbling/Erlang/comma-quibbling.erl @@ -0,0 +1,17 @@ +-module( comma_quibbling ). + +-export( [task/0] ). + +task() -> [generate(X) || X <- [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]]. + + + +generate( List ) -> "{" ++ generate_content(List) ++ "}". + +generate_content( [] ) -> ""; +generate_content( [X] ) -> X; +generate_content( [X1, X2] ) -> string:join( [X1, "and", X2], " " ); +generate_content( Xs ) -> + [Last, Second_to_last | T] = lists:reverse( Xs ), + With_commas = [X ++ "," || X <- T], + string:join(lists:reverse([Last, "and", Second_to_last | With_commas]), " "). diff --git a/Task/Comma-quibbling/Go/comma-quibbling.go b/Task/Comma-quibbling/Go/comma-quibbling.go new file mode 100644 index 0000000000..6eec2648ba --- /dev/null +++ b/Task/Comma-quibbling/Go/comma-quibbling.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "strings" +) + +func q(s []string) string { + switch len(s) { + case 0: + return "{}" + case 1: + return "{" + s[0] + "}" + case 2: + return "{" + s[0] + " and " + s[1] + "}" + default: + return "{" + + strings.Join(s[:len(s)-1], ", ") + + " and " + + s[len(s)-1] + + "}" + } +} + +func main() { + fmt.Println(q([]string{})) + fmt.Println(q([]string{"ABC"})) + fmt.Println(q([]string{"ABC", "DEF"})) + fmt.Println(q([]string{"ABC", "DEF", "G", "H"})) +} diff --git a/Task/Comma-quibbling/Groovy/comma-quibbling-1.groovy b/Task/Comma-quibbling/Groovy/comma-quibbling-1.groovy new file mode 100644 index 0000000000..e734723cb2 --- /dev/null +++ b/Task/Comma-quibbling/Groovy/comma-quibbling-1.groovy @@ -0,0 +1 @@ +def commaQuibbling = { it.size() < 2 ? "{${it.join(', ')}}" : "{${it[0..-2].join(', ')} and ${it[-1]}}" } diff --git a/Task/Comma-quibbling/Groovy/comma-quibbling-2.groovy b/Task/Comma-quibbling/Groovy/comma-quibbling-2.groovy new file mode 100644 index 0000000000..027c0720bf --- /dev/null +++ b/Task/Comma-quibbling/Groovy/comma-quibbling-2.groovy @@ -0,0 +1,4 @@ +['{}': [], '{ABC}': ['ABC'], '{ABC and DEF}': ['ABC', 'DEF'], '{ABC, DEF, G and H}': ['ABC', 'DEF', 'G', 'H']].each { expected, input -> + println "Verifying commaQuibbling($input) == $expected" + assert commaQuibbling(input) == expected +} diff --git a/Task/Comma-quibbling/Haskell/comma-quibbling.hs b/Task/Comma-quibbling/Haskell/comma-quibbling.hs new file mode 100644 index 0000000000..92b26081f3 --- /dev/null +++ b/Task/Comma-quibbling/Haskell/comma-quibbling.hs @@ -0,0 +1,9 @@ +quibble ws = "{" ++ quibbles ws ++ "}" + where quibbles [] = "" + quibbles [a] = a + quibbles [a,b] = a ++ " and " ++ b + quibbles (a:bs) = a ++ ", " ++ quibbles bs + +main = mapM_ (putStrLn . quibble) $ + [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] ++ + (map words ["One two three four", "Me myself I", "Jack Jill", "Loner" ]) diff --git a/Task/Comma-quibbling/Icon/comma-quibbling.icon b/Task/Comma-quibbling/Icon/comma-quibbling.icon new file mode 100644 index 0000000000..f45088838a --- /dev/null +++ b/Task/Comma-quibbling/Icon/comma-quibbling.icon @@ -0,0 +1,9 @@ +procedure main() + every write(quibble([] | ["ABC"] | ["ABC","DEF"] | ["ABC","DEF","G","H"])) +end + +procedure quibble(A) + join := s := "" + while s := pull(A)||join||s do join := if *join = 0 then " and " else ", " + return "{"||s||"}" +end diff --git a/Task/Comma-quibbling/J/comma-quibbling-1.j b/Task/Comma-quibbling/J/comma-quibbling-1.j new file mode 100644 index 0000000000..e2df143895 --- /dev/null +++ b/Task/Comma-quibbling/J/comma-quibbling-1.j @@ -0,0 +1,3 @@ +quibLast2=: ' and ' joinstring (2 -@<. #) {. ] +withoutLast2=: ([: # _2&}.) {. ] +quibble=: '{', '}' ,~ ', ' joinstring withoutLast2 , <@quibLast2 diff --git a/Task/Comma-quibbling/J/comma-quibbling-2.j b/Task/Comma-quibbling/J/comma-quibbling-2.j new file mode 100644 index 0000000000..614d0cb75e --- /dev/null +++ b/Task/Comma-quibbling/J/comma-quibbling-2.j @@ -0,0 +1,6 @@ + Tests=: (<'');(<'ABC');('ABC';'DEF');<('ABC';'DEF';'G';'H') + quibble every Tests +{} +{ABC} +{ABC and DEF} +{ABC, DEF, G and H} diff --git a/Task/Comma-quibbling/J/comma-quibbling-3.j b/Task/Comma-quibbling/J/comma-quibbling-3.j new file mode 100644 index 0000000000..f1f17a2adb --- /dev/null +++ b/Task/Comma-quibbling/J/comma-quibbling-3.j @@ -0,0 +1,2 @@ +commaand=: 1 ;@}.&, ] ,.~ 1 |.!.(<' and ') (<', ')"0 +quibble=: '{','}',~ commaand diff --git a/Task/Comma-quibbling/Java/comma-quibbling.java b/Task/Comma-quibbling/Java/comma-quibbling.java new file mode 100644 index 0000000000..04ffcd972f --- /dev/null +++ b/Task/Comma-quibbling/Java/comma-quibbling.java @@ -0,0 +1,21 @@ +public class Quibbler { + + public static String quibble(String[] words) { + String qText = "{"; + for(int wIndex = 0; wIndex < words.length; wIndex++) { + qText += words[wIndex] + (wIndex == words.length-1 ? "" : + wIndex == words.length-2 ? " and " : + ", "; + } + qText += "}"; + return qText; + } + + public static void main(String[] args) { + System.out.println(quibble(new String[]{})); + System.out.println(quibble(new String[]{"ABC"})); + System.out.println(quibble(new String[]{"ABC", "DEF"})); + System.out.println(quibble(new String[]{"ABC", "DEF", "G"})); + System.out.println(quibble(new String[]{"ABC", "DEF", "G", "H"})); + } +} diff --git a/Task/Comma-quibbling/JavaScript/comma-quibbling.js b/Task/Comma-quibbling/JavaScript/comma-quibbling.js new file mode 100644 index 0000000000..b24c9674d9 --- /dev/null +++ b/Task/Comma-quibbling/JavaScript/comma-quibbling.js @@ -0,0 +1,13 @@ +function quibble(words) { + return "{" + + words.slice(0, words.length-1).join(",") + + (words.length > 1 ? " and " : "") + + (words[words.length-1] || '') + + "}"; +} + +[[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]].forEach( + function(s) { + console.log(quibble(s)); + } +); diff --git a/Task/Comma-quibbling/Julia/comma-quibbling.julia b/Task/Comma-quibbling/Julia/comma-quibbling.julia new file mode 100644 index 0000000000..3e6b4561c7 --- /dev/null +++ b/Task/Comma-quibbling/Julia/comma-quibbling.julia @@ -0,0 +1,4 @@ +quibble(words) = + "{"* (isempty(words) ? "" : + length(words)==1? words[1] : + join(words[1:end-1],", ")*" and "*words[end]) *"}" diff --git a/Task/Comma-quibbling/Logo/comma-quibbling.logo b/Task/Comma-quibbling/Logo/comma-quibbling.logo new file mode 100644 index 0000000000..58b33d2eff --- /dev/null +++ b/Task/Comma-quibbling/Logo/comma-quibbling.logo @@ -0,0 +1,26 @@ +to join :delimiter :list [:result []] + output cond [ + [ [empty? :list] :result ] + [ [empty? :result] (join :delimiter butfirst :list first :list) ] + [ else (join :delimiter butfirst :list + (word :result :delimiter first :list)) ] + ] +end + +to quibble :list + local "length + make "length count :list + make "text ( + ifelse [:length <= 2] [ + (join "\ and\ :list) + ] [ + (join "\ and\ (sentence join ",\ butlast :list last :list)) + ]) + output ifelse [empty? :text] "\{\} [(word "\{ :text "\})] +end + +foreach [ [] [ABC] [ABC DEF] [ABC DEF G H] ] [ + print quibble ? +] + +bye diff --git a/Task/Comma-quibbling/MAXScript/comma-quibbling-1.max b/Task/Comma-quibbling/MAXScript/comma-quibbling-1.max new file mode 100644 index 0000000000..62bbf2db30 --- /dev/null +++ b/Task/Comma-quibbling/MAXScript/comma-quibbling-1.max @@ -0,0 +1,23 @@ +fn separate words: = +( + if words == unsupplied or words == undefined or classof words != array then return "{}" + else + ( + local toReturn = "{" + local pos = 1 + while pos <= words.count do + ( + if pos == 1 then (append toReturn words[pos]; pos+=1) + else + ( + if pos <= words.count-1 then (append toReturn (", "+words[pos]); pos+=1) + else + ( + append toReturn (" and " + words[pos]) + pos +=1 + ) + ) + ) + return (toReturn+"}") + ) +) diff --git a/Task/Comma-quibbling/MAXScript/comma-quibbling-2.max b/Task/Comma-quibbling/MAXScript/comma-quibbling-2.max new file mode 100644 index 0000000000..ca409bb2d2 --- /dev/null +++ b/Task/Comma-quibbling/MAXScript/comma-quibbling-2.max @@ -0,0 +1,8 @@ +separate words:#() +"{}" +separate words:#("ABC") +"{ABC}" +separate words:#("ABC","DEF") +"{ABC and DEF}" +separate words:#("ABC","DEF","G","H") +"{ABC, DEF, G and H}" diff --git a/Task/Comma-quibbling/Maple/comma-quibbling-1.maple b/Task/Comma-quibbling/Maple/comma-quibbling-1.maple new file mode 100644 index 0000000000..3434c58a32 --- /dev/null +++ b/Task/Comma-quibbling/Maple/comma-quibbling-1.maple @@ -0,0 +1,12 @@ +Quibble := proc( los ) + uses StringTools; + Fence( proc() + if los = [] then + "" + elif numelems( los ) = 1 then + los[ 1 ] + else + cat( Join( los[ 1 .. -2 ], ", " ), " and ", los[ -1 ] ) + end if + end(), "{", "}" ) +end proc: diff --git a/Task/Comma-quibbling/Maple/comma-quibbling-2.maple b/Task/Comma-quibbling/Maple/comma-quibbling-2.maple new file mode 100644 index 0000000000..63843cab5f --- /dev/null +++ b/Task/Comma-quibbling/Maple/comma-quibbling-2.maple @@ -0,0 +1,11 @@ +> Quibble([]); + "{}" + +> Quibble( [ "ABC" ] ); + "{ABC}" + +> Quibble( [ "ABC", "DEF" ] ); + "{ABC and DEF}" + +> Quibble( ["ABC", "DEF", "G", "H"] ); + "{ABC, DEF, G and H}" diff --git a/Task/Comma-quibbling/Mathematica/comma-quibbling.math b/Task/Comma-quibbling/Mathematica/comma-quibbling.math new file mode 100644 index 0000000000..cb9d4c3c52 --- /dev/null +++ b/Task/Comma-quibbling/Mathematica/comma-quibbling.math @@ -0,0 +1,4 @@ +quibble[words___] := + ToString@{StringJoin@@ + Replace[Riffle[{words}, ", "], + {most__, ", ", last_} -> {most, " and ", last}]} diff --git a/Task/Comma-quibbling/NetRexx/comma-quibbling.netrexx b/Task/Comma-quibbling/NetRexx/comma-quibbling.netrexx new file mode 100644 index 0000000000..267e6c7d35 --- /dev/null +++ b/Task/Comma-quibbling/NetRexx/comma-quibbling.netrexx @@ -0,0 +1,25 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method quibble(arg) public static + parse arg '[' lst ']' + lst = lst.changestr('"', '').space(1) + lc = lst.lastpos(',') + if lc > 0 then + lst = lst.insert('and', lc).overlay(' ', lc) + return '{'lst'}' + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + lists = ['[]', - -- {} + '["ABC"]', - -- {ABC} + '["ABC", "DEF"]', - -- {ABC and DEF} + '["ABC", "DEF", "G", "H"]'] -- {ABC, DEF, G and H} + loop lst over lists + say lst.right(30) ':' quibble(lst) + end lst + return diff --git a/Task/Comma-quibbling/PARI-GP/comma-quibbling.pari b/Task/Comma-quibbling/PARI-GP/comma-quibbling.pari new file mode 100644 index 0000000000..572dd52f3d --- /dev/null +++ b/Task/Comma-quibbling/PARI-GP/comma-quibbling.pari @@ -0,0 +1,11 @@ +comma(v)={ + if(#v==0, return("{}")); + if(#v==1, return(Str("{"v[1]"}"))); + my(s=Str("{",v[1])); + for(i=2,#v-1,s=Str(s,", ",v[i])); + Str(s," and ",v[#v],"}") +}; +comma([]) +comma(["ABC"]) +comma(["ABC", "DEF"]) +comma(["ABC", "DEF", "G", "H"]) diff --git a/Task/Comma-quibbling/PHP/comma-quibbling.php b/Task/Comma-quibbling/PHP/comma-quibbling.php new file mode 100644 index 0000000000..296c9e2c0f --- /dev/null +++ b/Task/Comma-quibbling/PHP/comma-quibbling.php @@ -0,0 +1,29 @@ +1 Then + result=result!!' and '!!word(wn); + End; + Return('{'!!result!!'}'); + End; + End; diff --git a/Task/Comma-quibbling/Perl-6/comma-quibbling.pl6 b/Task/Comma-quibbling/Perl-6/comma-quibbling.pl6 new file mode 100644 index 0000000000..84bef54f04 --- /dev/null +++ b/Task/Comma-quibbling/Perl-6/comma-quibbling.pl6 @@ -0,0 +1,6 @@ +sub comma-quibbling(@A) { + <{ }>.join: @A < 2 ?? @A !! "@A[0..*-2].join(', ') and @A[*-1]"; +} + +say comma-quibbling($_) for + [], [], [], []; diff --git a/Task/Comma-quibbling/Perl/comma-quibbling-1.pl b/Task/Comma-quibbling/Perl/comma-quibbling-1.pl new file mode 100644 index 0000000000..e994df60b9 --- /dev/null +++ b/Task/Comma-quibbling/Perl/comma-quibbling-1.pl @@ -0,0 +1,8 @@ +sub comma_quibbling(@) { + return "{$_}" for + @_ < 2 ? "@_" : + join(', ', @_[0..@_-2]) . ' and ' . $_[-1]; +} + +print comma_quibbling(@$_), "\n" for + [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)]; diff --git a/Task/Comma-quibbling/Perl/comma-quibbling-2.pl b/Task/Comma-quibbling/Perl/comma-quibbling-2.pl new file mode 100644 index 0000000000..1d3a4b826a --- /dev/null +++ b/Task/Comma-quibbling/Perl/comma-quibbling-2.pl @@ -0,0 +1,8 @@ +use 5.01; +sub comma_quibbling{ + my $last = pop // ''; + return '{'. (@_ ? (join ', ', @_).' and '.$last : $last).'}'; +} + +say for map {comma_quibbling(@$_)} + [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)]; diff --git a/Task/Comma-quibbling/PicoLisp/comma-quibbling.l b/Task/Comma-quibbling/PicoLisp/comma-quibbling.l new file mode 100644 index 0000000000..f4f4f5e241 --- /dev/null +++ b/Task/Comma-quibbling/PicoLisp/comma-quibbling.l @@ -0,0 +1,8 @@ +(for L '([] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"]) + (let H (head -1 L) + (prinl + "{" + (glue ", " H) + (and H " and ") + (last L) + "}" ) ) ) diff --git a/Task/Comma-quibbling/Prolog/comma-quibbling-1.pro b/Task/Comma-quibbling/Prolog/comma-quibbling-1.pro new file mode 100644 index 0000000000..5de5f51554 --- /dev/null +++ b/Task/Comma-quibbling/Prolog/comma-quibbling-1.pro @@ -0,0 +1,18 @@ +words_series(Words, Bracketed) :- + words_serialized(Words, Serialized), + atomics_to_string(["{",Serialized,"}"], Bracketed). + +words_serialized([], ""). +words_serialized([Word], Word) :- !. +words_serialized(Words, Serialized) :- + append(Rest, [Last], Words), %% Splits the list of *Words* into the *Last* word and the *Rest* + atomics_to_string(Rest, ", ", WithCommas), + atomics_to_string([WithCommas, " and ", Last], Serialized). + + + +test :- + forall( member(Words, [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]), + ( words_series(Words, Series), + format('~w ~15|=> ~w~n', [Words, Series])) + ). diff --git a/Task/Comma-quibbling/Prolog/comma-quibbling-2.pro b/Task/Comma-quibbling/Prolog/comma-quibbling-2.pro new file mode 100644 index 0000000000..b4558f7e34 --- /dev/null +++ b/Task/Comma-quibbling/Prolog/comma-quibbling-2.pro @@ -0,0 +1,6 @@ +?- test. +[] => {} +[ABC] => {ABC} +[ABC,DEF] => {ABC and DEF} +[ABC,DEF,G,H] => {ABC, DEF, G and H} +true. diff --git a/Task/Comma-quibbling/Python/comma-quibbling-1.py b/Task/Comma-quibbling/Python/comma-quibbling-1.py new file mode 100644 index 0000000000..f2d4c217cf --- /dev/null +++ b/Task/Comma-quibbling/Python/comma-quibbling-1.py @@ -0,0 +1,12 @@ +>>> def strcat(sequence): + return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1] + +>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]): + print('Input: %-24r -> Output: %r' % (seq, strcat(seq))) + + +Input: [] -> Output: '{}' +Input: ['ABC'] -> Output: '{ABC}' +Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}' +Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}' +>>> diff --git a/Task/Comma-quibbling/Python/comma-quibbling-2.py b/Task/Comma-quibbling/Python/comma-quibbling-2.py new file mode 100644 index 0000000000..53947052c1 --- /dev/null +++ b/Task/Comma-quibbling/Python/comma-quibbling-2.py @@ -0,0 +1,5 @@ +def commaQuibble(s): + return '{%s}' % ' and '.join(s).replace(' and ', ', ', len(s) - 2) + +for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]): + print('Input: %-24r -> Output: %r' % (seq, commaQuibble(seq))) diff --git a/Task/Comma-quibbling/Python/comma-quibbling-3.py b/Task/Comma-quibbling/Python/comma-quibbling-3.py new file mode 100644 index 0000000000..a6ee1dc736 --- /dev/null +++ b/Task/Comma-quibbling/Python/comma-quibbling-3.py @@ -0,0 +1,15 @@ +>>> def quibble(s): + return ('{' + + (', '.join(s[:-1]) + ' and ' if len(s) > 1 else '') + + (s[-1] if s else '') + + '}') + +>>> for seq in ([], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]): + print('Input: %-24r -> Output: %r' % (seq, quibble(seq))) + + +Input: [] -> Output: '{}' +Input: ['ABC'] -> Output: '{ABC}' +Input: ['ABC', 'DEF'] -> Output: '{ABC and DEF}' +Input: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}' +>>> diff --git a/Task/Comma-quibbling/README b/Task/Comma-quibbling/README new file mode 100644 index 0000000000..04060185a3 --- /dev/null +++ b/Task/Comma-quibbling/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Comma_quibbling diff --git a/Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol b/Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol new file mode 100644 index 0000000000..d6f12f39ba --- /dev/null +++ b/Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol @@ -0,0 +1,18 @@ +Rebol [] + +comma-quibbling: func [block] [ + rejoin [ + "^{" + + to-string use [s] [ + s: copy block + s: next s + forskip s 2 [insert s either tail? next s [" and "] [", "]] + s: head s + ] + + "^}" + ] +] + +foreach t [[] [ABC] [ABC DEF] [ABC DEF G H]] [print comma-quibbling t] diff --git a/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol b/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol new file mode 100644 index 0000000000..42c9c25002 --- /dev/null +++ b/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol @@ -0,0 +1,24 @@ +Rebol [] + +; builds string instead of using an intermediate block + +comma-quibbling: func [block /oxford /local s length] [ + length: length? block + rejoin [ + "^{" + + either length < 2 [to-string block] [ + s: to-string block/1 + for n 2 (length - 1) 1 [repend s [", " pick block n]] + if all [oxford (length > 2)] [append s ","] + repend s [" and " last block] + ] + + "^}" + ] +] + +test: [[] [ABC] [ABC DEF] [ABC DEF G H]] +foreach t test [print comma-quibbling t] +print "Now with Oxford comma" +foreach t test [print comma-quibbling/oxford t] diff --git a/Task/Comma-quibbling/REXX/comma-quibbling-1.rexx b/Task/Comma-quibbling/REXX/comma-quibbling-1.rexx new file mode 100644 index 0000000000..21b917c034 --- /dev/null +++ b/Task/Comma-quibbling/REXX/comma-quibbling-1.rexx @@ -0,0 +1,15 @@ +say quibbling('') +say quibbling('ABC') +say quibbling('ABC DEF') +say quibbling('ABC DEF G H') +exit + +quibbling: procedure + parse arg list + Select + When list='' Then result='' + When words(list)=1 then result=word(list,1) + Otherwise result=translate(strip(subword(list,1,words(list)-1)),',',' '), + 'and' word(list,words(list)) + End + Return '{'result'}' diff --git a/Task/Comma-quibbling/REXX/comma-quibbling-2.rexx b/Task/Comma-quibbling/REXX/comma-quibbling-2.rexx new file mode 100644 index 0000000000..707c692c22 --- /dev/null +++ b/Task/Comma-quibbling/REXX/comma-quibbling-2.rexx @@ -0,0 +1,21 @@ +say quibbling('') +say quibbling('ABC') +say quibbling('ABC DEF') +say quibbling('ABC DEF G H') +exit +quibbling: + parse arg list + If list='' Then result='' + Else Do + Do wi=1 By 1 while list<>'' + Parse Var list word.wi ' ' list + End + wn=wi-1 + result=word.1 + Do wi=2 To wn-1 + result=result', 'word.wi + End + If wn>1 Then + result=result 'and' word.wn + End + Return '{'result'}' diff --git a/Task/Comma-quibbling/REXX/comma-quibbling-3.rexx b/Task/Comma-quibbling/REXX/comma-quibbling-3.rexx new file mode 100644 index 0000000000..13c8ae06cc --- /dev/null +++ b/Task/Comma-quibbling/REXX/comma-quibbling-3.rexx @@ -0,0 +1,24 @@ +/* Rexx */ + +i_ = 0 +i_ = i_ + 1; lists.0 = i_; lists.i_ = '[]' +i_ = i_ + 1; lists.0 = i_; lists.i_ = '["ABC"]' +i_ = i_ + 1; lists.0 = i_; lists.i_ = '["ABC", ''DEF'']' +i_ = i_ + 1; lists.0 = i_; lists.i_ = '[ABC, DEF, G, H]' + +say +do i_ = 1 to lists.0 + list = lists.i_ + say right(list, 30) ':' quibbling03(list) + end i_ +exit + +quibbling03: +procedure + parse arg '[' lst ']' + lst = changestr('"', changestr("'", lst, ''), '') -- remove double & single quotes + lc = lastpos(',', lst) + if lc > 0 then + lst = overlay(' ', insert('and', lst, lc), lc) + lst = space(lst, 1) -- remove extra spaces + return '{'lst'}' diff --git a/Task/Comma-quibbling/Racket/comma-quibbling.rkt b/Task/Comma-quibbling/Racket/comma-quibbling.rkt new file mode 100644 index 0000000000..ff0fd70c3b --- /dev/null +++ b/Task/Comma-quibbling/Racket/comma-quibbling.rkt @@ -0,0 +1,11 @@ +(define (quibbling words) + (define (sub-quibbling words) + (match words + ['() ""] + [(list a) a] + [(list a b) (format "~a and ~a" a b)] + [(list a b ___) (format "~a, ~a" a (sub-quibbling b))])) + (format "{~a}" (sub-quibbling words))) + +(for ((input '([] ["ABC"] ["ABC" "DEF"] ["ABC" "DEF" "G" "H"]))) + (printf "~s\t->\t~a~%" input (quibbling input))) diff --git a/Task/Comma-quibbling/Ruby/comma-quibbling.rb b/Task/Comma-quibbling/Ruby/comma-quibbling.rb new file mode 100644 index 0000000000..a7e45dc4dc --- /dev/null +++ b/Task/Comma-quibbling/Ruby/comma-quibbling.rb @@ -0,0 +1,8 @@ +def comma_quibbling(a) + %w<{ }>.join(a.length < 2 ? a.first : + "#{a[0..-2].join(', ')} and #{a[-1]}") +end + +[[], %w, %w, %w].each do |a| + puts comma_quibbling(a) +end diff --git a/Task/Comma-quibbling/Run-BASIC/comma-quibbling.run b/Task/Comma-quibbling/Run-BASIC/comma-quibbling.run new file mode 100644 index 0000000000..afc27b12ca --- /dev/null +++ b/Task/Comma-quibbling/Run-BASIC/comma-quibbling.run @@ -0,0 +1,18 @@ +wrds$ = "[] +[""ABC""] +[""ABC"", ""DEF""] +[""ABC"", ""DEF"", ""G"", ""H""] +" +while word$(wrds$,j+1,chr$(13)) <> "" + a$ = word$(wrds$,j+1,chr$(13)) + print a$;" ==> "; + a$ = "{"+mid$(a$,2,len(a$)-2)+"}" + j = j + 1 + for i = len(a$) to 1 step -1 + if mid$(a$,i,1) = "," then + a$ = left$(a$,i-1) + " and " + mid$(a$,i+2) + exit for + end if + next i + print a$ +WEND diff --git a/Task/Comma-quibbling/Rust/comma-quibbling.rust b/Task/Comma-quibbling/Rust/comma-quibbling.rust new file mode 100644 index 0000000000..659705da7d --- /dev/null +++ b/Task/Comma-quibbling/Rust/comma-quibbling.rust @@ -0,0 +1,16 @@ +// rust 0.9-pre + +fn quibble(seq: &[&str]) -> ~str { + match seq { + [] => ~"{}", + [ref word] => "{" + *word + "}", + [..words, ref word] => "{" + words.connect(", ") + " and " + *word + "}", + } +} + +fn main() { + println(quibble([])); + println(quibble(["ABC"])); + println(quibble(["ABC", "DEF"])); + println(quibble(["ABC", "DEF", "G", "H"])); +} diff --git a/Task/Comma-quibbling/Scala/comma-quibbling.scala b/Task/Comma-quibbling/Scala/comma-quibbling.scala new file mode 100644 index 0000000000..f44be074f8 --- /dev/null +++ b/Task/Comma-quibbling/Scala/comma-quibbling.scala @@ -0,0 +1,13 @@ +def quibble( s:List[String] ) = s match { + case m if m.isEmpty => "{}" + case m if m.length < 3 => m.mkString("{", " and ", "}") + case m => "{" + m.init.mkString(", ") + " and " + m.last + "}" +} + +// A little test... +{ + println( quibble( List() ) ) + println( quibble( List("ABC") ) ) + println( quibble( List("ABC","DEF") ) ) + println( quibble( List("ABC","DEF","G","H") ) ) +} diff --git a/Task/Comma-quibbling/Seed7/comma-quibbling.seed7 b/Task/Comma-quibbling/Seed7/comma-quibbling.seed7 new file mode 100644 index 0000000000..8004a15c15 --- /dev/null +++ b/Task/Comma-quibbling/Seed7/comma-quibbling.seed7 @@ -0,0 +1,21 @@ +$ include "seed7_05.s7i"; + +const func string: quibble (in array string: input) is func + result + var string: quibble is "{"; + begin + case length(input) of + when {0}: quibble &:= "}"; + when {1}: quibble &:= input[1] & "}"; + otherwise: quibble &:= join(input[.. pred(length(input))], ", ") & + " and " & input[length(input)] & "}"; + end case; + end func; + +const proc: main is func + begin + writeln(quibble(0 times "")); + writeln(quibble([] ("ABC"))); + writeln(quibble([] ("ABC", "DEF"))); + writeln(quibble([] ("ABC", "DEF", "G", "H"))); + end func; diff --git a/Task/Comma-quibbling/Standard-ML/comma-quibbling.ml b/Task/Comma-quibbling/Standard-ML/comma-quibbling.ml new file mode 100644 index 0000000000..4b244c6be5 --- /dev/null +++ b/Task/Comma-quibbling/Standard-ML/comma-quibbling.ml @@ -0,0 +1,14 @@ +local + fun quib [] = "" + | quib [x] = x + | quib [x0,x1] = x0 ^ " and " ^ x1 + | quib (x::xs) = x ^ ", " ^ quib xs +in + fun quibble xs = "{" ^ quib xs ^ "}" +end + +(* Tests: *) +val t_quibble_0 = quibble [] = "{}" +val t_quibble_1 = quibble ["ABC"] = "{ABC}" +val t_quibble_2 = quibble ["ABC", "DEF"] = "{ABC and DEF}" +val t_quibble_3 = quibble ["ABC", "DEF", "G", "H"] = "{ABC, DEF, G and H}" diff --git a/Task/Comma-quibbling/Tcl/comma-quibbling.tcl b/Task/Comma-quibbling/Tcl/comma-quibbling.tcl new file mode 100644 index 0000000000..52971cde22 --- /dev/null +++ b/Task/Comma-quibbling/Tcl/comma-quibbling.tcl @@ -0,0 +1,7 @@ +proc commaQuibble {lst} { + return \{[join [lreplace $lst end-1 end [join [lrange $lst end-1 end] " and "]] ", "]\} +} + +foreach input { {} {"ABC"} {"ABC" "DEF"} {"ABC" "DEF" "G" "H"} } { + puts [commaQuibble $input] +} diff --git a/Task/Comma-quibbling/UNIX-Shell/comma-quibbling.sh b/Task/Comma-quibbling/UNIX-Shell/comma-quibbling.sh new file mode 100644 index 0000000000..0753bac442 --- /dev/null +++ b/Task/Comma-quibbling/UNIX-Shell/comma-quibbling.sh @@ -0,0 +1,15 @@ +quibble() { + # Here awk(1) is easier than sed(1). + awk 'BEGIN { + for (i = 1; i < ARGC - 2; i++) s = s ARGV[i] ", " + i = ARGC - 2; if (i > 0) s = s ARGV[i] " and " + i = ARGC - 1; if (i > 0) s = s ARGV[i] + printf "{%s}\n", s + exit 0 + }' "$@" +} + +quibble +quibble ABC +quibble ABC DEF +quibble ABC DEF G H diff --git a/Task/Comma-quibbling/XPL0/comma-quibbling.xpl0 b/Task/Comma-quibbling/XPL0/comma-quibbling.xpl0 new file mode 100644 index 0000000000..b2885d19ff --- /dev/null +++ b/Task/Comma-quibbling/XPL0/comma-quibbling.xpl0 @@ -0,0 +1,17 @@ +include c:\cxpl\codes; + +proc Quibble(N, S); +int N, S; +int I; +[ChOut(0, ^{); +for I:= 0 to N-1 do + [Text(0, S(I)); + if IM contains [[Arithmetic/Complex|complex numbers]]. Then the [[wp:conjugate transpose|conjugate transpose]] of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. + +: (M^H)_{ji} = \overline{M_{ij}} + +This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. + +In the next list, M must also be a square matrix. + +* A [[wp:Hermitian matrix|Hermitian matrix]] equals its own conjugate transpose: M^H = M. +* A [[wp:normal matrix|normal matrix]] is commutative in [[matrix multiplication|multiplication]] with its conjugate transpose: M^HM = MM^H. +* A [[wp:unitary matrix|unitary matrix]] has its [[inverse matrix|inverse]] equal to its conjugate transpose: M^H = M^{-1}. This is true [[wikt:iff|iff]] M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix. + +Given some matrix of complex numbers, find its conjugate transpose. Also determine if it is a Hermitian matrix, normal matrix, or a unitary matrix. + +* MathWorld: [http://mathworld.wolfram.com/ConjugateTranspose.html conjugate transpose], [http://mathworld.wolfram.com/HermitianMatrix.html Hermitian matrix], [http://mathworld.wolfram.com/NormalMatrix.html normal matrix], [http://mathworld.wolfram.com/UnitaryMatrix.html unitary matrix] diff --git a/Task/Conjugate-transpose/00META.yaml b/Task/Conjugate-transpose/00META.yaml new file mode 100644 index 0000000000..106b0ac419 --- /dev/null +++ b/Task/Conjugate-transpose/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Matrices diff --git a/Task/Conjugate-transpose/Ada/conjugate-transpose.ada b/Task/Conjugate-transpose/Ada/conjugate-transpose.ada new file mode 100644 index 0000000000..8970ff2944 --- /dev/null +++ b/Task/Conjugate-transpose/Ada/conjugate-transpose.ada @@ -0,0 +1,47 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Complex_Text_IO; use Ada.Complex_Text_IO; +with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types; +with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays; +procedure ConTrans is + subtype CM is Complex_Matrix; + S2O2 : constant Float := 0.7071067811865; + + procedure Print (mat : CM) is begin + for row in mat'Range(1) loop for col in mat'Range(2) loop + Put(mat(row,col), Exp=>0, Aft=>4); + end loop; New_Line; end loop; + end Print; + + function almostzero(mat : CM; tol : Float) return Boolean is begin + for row in mat'Range(1) loop for col in mat'Range(2) loop + if abs(mat(row,col)) > tol then return False; end if; + end loop; end loop; + return True; + end almostzero; + + procedure Examine (mat : CM) is + CT : CM := Conjugate (Transpose(mat)); + isherm, isnorm, isunit : Boolean; + begin + isherm := almostzero(mat-CT, 1.0e-6); + isnorm := almostzero(mat*CT-CT*mat, 1.0e-6); + isunit := almostzero(CT-Inverse(mat), 1.0e-6); + Print(mat); + Put_Line("Conjugate transpose:"); Print(CT); + Put_Line("Hermitian?: " & isherm'Img); + Put_Line("Normal?: " & isnorm'Img); + Put_Line("Unitary?: " & isunit'Img); + end Examine; + + hmat : CM := ((3.0+0.0*i, 2.0+1.0*i), (2.0-1.0*i, 1.0+0.0*i)); + nmat : CM := ((1.0+0.0*i, 1.0+0.0*i, 0.0+0.0*i), + (0.0+0.0*i, 1.0+0.0*i, 1.0+0.0*i), + (1.0+0.0*i, 0.0+0.0*i, 1.0+0.0*i)); + umat : CM := ((S2O2+0.0*i, S2O2+0.0*i, 0.0+0.0*i), + (0.0+S2O2*i, 0.0-S2O2*i, 0.0+0.0*i), + (0.0+0.0*i, 0.0+0.0*i, 0.0+1.0*i)); +begin + Put_Line("hmat:"); Examine(hmat); New_Line; + Put_Line("nmat:"); Examine(nmat); New_Line; + Put_Line("umat:"); Examine(umat); +end ConTrans; diff --git a/Task/Conjugate-transpose/C/conjugate-transpose.c b/Task/Conjugate-transpose/C/conjugate-transpose.c new file mode 100644 index 0000000000..9fff2c523a --- /dev/null +++ b/Task/Conjugate-transpose/C/conjugate-transpose.c @@ -0,0 +1,184 @@ +/*28th August, 2012 +Abhishek Ghosh + +Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */ + +#include +#include +#include + +typedef struct +{ + int rows, cols; + complex **z; +} matrix; + +matrix +transpose (matrix a) +{ + int i, j; + matrix b; + + b.rows = a.cols; + b.cols = a.rows; + + b.z = malloc (b.rows * sizeof (complex *)); + + for (i = 0; i < b.rows; i++) + { + b.z[i] = malloc (b.cols * sizeof (complex)); + for (j = 0; j < b.cols; j++) + { + b.z[i][j] = conj (a.z[j][i]); + } + } + + return b; +} + +int +isHermitian (matrix a) +{ + int i, j; + matrix b = transpose (a); + + if (b.rows == a.rows && b.cols == a.cols) + { + for (i = 0; i < b.rows; i++) + { + for (j = 0; j < b.cols; j++) + { + if (b.z[i][j] != a.z[i][j]) + return 0; + } + } + } + + else + return 0; + + return 1; +} + +matrix +multiply (matrix a, matrix b) +{ + matrix c; + int i, j; + + if (a.cols == b.rows) + { + c.rows = a.rows; + c.cols = b.cols; + + c.z = malloc (c.rows * (sizeof (complex *))); + + for (i = 0; i < c.rows; i++) + { + c.z[i] = malloc (c.cols * sizeof (complex)); + c.z[i][j] = 0 + 0 * I; + for (j = 0; j < b.cols; j++) + { + c.z[i][j] += a.z[i][j] * b.z[j][i]; + } + } + + } + + return c; +} + +int +isNormal (matrix a) +{ + int i, j; + matrix a_ah, ah_a; + + if (a.rows != a.cols) + return 0; + + a_ah = multiply (a, transpose (a)); + ah_a = multiply (transpose (a), a); + + for (i = 0; i < a.rows; i++) + { + for (j = 0; j < a.cols; j++) + { + if (a_ah.z[i][j] != ah_a.z[i][j]) + return 0; + } + } + + return 1; +} + +int +isUnitary (matrix a) +{ + matrix b; + int i, j; + if (isNormal (a) == 1) + { + b = multiply (a, transpose(a)); + + for (i = 0; i < b.rows; i++) + { + for (j = 0; j < b.cols; j++) + { + if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) + return 0; + } + } + return 1; + } + return 0; +} + + +int +main () +{ + complex z = 3 + 4 * I; + matrix a, aT; + int i, j; + printf ("Enter rows and columns :"); + scanf ("%d%d", &a.rows, &a.cols); + + a.z = malloc (a.rows * sizeof (complex *)); + printf ("Randomly Generated Complex Matrix A is : "); + for (i = 0; i < a.rows; i++) + { + printf ("\n"); + a.z[i] = malloc (a.cols * sizeof (complex)); + for (j = 0; j < a.cols; j++) + { + a.z[i][j] = rand () % 10 + rand () % 10 * I; + printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); + } + } + + aT = transpose (a); + + printf ("\n\nTranspose of Complex Matrix A is : "); + for (i = 0; i < aT.rows; i++) + { + printf ("\n"); + aT.z[i] = malloc (aT.cols * sizeof (complex)); + for (j = 0; j < aT.cols; j++) + { + aT.z[i][j] = rand () % 10 + rand () % 10 * I; + printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); + } + } + + printf ("\n\nComplex Matrix A %s hermitian", + isHermitian (a) == 1 ? "is" : "is not"); + printf ("\n\nComplex Matrix A %s unitary", + isUnitary (a) == 1 ? "is" : "is not"); + printf ("\n\nComplex Matrix A %s normal", + isNormal (a) == 1 ? "is" : "is not"); + + + + return 0; +} diff --git a/Task/Conjugate-transpose/D/conjugate-transpose-1.d b/Task/Conjugate-transpose/D/conjugate-transpose-1.d new file mode 100644 index 0000000000..a26674ebd2 --- /dev/null +++ b/Task/Conjugate-transpose/D/conjugate-transpose-1.d @@ -0,0 +1,107 @@ +import std.stdio, std.complex, std.math, std.range, std.algorithm, + std.numeric; + +T[][] conjugateTranspose(T)(in T[][] m) pure nothrow @safe { + auto r = new typeof(return)(m[0].length, m.length); + foreach (immutable nr, const row; m) + foreach (immutable nc, immutable c; row) + r[nc][nr] = c.conj; + return r; +} + +bool isRectangular(T)(in T[][] M) pure nothrow @safe @nogc { + return M.all!(row => row.length == M[0].length); +} + +T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/ +in { + assert(A.isRectangular && B.isRectangular && + !A.empty && !B.empty && A[0].length == B.length); +} body { + auto result = new T[][](A.length, B[0].length); + auto aux = new T[B.length]; + + foreach (immutable j; 0 .. B[0].length) { + foreach (immutable k, const row; B) + aux[k] = row[j]; + foreach (immutable i, const ai; A) + result[i][j] = dotProduct(ai, aux); + } + + return result; +} + +/// Check any number of complex matrices for equality within +/// some bits of mantissa. +bool areEqual(T)(in Complex!T[][][] matrices, in size_t nBits=20) +pure nothrow /*@safe*/ { + static bool allSame(U)(in U[] v) pure nothrow @nogc { + return v[1 .. $].all!(c => c == v[0]); + } + + bool allNearSame(in Complex!T[] v) pure nothrow @nogc { + auto v0 = v[0].Complex!T; // To avoid another cast. + return v[1 .. $].all!(c => feqrel(v0.re, c.re) >= nBits && + feqrel(v0.im, c.im) >= nBits); + } + + immutable x = matrices.map!(m => m.length).array; + if (!allSame(x)) + return false; + immutable y = matrices.map!(m => m[0].length).array; + if (!allSame(y)) + return false; + foreach (immutable s; 0 .. x[0]) + foreach (immutable t; 0 .. y[0]) + if (!allNearSame(matrices.map!(m => m[s][t]).array)) + return false; + return true; +} + +bool isHermitian(T)(in Complex!T[][] m, in Complex!T[][] ct) +pure nothrow /*@safe*/ { + return [m, ct].areEqual; +} + +bool isNormal(T)(in Complex!T[][] m, in Complex!T[][] ct) +pure nothrow /*@safe*/ { + return [matMul(m, ct), matMul(ct, m)].areEqual; +} + +auto complexIdentitymatrix(in size_t side) pure nothrow /*@safe*/ { + return side.iota.map!(r => side.iota.map!(c => complex(r == c)).array).array; +} + +bool isUnitary(T)(in Complex!T[][] m, in Complex!T[][] ct) +pure nothrow /*@safe*/ { + immutable mct = matMul(m, ct); + immutable ident = mct.length.complexIdentitymatrix; + return [mct, matMul(ct, m), ident].areEqual; +} + +void main() /*@safe*/ { + alias C = complex; + immutable x = 2 ^^ 0.5 / 2; + + immutable data = [[[C(3.0, 0.0), C(2.0, 1.0)], + [C(2.0, -1.0), C(1.0, 0.0)]], + + [[C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)], + [C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)], + [C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)]], + + [[C(x, 0.0), C(x, 0.0), C(0.0, 0.0)], + [C(0.0, -x), C(0.0, x), C(0.0, 0.0)], + [C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)]]]; + + foreach (immutable mat; data) { + enum mFormat = "[%([%(%1.3f, %)],\n %)]]"; + writefln("Matrix:\n" ~ mFormat, mat); + immutable ct = conjugateTranspose(mat); + "Its conjugate transpose:".writeln; + writefln(mFormat, ct); + writefln("Hermitian? %s.", isHermitian(mat, ct)); + writefln("Normal? %s.", isNormal(mat, ct)); + writefln("Unitary? %s.\n", isUnitary(mat, ct)); + } +} diff --git a/Task/Conjugate-transpose/D/conjugate-transpose-2.d b/Task/Conjugate-transpose/D/conjugate-transpose-2.d new file mode 100644 index 0000000000..6897ea6e59 --- /dev/null +++ b/Task/Conjugate-transpose/D/conjugate-transpose-2.d @@ -0,0 +1,90 @@ +import std.stdio, std.complex, std.math, std.range, std.algorithm, + std.numeric, std.exception, std.traits; + +// alias CM(T) = Complex!T[][]; // Not yet useful. + +auto conjugateTranspose(T)(in Complex!T[][] m) pure nothrow /*@safe*/ +if (!hasIndirections!T) { + return iota(m[0].length).map!(i => m.transversal(i).map!conj.array).array; +} + +T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow /*@safe*/ { + immutable Bt = B[0].length.iota.map!(i => B.transversal(i).array).array; + return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array; +} + +/// Check any number of complex matrices for equality within +/// some bits of mantissa. +bool areEqual(T)(in Complex!T[][][] matrices, in size_t nBits=20) +pure nothrow /*@safe*/ { + static bool allSame(U)(in U[] v) pure nothrow @nogc @safe { + return v[1 .. $].all!(c => c == v[0]); + } + + bool allNearSame(in Complex!T[] v) pure nothrow @nogc @safe { + auto v0 = v[0].Complex!T; // To avoid another cast. + return v[1 .. $].all!(c => feqrel(v0.re, c.re) >= nBits && + feqrel(v0.im, c.im) >= nBits); + } + + immutable x = matrices.map!(m => m.length).array; + if (!allSame(x)) + return false; + immutable y = matrices.map!(m => m[0].length).array; + if (!allSame(y)) + return false; + foreach (immutable s; 0 .. x[0]) + foreach (immutable t; 0 .. y[0]) + if (!allNearSame(matrices.map!(m => m[s][t]).array)) + return false; + return true; +} + +bool isHermitian(T)(in Complex!T[][] m, in Complex!T[][] ct) +pure nothrow /*@safe*/ { + return [m, ct].areEqual; +} + +bool isNormal(T)(immutable Complex!T[][] m, immutable Complex!T[][] ct) +pure nothrow /*@safe*/ { + return [matMul(m, ct), matMul(ct, m)].areEqual; +} + +auto complexIdentitymatrix(in size_t side) pure nothrow /*@safe*/ { + return side.iota.map!(r => side.iota.map!(c => complex(r == c)).array).array; +} + +bool isUnitary(T)(immutable Complex!T[][] m, immutable Complex!T[][] ct) +pure nothrow /*@safe*/ { + immutable mct = matMul(m, ct); + immutable ident = mct.length.complexIdentitymatrix; + return [mct, matMul(ct, m), ident].areEqual; +} + +void main() { + alias C = complex; + immutable x = 2 ^^ 0.5 / 2; + + foreach (/*immutable*/ const matrix; + [[[C(3.0, 0.0), C(2.0, 1.0)], + [C(2.0, -1.0), C(1.0, 0.0)]], + + [[C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)], + [C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)], + [C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)]], + + [[C(x, 0.0), C(x, 0.0), C(0.0, 0.0)], + [C(0.0, -x), C(0.0, x), C(0.0, 0.0)], + [C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)]]]) { + immutable mat = matrix.assumeUnique; //* + + enum mFormat = "[%([%(%1.3f, %)],\n %)]]"; + writefln("Matrix:\n" ~ mFormat, mat); + immutable ct = conjugateTranspose(mat); + "Its conjugate transpose:".writeln; + writefln(mFormat, ct); + writefln("Hermitian? %s.", isHermitian(mat, ct)); + writefln("Normal? %s.", isNormal(mat, ct)); + writefln("Unitary? %s.\n", isUnitary(mat, ct)); + } +} diff --git a/Task/Conjugate-transpose/Factor/conjugate-transpose.factor b/Task/Conjugate-transpose/Factor/conjugate-transpose.factor new file mode 100644 index 0000000000..169148530c --- /dev/null +++ b/Task/Conjugate-transpose/Factor/conjugate-transpose.factor @@ -0,0 +1,14 @@ +USING: kernel math.functions math.matrices sequences ; +IN: rosetta.hermitian + +: conj-t ( matrix -- conjugate-transpose ) + flip [ [ conjugate ] map ] map ; + +: hermitian-matrix? ( matrix -- ? ) + dup conj-t = ; + +: normal-matrix? ( matrix -- ? ) + dup conj-t [ m. ] [ swap m. ] 2bi = ; + +: unitary-matrix? ( matrix -- ? ) + [ dup conj-t m. ] [ length identity-matrix ] bi = ; diff --git a/Task/Conjugate-transpose/Fortran/conjugate-transpose.f b/Task/Conjugate-transpose/Fortran/conjugate-transpose.f new file mode 100644 index 0000000000..de34656893 --- /dev/null +++ b/Task/Conjugate-transpose/Fortran/conjugate-transpose.f @@ -0,0 +1,64 @@ +program conjugate_transpose + + complex, dimension(3, 3) :: a + integer :: i + a = reshape((/ (i, i=1,9) /), shape(a)) + call characterize(a) + a(:2,:2) = reshape((/cmplx(3,0),cmplx(2,-1),cmplx(2,1),cmplx(1,0)/),(/2,2/)) + call characterize(a(:2,:2)) + call characterize(cmplx(reshape((/1,0,1,1,1,0,0,1,1/),(/3,3/)),0)) + a(3,:) = (/cmplx(0,0), cmplx(0,0), cmplx(0,1)/)*sqrt(2.0) + a(2,:) = (/cmplx(0,-1),cmplx(0,1),cmplx(0,0)/) + a(1,:) = (/1,1,0/) + a = a * sqrt(2.0)/2.0 + call characterize(a) + +contains + + subroutine characterize(a) + complex, dimension(:,:), intent(in) :: a + integer :: i, j + do i=1, size(a,1) + print *,(a(i, j), j=1,size(a,1)) + end do + print *,'Is Hermitian? ',HermitianQ(a) + print *,'Is normal? ',NormalQ(a) + print *,'Unitary? ',UnitaryQ(a) + print '(/)' + end subroutine characterize + + function ct(a) result(b) ! return the conjugate transpose of a matrix + complex, dimension(:,:), intent(in) :: a + complex, dimension(size(a,1),size(a,1)) :: b + b = conjg(transpose(a)) + end function ct + + function identity(n) result(b) ! return identity matrix + integer, intent(in) :: n + real, dimension(n,n) :: b + integer :: i + b = 0 + do i=1, n + b(i,i) = 1 + end do + end function identity + + logical function HermitianQ(a) + complex, dimension(:,:), intent(in) :: a + HermitianQ = all(a .eq. ct(a)) + end function HermitianQ + + logical function NormalQ(a) + complex, dimension(:,:), intent(in) :: a + NormalQ = all(matmul(ct(a),a) .eq. matmul(a,ct(a))) + end function NormalQ + + logical function UnitaryQ(a) + ! if A inverse equals A star + ! then multiplying each side by A should result in the identity matrix + ! Thus show that A times A star is sufficiently close to I . + complex, dimension(:,:), intent(in) :: a + UnitaryQ = all(abs(matmul(a,ct(a)) - identity(size(a,1))) .lt. 1e-6) + end function UnitaryQ + +end program conjugate_transpose diff --git a/Task/Conjugate-transpose/Go/conjugate-transpose.go b/Task/Conjugate-transpose/Go/conjugate-transpose.go new file mode 100644 index 0000000000..347c78b5eb --- /dev/null +++ b/Task/Conjugate-transpose/Go/conjugate-transpose.go @@ -0,0 +1,112 @@ +package main + +import ( + "fmt" + "math" + "math/cmplx" +) + +// a type to represent matrices +type matrix struct { + ele []complex128 + cols int +} + +// conjugate transpose, implemented here as a method on the matrix type. +func (m *matrix) conjTranspose() *matrix { + r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} + rx := 0 + for _, e := range m.ele { + r.ele[rx] = cmplx.Conj(e) + rx += r.cols + if rx >= len(r.ele) { + rx -= len(r.ele) - 1 + } + } + return r +} + +// program to demonstrate capabilites on example matricies +func main() { + show("h", matrixFromRows([][]complex128{ + {3, 2 + 1i}, + {2 - 1i, 1}})) + + show("n", matrixFromRows([][]complex128{ + {1, 1, 0}, + {0, 1, 1}, + {1, 0, 1}})) + + show("u", matrixFromRows([][]complex128{ + {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, + {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, + {0, 0, 1i}})) +} + +func show(name string, m *matrix) { + m.print(name) + ct := m.conjTranspose() + ct.print(name + "_ct") + + fmt.Println("Hermitian:", m.equal(ct, 1e-14)) + + mct := m.mult(ct) + ctm := ct.mult(m) + fmt.Println("Normal:", mct.equal(ctm, 1e-14)) + + i := eye(m.cols) + fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) +} + +// two constructors +func matrixFromRows(rows [][]complex128) *matrix { + m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} + for rx, row := range rows { + copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) + } + return m +} + +func eye(n int) *matrix { + r := &matrix{make([]complex128, n*n), n} + n++ + for x := 0; x < len(r.ele); x += n { + r.ele[x] = 1 + } + return r +} + +// print method outputs matrix to stdout +func (m *matrix) print(heading string) { + fmt.Print("\n", heading, "\n") + for e := 0; e < len(m.ele); e += m.cols { + fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) + fmt.Println() + } +} + +// equal method uses ε to allow for floating point error. +func (a *matrix) equal(b *matrix, ε float64) bool { + for x, aEle := range a.ele { + if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || + math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { + return false + } + } + return true +} + +// mult method taken from matrix multiply task +func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { + m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} + for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { + for m2r0 := 0; m2r0 < m2.cols; m2r0++ { + for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { + m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] + m1x++ + } + m3x++ + } + } + return m3 +} diff --git a/Task/Conjugate-transpose/J/conjugate-transpose-1.j b/Task/Conjugate-transpose/J/conjugate-transpose-1.j new file mode 100644 index 0000000000..37c90d093c --- /dev/null +++ b/Task/Conjugate-transpose/J/conjugate-transpose-1.j @@ -0,0 +1 @@ + ct =: +@|: NB. Conjugate transpose (ct A is A_ct) diff --git a/Task/Conjugate-transpose/J/conjugate-transpose-2.j b/Task/Conjugate-transpose/J/conjugate-transpose-2.j new file mode 100644 index 0000000000..01e9c0a33e --- /dev/null +++ b/Task/Conjugate-transpose/J/conjugate-transpose-2.j @@ -0,0 +1,13 @@ + X =: +/ . * NB. Matrix Multiply (x) + + HERMITIAN =: 3 2j1 ,: 2j_1 1 + (-: ct) HERMITIAN NB. A_ct = A +1 + + NORMAL =: 1 1 0 , 0 1 1 ,: 1 0 1 + ((X~ -: X) ct) NORMAL NB. A_ct x A = A x A_ct +1 + + UNITARY =: (-:%:2) * 1 1 0 , 0j_1 0j1 0 ,: 0 0 0j1 * %:2 + (ct -: %.) UNITARY NB. A_ct = A^-1 +1 diff --git a/Task/Conjugate-transpose/J/conjugate-transpose-3.j b/Task/Conjugate-transpose/J/conjugate-transpose-3.j new file mode 100644 index 0000000000..2e50183c7c --- /dev/null +++ b/Task/Conjugate-transpose/J/conjugate-transpose-3.j @@ -0,0 +1,16 @@ + HERMITIAN;NORMAL;UNITARY ++--------+-----+--------------------------+ +| 3 2j1|1 1 0| 0.707107 0.707107 0| +|2j_1 1|0 1 1|0j_0.707107 0j0.707107 0| +| |1 0 1| 0 0 0j1| ++--------+-----+--------------------------+ + NB. In J, PjQ is P + Q*i and the 0.7071... is sqrt(2) + + hermitian=: -: ct + normal =: (X~ -: X) ct + unitary=: ct -: %. + + (hermitian,normal,unitary)&.>HERMITIAN;NORMAL;UNITARY ++-----+-----+-----+ +|1 1 0|0 1 0|0 1 1| ++-----+-----+-----+ diff --git a/Task/Conjugate-transpose/Julia/conjugate-transpose-1.julia b/Task/Conjugate-transpose/Julia/conjugate-transpose-1.julia new file mode 100644 index 0000000000..e80e14d91d --- /dev/null +++ b/Task/Conjugate-transpose/Julia/conjugate-transpose-1.julia @@ -0,0 +1 @@ +A' diff --git a/Task/Conjugate-transpose/Julia/conjugate-transpose-2.julia b/Task/Conjugate-transpose/Julia/conjugate-transpose-2.julia new file mode 100644 index 0000000000..04839d9ca1 --- /dev/null +++ b/Task/Conjugate-transpose/Julia/conjugate-transpose-2.julia @@ -0,0 +1 @@ +ishermitian(A) diff --git a/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia b/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia new file mode 100644 index 0000000000..715e19c524 --- /dev/null +++ b/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia @@ -0,0 +1,2 @@ +isnormal(A) = size(A,1) == size(A,2) && A'*A == A*A' +isunitary(A) = size(A,1) == size(A,2) && A'*A == eye(A) diff --git a/Task/Conjugate-transpose/Maple/conjugate-transpose.maple b/Task/Conjugate-transpose/Maple/conjugate-transpose.maple new file mode 100644 index 0000000000..7b10e7740c --- /dev/null +++ b/Task/Conjugate-transpose/Maple/conjugate-transpose.maple @@ -0,0 +1,10 @@ +M:=<<3|2+I>,<2-I|1>>: + +with(LinearAlgebra): +IsNormal:=A->EqualEntries(A^%H.A,A.A^%H): + +M^%H; +HermitianTranspose(M); +type(M,'Matrix'(hermitian)); +IsNormal(M); +IsUnitary(M); diff --git a/Task/Conjugate-transpose/Mathematica/conjugate-transpose.math b/Task/Conjugate-transpose/Mathematica/conjugate-transpose.math new file mode 100644 index 0000000000..29769be48a --- /dev/null +++ b/Task/Conjugate-transpose/Mathematica/conjugate-transpose.math @@ -0,0 +1,17 @@ +NormalMatrixQ[a_List?MatrixQ] := Module[{b = Conjugate@Transpose@a},a.b === b.a] +UnitaryQ[m_List?MatrixQ] := (Conjugate@Transpose@m.m == IdentityMatrix@Length@m) + +m = {{1, 2I, 3}, {3+4I, 5, I}}; +m //MatrixForm +-> +(1 2I 3 +3+4I 5 I) + +ConjugateTranspose[m] //MatrixForm +-> +(1 3-4I +-2I 5 +3 -I) + +{HermitianMatrixQ@#, NormalMatrixQ@#, UnitaryQ@#}&@m +-> {False, False, False} diff --git a/Task/Conjugate-transpose/PARI-GP/conjugate-transpose.pari b/Task/Conjugate-transpose/PARI-GP/conjugate-transpose.pari new file mode 100644 index 0000000000..72eb173c42 --- /dev/null +++ b/Task/Conjugate-transpose/PARI-GP/conjugate-transpose.pari @@ -0,0 +1,4 @@ +conjtranspose(M)=conj(M~) +isHermitian(M)=M==conj(M~) +isnormal(M)=my(H=conj(M~));H*M==M*H +isunitary(M)=M*conj(M~)==1 diff --git a/Task/Conjugate-transpose/PL-I/conjugate-transpose.pli b/Task/Conjugate-transpose/PL-I/conjugate-transpose.pli new file mode 100644 index 0000000000..3afa5a479b --- /dev/null +++ b/Task/Conjugate-transpose/PL-I/conjugate-transpose.pli @@ -0,0 +1,49 @@ +test: procedure options (main); /* 1 October 2012 */ + declare n fixed binary; + + put ('Conjugate a complex square matrix.'); + put skip list ('What is the order of the matrix?:'); + get (n); + begin; + declare (M, MH, MM, MM_MMH, MM_MHM, IDENTITY)(n,n) fixed complex; + declare i fixed binary; + + IDENTITY = 0; do i = 1 to n; IDENTITY(I,I) = 1; end; + put skip list ('Please type the matrix:'); + get list (M); + do i = 1 to n; + put skip list (M(i,*)); + end; + do i = 1 to n; + MH(i,*) = conjg(M(*,i)); + end; + put skip list ('The conjugate transpose is:'); + do i = 1 to n; + put skip list (MH(i,*)); + end; + if all(M=MH) then + put skip list ('Matrix is Hermitian'); + call MMULT(M, MH, MM_MMH); + call MMULT(MH, M, MM_MHM); + + if all(MM_MMH = MM_MHM) then + put skip list ('Matrix is Normal'); + + if all(ABS(MM_MMH - IDENTITY) < 0.0001) then + put skip list ('Matrix is unitary'); + if all(ABS(MM_MHM - IDENTITY) < 0.0001) then + put skip list ('Matrix is unitary'); + end; + +MMULT: procedure (M, MH, MM); + declare (M, MH, MM)(*,*) fixed complex; + declare (i, j, n) fixed binary; + + n = hbound(M,1); + do i = 1 to n; + do j = 1 to n; + MM(i,j) = sum(M(i,*) * MH(*,j) ); + end; + end; +end MMULT; +end test; diff --git a/Task/Conjugate-transpose/Python/conjugate-transpose.py b/Task/Conjugate-transpose/Python/conjugate-transpose.py new file mode 100644 index 0000000000..235d0ead76 --- /dev/null +++ b/Task/Conjugate-transpose/Python/conjugate-transpose.py @@ -0,0 +1,72 @@ +def conjugate_transpose(m): + return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) + +def mmul( ma, mb): + return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) + +def mi(size): + 'Complex Identity matrix' + sz = range(size) + m = [[0 + 0j for i in sz] for j in sz] + for i in range(size): + m[i][i] = 1 + 0j + return tuple(tuple(row) for row in m) + +def __allsame(vector): + first, rest = vector[0], vector[1:] + return all(i == first for i in rest) + +def __allnearsame(vector, eps=1e-14): + first, rest = vector[0], vector[1:] + return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps + for i in rest) + +def isequal(matrices, eps=1e-14): + 'Check any number of matrices for equality within eps' + x = [len(m) for m in matrices] + if not __allsame(x): return False + y = [len(m[0]) for m in matrices] + if not __allsame(y): return False + for s in range(x[0]): + for t in range(y[0]): + if not __allnearsame([m[s][t] for m in matrices], eps): return False + return True + + +def ishermitian(m, ct): + return isequal([m, ct]) + +def isnormal(m, ct): + return isequal([mmul(m, ct), mmul(ct, m)]) + +def isunitary(m, ct): + mct, ctm = mmul(m, ct), mmul(ct, m) + mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) + ident = mi(mctx) + return isequal([mct, ctm, ident]) + +def printm(comment, m): + print(comment) + fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] + width = max(max(len(f) for f in row) for row in fields) + lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) + print('\n'.join(lines)) + +if __name__ == '__main__': + for matrix in [ + ((( 3.000+0.000j), (+2.000+1.000j)), + (( 2.000-1.000j), (+1.000+0.000j))), + + ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), + (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), + (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), + + ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), + (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), + (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: + printm('\nMatrix:', matrix) + ct = conjugate_transpose(matrix) + printm('Its conjugate transpose:', ct) + print('Hermitian? %s.' % ishermitian(matrix, ct)) + print('Normal? %s.' % isnormal(matrix, ct)) + print('Unitary? %s.' % isunitary(matrix, ct)) diff --git a/Task/Conjugate-transpose/README b/Task/Conjugate-transpose/README new file mode 100644 index 0000000000..2f7d38ba89 --- /dev/null +++ b/Task/Conjugate-transpose/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Conjugate_transpose diff --git a/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx b/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx new file mode 100644 index 0000000000..5f1d6cc189 --- /dev/null +++ b/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx @@ -0,0 +1,88 @@ +/*REXX pgm performs a conjugate transpose on a complex square matrix.*/ +parse arg N elements; if N=='' then N=3 +M.=0 /*Matrix has all elements = zero.*/ +k=0; do r=1 for N + do c=1 for N; k=k+1; M.r.c=word(word(elements,k) 1,1); end /*c*/ + end /*r*/ + +call showCmat 'M' ,N /*display a nice formatted matrix*/ +identity.=0; do d=1 for N; identity.d.d=1; end /*d*/ +call conjCmat 'MH', "M" ,N /*conjugate the M matrix ───► MH */ +call showCmat 'MH' ,N /*display a nice formatted matrix*/ +say 'M is Hermitian: ' word('no yes',isHermitian('M',"MH",N)+1) +call multCmat 'M', 'MH', 'MMH', N /*multiple two matrices together.*/ +call multCmat 'MH', 'M', 'MHM', N /* " " " " */ +say ' M is Normal: ' word('no yes',isHermitian('MMH',"MHM",N)+1) +say ' M is Unary: ' word('no yes',isUnary('M',N)+1) +say 'MMH is Unary: ' word('no yes',isUnary('MMH',N)+1) +say 'MHM is Unary: ' word('no yes',isUnary('MHM',N)+1) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CONJCMAT subroutine─────────────────*/ +conjCmat: arg matX,matY,rows 1 cols; call normCmat matY,rows + do r=1 for rows; _= + do c=1 for cols; v=value(matY'.'r"."c) + rP=rP(v); cP=-cP(v); call value matX'.'c"."r, rP','cP + end /*c*/ + end /*r*/ +return +/*──────────────────────────────────ISHERMITIAN subroutine──────────────*/ +isHermitian: arg matX,matY,rows 1 cols; call normCmat matX,rows + call normCmat matY,rows + do r=1 for rows; _= + do c=1 for cols + if value(matX'.'r"."c)\=value(matY'.'r"."c) then return 0 + end /*c*/ + end /*r*/ +return 1 +/*──────────────────────────────────ISUNARY subroutine──────────────────*/ +isUnary: arg matX,rows 1 cols + do r=1 for rows; _= + do c=1 for cols; z=value(matX'.'r"."c); rP=rP(z); cP=cP(z) + if abs(sqrt(rP(z)**2+cP(z)**2)-(r==c))>=.0001 then return 0 + end /*c*/ + end /*r*/ +return 1 +/*──────────────────────────────────MULTCMAT subroutine─────────────────*/ +multCmat: arg matA,matB,matT,rows 1 cols; call value matT'.',0 + do r=1 for rows; _= + do c=1 for cols + do k=1 for cols; T=value(matT'.'r"."c); Tr=rP(T); Tc=cP(T) + A=value(matA'.'r"."k); Ar=rP(A); Ac=cP(A) + B=value(matB'.'k"."c); Br=rP(B); Bc=cP(B) + Pr=Ar*Br-Ac*Bc; Pc=Ac*Br+Ar*Bc; Tr=Tr+Pr; Tc=Tc+Pc + call value matT'.'r"."c,Tr','Tc + end /*k*/ + end /*c*/ + end /*r*/ +return +/*──────────────────────────────────NORMCMAT subroutine─────────────────*/ +normCmat: arg matN,rows 1 cols + do r=1 to rows; _= + do c=1 to cols; v=translate(value(matN'.'r"."c),,"IiJj") + parse upper var v real ',' cplx + if real\=='' then real=real/1 + if cplx\=='' then cplx=cplx/1; if cplx=0 then cplx= + if cplx\=='' then cplx=cplx"j" + call value matN'.'r"."c,strip(real','cplx,"T",',') + end /*c*/ + end /*r*/ +return +/*──────────────────────────────────SHOWCMAT subroutine─────────────────*/ +showCmat: arg matX,rows,cols; if cols=='' then cols=rows; pad=left('',6) +say; say center('matrix' matX,79,'─'); call normCmat matX,rows,cols + do r=1 to rows; _= + do c=1 to cols; _=_ pad left(value(matX'.'r"."c),9) + end /*c*/ + say _ + end /*r*/ +say; return +/*──────────────────────────────────one─liner subroutines───────────────*/ +cP: procedure; arg ',' p; return word(strip(translate(p,,'IJ')) 0,1) +rP: procedure; parse arg r ','; return word(r 0,1) +/*──────────────────────────────────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 diff --git a/Task/Conjugate-transpose/Racket/conjugate-transpose-1.rkt b/Task/Conjugate-transpose/Racket/conjugate-transpose-1.rkt new file mode 100644 index 0000000000..d7098b8e72 --- /dev/null +++ b/Task/Conjugate-transpose/Racket/conjugate-transpose-1.rkt @@ -0,0 +1,16 @@ +#lang racket +(require math) +(define H matrix-hermitian) + +(define (normal? M) + (define MH (H M)) + (equal? (matrix* MH M) + (matrix* M MH))) + +(define (unitary? M) + (define MH (H M)) + (and (matrix-identity? (matrix* MH M)) + (matrix-identity? (matrix* M MH)))) + +(define (hermitian? M) + (equal? (H M) M)) diff --git a/Task/Conjugate-transpose/Racket/conjugate-transpose-2.rkt b/Task/Conjugate-transpose/Racket/conjugate-transpose-2.rkt new file mode 100644 index 0000000000..027fae2431 --- /dev/null +++ b/Task/Conjugate-transpose/Racket/conjugate-transpose-2.rkt @@ -0,0 +1,6 @@ +(define M (matrix [[3.000+0.000i +2.000+1.000i] + [2.000-1.000i +1.000+0.000i]])) +(H M) +(normal? M) +(unitary? M) +(hermitian? M) diff --git a/Task/Conjugate-transpose/Racket/conjugate-transpose-3.rkt b/Task/Conjugate-transpose/Racket/conjugate-transpose-3.rkt new file mode 100644 index 0000000000..4a04483074 --- /dev/null +++ b/Task/Conjugate-transpose/Racket/conjugate-transpose-3.rkt @@ -0,0 +1,4 @@ +(array #[#[3.0-0.0i 2.0+1.0i] #[2.0-1.0i 1.0-0.0i]]) +#t +#f +#f diff --git a/Task/Conjugate-transpose/Ruby/conjugate-transpose.rb b/Task/Conjugate-transpose/Ruby/conjugate-transpose.rb new file mode 100644 index 0000000000..819a0b5a90 --- /dev/null +++ b/Task/Conjugate-transpose/Ruby/conjugate-transpose.rb @@ -0,0 +1,25 @@ +require 'matrix' + +# Start with some matrix. +i = Complex::I +matrix = Matrix[[i, 0, 0], + [0, i, 0], + [0, 0, i]] + +# Find the conjugate transpose. +# Matrix#conjugate appeared in Ruby 1.9.2. +conjt = matrix.conj.t # aliases for matrix.conjugate.tranpose +print 'conjugate tranpose: '; puts conjt + +if matrix.square? + # These predicates appeared in Ruby 1.9.3. + print 'Hermitian? '; puts matrix.hermitian? + print ' normal? '; puts matrix.normal? + print ' unitary? '; puts matrix.unitary? +else + # Matrix is not square. These predicates would + # raise ExceptionForMatrix::ErrDimensionMismatch. + print 'Hermitian? false' + print ' normal? false' + print ' unitary? false' +end diff --git a/Task/Conjugate-transpose/Tcl/conjugate-transpose-1.tcl b/Task/Conjugate-transpose/Tcl/conjugate-transpose-1.tcl new file mode 100644 index 0000000000..529feb23a2 --- /dev/null +++ b/Task/Conjugate-transpose/Tcl/conjugate-transpose-1.tcl @@ -0,0 +1,57 @@ +package require struct::matrix +package require math::complexnumbers + +proc complexMatrix.equal {m1 m2 {epsilon 1e-14}} { + if {[$m1 rows] != [$m2 rows] || [$m1 columns] != [$m2 columns]} { + return 0 + } + # Compute the magnitude of the difference between two complex numbers + set ceq [list apply {{epsilon a b} { + expr {[mod [- $a $b]] < $epsilon} + } ::math::complexnumbers} $epsilon] + for {set i 0} {$i<[$m1 columns]} {incr i} { + for {set j 0} {$j<[$m1 rows]} {incr j} { + if {![{*}$ceq [$m1 get cell $i $j] [$m2 get cell $i $j]]} { + return 0 + } + } + } + return 1 +} + +proc complexMatrix.multiply {a b} { + if {[$a columns] != [$b rows]} { + error "incompatible sizes" + } + # Simplest to use a lambda in the complex NS + set cpm {{sum a b} { + + $sum [* $a $b] + } ::math::complexnumbers} + set c0 [math::complexnumbers::complex 0.0 0.0]; # Complex zero + set c [struct::matrix] + $c add columns [$b columns] + $c add rows [$a rows] + for {set i 0} {$i < [$a rows]} {incr i} { + for {set j 0} {$j < [$b columns]} {incr j} { + set sum $c0 + foreach rv [$a get row $i] cv [$b get column $j] { + set sum [apply $cpm $sum $rv $cv] + } + $c set cell $j $i $sum + } + } + return $c +} + +proc complexMatrix.conjugateTranspose {matrix} { + set mat [struct::matrix] + $mat = $matrix + $mat transpose + for {set c 0} {$c < [$mat columns]} {incr c} { + for {set r 0} {$r < [$mat rows]} {incr r} { + set val [$mat get cell $c $r] + $mat set cell $c $r [math::complexnumbers::conj $val] + } + } + return $mat +} diff --git a/Task/Conjugate-transpose/Tcl/conjugate-transpose-2.tcl b/Task/Conjugate-transpose/Tcl/conjugate-transpose-2.tcl new file mode 100644 index 0000000000..b395d5850b --- /dev/null +++ b/Task/Conjugate-transpose/Tcl/conjugate-transpose-2.tcl @@ -0,0 +1,52 @@ +proc isHermitian {matrix {epsilon 1e-14}} { + if {[$matrix rows] != [$matrix columns]} { + # Must be square! + return 0 + } + set cc [complexMatrix.conjugateTranspose $matrix] + set result [complexMatrix.equal $matrix $cc $epsilon] + $cc destroy + return $result +} + +proc isNormal {matrix {epsilon 1e-14}} { + if {[$matrix rows] != [$matrix columns]} { + # Must be square! + return 0 + } + set mh [complexMatrix.conjugateTranspose $matrix] + set mhm [complexMatrix.multiply $mh $matrix] + set mmh [complexMatrix.multiply $matrix $mh] + $mh destroy + set result [complexMatrix.equal $mhm $mmh $epsilon] + $mhm destroy + $mmh destroy + return $result +} + +proc isUnitary {matrix {epsilon 1e-14}} { + if {[$matrix rows] != [$matrix columns]} { + # Must be square! + return 0 + } + set mh [complexMatrix.conjugateTranspose $matrix] + set mhm [complexMatrix.multiply $mh $matrix] + set mmh [complexMatrix.multiply $matrix $mh] + $mh destroy + set result [complexMatrix.equal $mhm $mmh $epsilon] + $mhm destroy + if {$result} { + set id [struct::matrix] + $id = $matrix; # Just for its dimensions + for {set c 0} {$c < [$id columns]} {incr c} { + for {set r 0} {$r < [$id rows]} {incr r} { + $id set cell $c $r \ + [math::complexnumbers::complex [expr {$c==$r}] 0] + } + } + set result [complexMatrix.equal $mmh $id $epsilon] + $id destroy + } + $mmh destroy + return $result +} diff --git a/Task/Convert-decimal-number-to-rational/00DESCRIPTION b/Task/Convert-decimal-number-to-rational/00DESCRIPTION new file mode 100644 index 0000000000..6e67542421 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/00DESCRIPTION @@ -0,0 +1,16 @@ +The task is to write a program to transform a decimal number into a fraction in lowest terms. + +It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, [[wp:Repeating decimal|repeating decimals]] such as 1/3 = 0.333... + +Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: +* 67 / 74 = 0.9(054) = 0.9054054... +* 14 / 27 = 0.(518) = 0.518518... + +Acceptable output: + +* 0.9054054 → 4527027 / 5000000 +* 0.518518 → 259259 / 500000 + +Finite decimals are of course no problem: + +* 0.75 → 3 / 4 diff --git a/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-1.ada b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-1.ada new file mode 100644 index 0000000000..2cfcc503a0 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-1.ada @@ -0,0 +1,6 @@ +generic + type Real is digits <>; +procedure Real_To_Rational(R: Real; + Bound: Positive; + Nominator: out Integer; + Denominator: out Positive); diff --git a/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-2.ada b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-2.ada new file mode 100644 index 0000000000..44c00a178b --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-2.ada @@ -0,0 +1,29 @@ +procedure Real_To_Rational (R: Real; + Bound: Positive; + Nominator: out Integer; + Denominator: out Positive) is + Error: Real; + Best: Positive := 1; + Best_Error: Real := Real'Last; +begin + if R = 0.0 then + Nominator := 0; + Denominator := 1; + return; + elsif R < 0.0 then + Real_To_Rational(-R, Bound, Nominator, Denominator); + Nominator := - Nominator; + return; + else + for I in 1 .. Bound loop + Error := abs(Real(I) * R - Real'Rounding(Real(I) * R)); + if Error < Best_Error then + Best := I; + Best_Error := Error; + end if; + end loop; + end if; + Denominator := Best; + Nominator := Integer(Real'Rounding(Real(Denominator) * R)); + +end Real_To_Rational; diff --git a/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-3.ada b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-3.ada new file mode 100644 index 0000000000..e43b7236bf --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-3.ada @@ -0,0 +1,25 @@ +with Ada.Text_IO; With Real_To_Rational; + +procedure Convert_Decimal_To_Rational is + + type My_Real is new Long_Float; -- change this for another "Real" type + + package FIO is new Ada.Text_IO.Float_IO(My_Real); + procedure R2R is new Real_To_Rational(My_Real); + + Nom, Denom: Integer; + R: My_Real; + +begin + loop + Ada.Text_IO.New_Line; + FIO.Get(R); + FIO.Put(R, Fore => 2, Aft => 9, Exp => 0); + exit when R = 0.0; + for I in 0 .. 4 loop + R2R(R, 10**I, Nom, Denom); + Ada.Text_IO.Put(" " & Integer'Image(Nom) & + " /" & Integer'Image(Denom)); + end loop; + end loop; +end Convert_Decimal_To_Rational; diff --git a/Task/Convert-decimal-number-to-rational/AutoHotkey/convert-decimal-number-to-rational.ahk b/Task/Convert-decimal-number-to-rational/AutoHotkey/convert-decimal-number-to-rational.ahk new file mode 100644 index 0000000000..e811690deb --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/AutoHotkey/convert-decimal-number-to-rational.ahk @@ -0,0 +1,86 @@ + Array := [] + inputbox, string, Enter Number + stringsplit, string, string, . + if ( string1 = 0 ) + string1 = + loop, parse, string, . + if A_index = 2 + loop, parse, A_loopfield + Array[A_index] := A_loopfield, k := A_index + if (k = 1) + { + numerator := Array[1] + Denominator := 10 + goto label + } + Original1 := K + To_rn := floor(k/2) + M_M := k - To_rn + Original2 := k - To_rn + loop + { + loop, % To_rn + + { + Check1 .= Array[k] + Check2 .= Array[M_M] + k-- + m_M-- + } + if ( check1 = check2 ) + { + ;~ process beginsTO check;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + loop, % To_rn + nines .= 9 + loop, % k - TO_rn + Zeroes .= 0 + loop % k - TO_rn + Minus .= Array[A_index] + loop % k + Plus .= Array[A_index] + if ( minus = "" ) + minus := 0 + Numerator := Plus - minus + Denominator := Nines . Zeroes + ;;;;;;;;;;;;;HCF + goto, label + } + Check1 = + check2 = + k := Original1 + m_M := original2 + A_index + TO_rn-- + if ( to_rn = 0 ) + { + zeroes = + loop % original1 + zeroes .= 0 + Denominator := 1 . zeroes + numerator := string2 + goto, label + } + } + esc::Exitapp + label: + Index := 2 + loop + { + + if (mod(denominator, numerator) = 0 ) + HCF := numerator + if ( index = floor(numerator/2) ) + break + if ( mod(numerator, index) = 0 ) && ( mod(denominator, index) = 0 ) + { + HCF = %index% + index++ + } + else + index++ + } + if ( HCF = "" ) + Ans := numerator "/" Denominator + else + Ans := floor(numerator/HCF) "/" floor(Denominator/HCF) + MsgBox % String . " -> " . String1 . " " . Ans + reload diff --git a/Task/Convert-decimal-number-to-rational/Bracmat/convert-decimal-number-to-rational.bracmat b/Task/Convert-decimal-number-to-rational/Bracmat/convert-decimal-number-to-rational.bracmat new file mode 100644 index 0000000000..a7dbda9d60 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Bracmat/convert-decimal-number-to-rational.bracmat @@ -0,0 +1,72 @@ +( ( exact + = integerPart decimalPart z + . @(!arg:?integerPart "." ?decimalPart) + & !integerPart + + ( @( !decimalPart + : (? ((%@:~0) ?:?decimalPart)) [?z + ) + & !decimalPart*10^(-1*!z) + | 0 + ) + | !arg + ) +& ( approximation + = integerPart firstDecimals repeatingDecimals + , x y z z-y x-y numerator denominator + . @( !arg + : ?integerPart + "." + [?x + ?firstDecimals + ?repeatingDecimals + [?y + !repeatingDecimals + [?z + ) + & !z+-1*!y:?z-y + & !x+-1*!y:?x-y + & 10:?numerator:?denominator + & ( !z-y:0&0:?repeatingDecimals + | 9:?denominator + & whl + ' ( !z+-1:>!y:?z + & !numerator*10:?numerator + & !denominator*10+9:?denominator + ) + & @(!repeatingDecimals:? #?repeatingDecimals) + ) + & ( @(!firstDecimals:? #?firstDecimals) + | 0:?firstDecimals + ) + & !integerPart + + !firstDecimals*10^(!x-y+!z-y) + + !numerator*!denominator^-1*!repeatingDecimals*10^!x-y + ) +& "0.9054054054" + "0.5185185185" + "0.75" + "0.905405400" + "0.1428571428" + "35.000" + "35.001" + "0.00000000001" + "0.000001000001" + "0.9" + "0.99" + "0.909" + "0.9090" + "0.90909" + : ?decs +& whl + ' ( !decs:%?dec ?decs + & approximation$!dec:?approx + & out + $ ( !dec + "=" + (exact$!dec:?precise) + ( !approx:!precise& + | str$("(approx. " !approx ")") + ) + ) + ) +); diff --git a/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-1.c b/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-1.c new file mode 100644 index 0000000000..cb60045bec --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-1.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include + +/* f : number to convert. + * num, denom: returned parts of the rational. + * md: max denominator value. Note that machine floating point number + * has a finite resolution (10e-16 ish for 64 bit double), so specifying + * a "best match with minimal error" is often wrong, because one can + * always just retrieve the significand and return that divided by + * 2**52, which is in a sense accurate, but generally not very useful: + * 1.0/7.0 would be "2573485501354569/18014398509481984", for example. + */ +void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom) +{ + /* a: continued fraction coefficients. */ + int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 }; + int64_t x, d, n = 1; + int i, neg = 0; + + if (md <= 1) { *denom = 1; *num = (int64_t) f; return; } + + if (f < 0) { neg = 1; f = -f; } + + while (f != floor(f)) { n <<= 1; f *= 2; } + d = f; + + /* continued fraction and check denominator each step */ + for (i = 0; i < 64; i++) { + a = n ? d / n : 0; + if (i && !a) break; + + x = d; d = n; n = x % n; + + x = a; + if (k[1] * a + k[0] >= md) { + x = (md - k[0]) / k[1]; + if (x * 2 >= a || k[1] >= md) + i = 65; + else + break; + } + + h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; + k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; + } + *denom = k[1]; + *num = neg ? -h[1] : h[1]; +} + +int main() +{ + int i; + int64_t d, n; + double f; + + printf("f = %16.14f\n", f = 1.0/7); + for (i = 1; i <= 20000000; i *= 16) { + printf("denom <= %d: ", i); + rat_approx(f, i, &n, &d); + printf("%lld/%lld\n", n, d); + } + + printf("\nf = %16.14f\n", f = atan2(1,1) * 4); + for (i = 1; i <= 20000000; i *= 16) { + printf("denom <= %d: ", i); + rat_approx(f, i, &n, &d); + printf("%lld/%lld\n", n, d); + } + + return 0; +} diff --git a/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-2.c b/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-2.c new file mode 100644 index 0000000000..314b1bb54a --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/C/convert-decimal-number-to-rational-2.c @@ -0,0 +1,17 @@ +f = 0.14285714285714 +denom <= 1: 0/1 +denom <= 16: 1/7 +denom <= 256: 1/7 +denom <= 4096: 1/7 +denom <= 65536: 1/7 +denom <= 1048576: 1/7 +denom <= 16777216: 1/7 + +f = 3.14159265358979 +denom <= 1: 3/1 +denom <= 16: 22/7 +denom <= 256: 355/113 +denom <= 4096: 355/113 +denom <= 65536: 104348/33215 +denom <= 1048576: 3126535/995207 +denom <= 16777216: 47627751/15160384 diff --git a/Task/Convert-decimal-number-to-rational/D/convert-decimal-number-to-rational.d b/Task/Convert-decimal-number-to-rational/D/convert-decimal-number-to-rational.d new file mode 100644 index 0000000000..922d7642a7 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/D/convert-decimal-number-to-rational.d @@ -0,0 +1,40 @@ +import std.stdio, std.math, std.string, std.typecons; + +alias Fraction = Tuple!(int,"nominator", uint,"denominator"); + +Fraction real2Rational(in real r, in uint bound) /*pure*/ nothrow { + if (r == 0.0) { + return Fraction(0, 1); + } else if (r < 0.0) { + auto result = real2Rational(-r, bound); + result.nominator = -result.nominator; + return result; + } else { + uint best = 1; + real bestError = real.max; + + foreach (i; 1 .. bound + 1) { + // round is not pure. + immutable real error = abs(i * r - round(i * r)); + if (error < bestError) { + best = i; + bestError = error; + } + } + + return Fraction(cast(int)round(best * r), best); + } +} + +void main() { + immutable tests = [ 0.750000000, 0.518518000, 0.905405400, + 0.142857143, 3.141592654, 2.718281828, + -0.423310825, 31.415926536]; + + foreach (r; tests) { + writef("%8.9f ", r); + foreach (i; 0 .. 5) + writef(" %d/%d", real2Rational(r, 10 ^^ i).tupleof); + writeln(); + } +} diff --git a/Task/Convert-decimal-number-to-rational/Go/convert-decimal-number-to-rational.go b/Task/Convert-decimal-number-to-rational/Go/convert-decimal-number-to-rational.go new file mode 100644 index 0000000000..7cd1ee6425 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Go/convert-decimal-number-to-rational.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + for _, d := range []string{"0.9054054", "0.518518", "0.75"} { + if r, ok := new(big.Rat).SetString(d); ok { + fmt.Println(d, "=", r) + } else { + fmt.Println(d, "invalid decimal number") + } + } +} diff --git a/Task/Convert-decimal-number-to-rational/Haskell/convert-decimal-number-to-rational.hs b/Task/Convert-decimal-number-to-rational/Haskell/convert-decimal-number-to-rational.hs new file mode 100644 index 0000000000..760834788e --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Haskell/convert-decimal-number-to-rational.hs @@ -0,0 +1,6 @@ +Prelude> map (\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75] +[67 % 74,14 % 27,3 % 4] +Prelude> [0.9054054, 0.518518, 0.75] :: [Rational] +[4527027 % 5000000,259259 % 500000,3 % 4] +Prelude> map (fst . head . Numeric.readFloat) ["0.9054054", "0.518518", "0.75"] :: [Rational] +[4527027 % 5000000,259259 % 500000,3 % 4] diff --git a/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-1.j b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-1.j new file mode 100644 index 0000000000..be92007959 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-1.j @@ -0,0 +1,2 @@ + x: 0.9054054 0.518518 0.75 NB. find "exact" rational representation +127424481939351r140737488355328 866492568306r1671094481399 3r4 diff --git a/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-2.j b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-2.j new file mode 100644 index 0000000000..ac7ccf5528 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-2.j @@ -0,0 +1,12 @@ + x: 0.9 0.5 +9r10 1r2 + x: 0.9054 0.5185 +4527r5000 1037r2000 + x: 0.9054054 0.5185185 +127424481939351r140737488355328 1037037r2000000 + x: 0.9054054054 0.5185185185 +5358191125333r5918002138463 6073341499873r11712872893031 + x: 0.9054054054054 0.5185185185185 +67r74 14r27 + x: 0.9054054054054054 0.5185185185185185 +67r74 14r27 diff --git a/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-3.j b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-3.j new file mode 100644 index 0000000000..d25e3fd2fc --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-3.j @@ -0,0 +1,2 @@ + x:(!. 5e_11) 0.9054054054 0.5185185185 +67r74 14r27 diff --git a/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-4.j b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-4.j new file mode 100644 index 0000000000..5617f32f45 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/J/convert-decimal-number-to-rational-4.j @@ -0,0 +1,6 @@ + 0j10": x:inv x: 0.9054054 0.518518 0.75 NB. invertible (shown to 10 decimal places) +0.9054054000 0.5185180000 0.7500000000 + 0j10": x:inv 67r74 42r81 3r4 NB. decimal representation (shown to 10 decimal places) +0.9054054054 0.5185185185 0.7500000000 + x: x:inv 67r74 42r81 3r4 NB. invertible +67r74 14r27 3r4 diff --git a/Task/Convert-decimal-number-to-rational/Julia/convert-decimal-number-to-rational.julia b/Task/Convert-decimal-number-to-rational/Julia/convert-decimal-number-to-rational.julia new file mode 100644 index 0000000000..8e15aed0e9 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Julia/convert-decimal-number-to-rational.julia @@ -0,0 +1,3 @@ +rational(0.9054054) +rational(0.518518) +rational(0.75) diff --git a/Task/Convert-decimal-number-to-rational/Liberty-BASIC/convert-decimal-number-to-rational.liberty b/Task/Convert-decimal-number-to-rational/Liberty-BASIC/convert-decimal-number-to-rational.liberty new file mode 100644 index 0000000000..cfad0ea5d2 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Liberty-BASIC/convert-decimal-number-to-rational.liberty @@ -0,0 +1,75 @@ +' Uses convention that one repeating sequence implies infinitely repeating sequence.. +' Non-recurring fractions are limited to nd number of digits in nuerator & denominator + +nd =3 ' suggest 3. 4 is slow. >4 is ....... +do + read x$ + data "0.5", "0.1", "0.333", "1 /3", "0.33", "0.14159265", "2^-0.5", "0.1 +0.9*rnd(1)" + data "0.142857142857", "int( 1000*rnd(1))/int( 1000*rnd(1))","end" ' always between 0 and 0.999999... + if x$ ="end" then exit do + print x$; " is "; + type$ =check$( x$) + print type$; + + if type$ ="recurring" then + x =val( mid$( x$, 3, ( len( x$) -2) /2)) + rep =( len( x$) -2) /2 + num =x + den =10^rep -1 + gcd =gcd( num, den) + print + print " Calculating exact fraction for ", recurring$( x); " recurring & found"; + print num /gcd; " /"; den /gcd + print + else ' non-recurring. Check numerators & denominators <1000 + x =eval( x$) + print + print " Looking for fractions that are close to "; using( "#.############", x); " & found "; + eps =10^nd + for n = 1 to nd + for i =1 to 10^n -1 + for j =i to 10^n -1 + fr =i /j + if abs( x -fr) =14 +end function + +function gcd( a, b) ' thanks Uncle Ben.. + while b <>0 + t =b + b =a mod b + a =t + wend + gcd =a +end function + +function check$( i$) + check$ ="non-recurring" + length =len( i$) -2 ' allow for the '0.'. + if length /2 =int( length /2) then if mid$( i$, 3, length /2) =mid$( i$, 3 +length /2, length /2) then check$ ="recurring" +end function diff --git a/Task/Convert-decimal-number-to-rational/MATLAB/convert-decimal-number-to-rational.m b/Task/Convert-decimal-number-to-rational/MATLAB/convert-decimal-number-to-rational.m new file mode 100644 index 0000000000..06088f0615 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/MATLAB/convert-decimal-number-to-rational.m @@ -0,0 +1,3 @@ + [a,b]=rat(.75) + [a,b]=rat(.518518) + [a,b]=rat(.9054054) diff --git a/Task/Convert-decimal-number-to-rational/Maple/convert-decimal-number-to-rational.maple b/Task/Convert-decimal-number-to-rational/Maple/convert-decimal-number-to-rational.maple new file mode 100644 index 0000000000..5026f1ad46 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Maple/convert-decimal-number-to-rational.maple @@ -0,0 +1,4 @@ +> map( convert, [ 0.9054054, 0.518518, 0.75 ], 'rational', 'exact' ); + 4527027 259259 + [-------, ------, 3/4] + 5000000 500000 diff --git a/Task/Convert-decimal-number-to-rational/Mathematica/convert-decimal-number-to-rational.math b/Task/Convert-decimal-number-to-rational/Mathematica/convert-decimal-number-to-rational.math new file mode 100644 index 0000000000..6bc4d10fea --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Mathematica/convert-decimal-number-to-rational.math @@ -0,0 +1,2 @@ +Map[Rationalize[#,0]&,{0.9054054,0.518518, 0.75} ] +-> {4527027/5000000,259259/500000,3/4} diff --git a/Task/Convert-decimal-number-to-rational/NetRexx/convert-decimal-number-to-rational.netrexx b/Task/Convert-decimal-number-to-rational/NetRexx/convert-decimal-number-to-rational.netrexx new file mode 100644 index 0000000000..dcbfa4de6d --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/NetRexx/convert-decimal-number-to-rational.netrexx @@ -0,0 +1,61 @@ +/*NetRexx program to convert decimal numbers to fractions ************* +* 16.08.2012 Walter Pachl derived from Rexx Version 2 +**********************************************************************/ +options replace format comments java crossref savelog symbols + Numeric Digits 10 /* use "only" 10 digs of precision */ + ratt('0.9054054054','67/74') + ratt('0.5185185185','14/27') + ratt('0.75' ,'3/4') + ratt('0.905405400',' 693627417/766095958') + ratt('0.9054054054','67/74') + ratt('0.1428571428','1/7') + ratt('35.000','35') + ratt('35.001','35001/1000') + ratt('0.00000000001','?') + ratt('0.000001000001','1/999999') + +ratt(0.9054054054,'1/3') + + +method ratt(d = Rexx,fs = Rexx) public static + fract=rat(d) + Say ' 'd '->' fract + Parse fract no '/' de + If de='' Then x=no + Else x=no/de + If x<>d Then + Say '> '||x 'is different' + +method rat(in, high='') public static +/********************************************************************** +* rat(number<,high) returns a fraction or an integer that is equal to +* or approximately equal to number. +* Nominator and denominator must not have more than high digits +* 16.08.2012 Walter Pachl derived from Rexx Version 2 +**********************************************************************/ + if high=='' then + high=10**(digits - 1) /* maximum nominator/denominator */ + x=in /* working copy */ + nom=0 /* start values nominator */ + den=1 /* denominator */ + tnom=1 /* temp nominator */ + tden=0 /* temp denominator */ + loop While tnom<=high & tden<=high /* nominator... not too large */ + n=x.trunc() /* take integer part of x */ + z=tnom; /* save temp nominator */ + tnom=n*tnom+nom; /* compute new temp nominator */ + nom=z /* assign nominator */ + z=tden; /* save temp denominator */ + tden=n*tden+den /* compute new temp denominato*/ + den=z /* assign denominator */ + if n=x | tnom/tden=in then do + if tnom>high | tden>high then /* temp value(s) too large */ + Leave /* don't use them */ + nom=tnom /* otherwise take them as */ + den=tden /* final values */ + leave /* and end the loop */ + end + x=1/(x-n) /* compute x for next round */ + end + If den=1 Then Return nom /* an integer */ + Else Return nom'/'den /* otherwise a fraction */ diff --git a/Task/Convert-decimal-number-to-rational/PARI-GP/convert-decimal-number-to-rational.pari b/Task/Convert-decimal-number-to-rational/PARI-GP/convert-decimal-number-to-rational.pari new file mode 100644 index 0000000000..edc912200d --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/PARI-GP/convert-decimal-number-to-rational.pari @@ -0,0 +1,5 @@ +convert(x)={ + my(n=0); + while(x-floor(x*10^n)/10^n!=0.,n++); + floor(x*10^n)/10^n +}; diff --git a/Task/Convert-decimal-number-to-rational/PL-I/convert-decimal-number-to-rational.pli b/Task/Convert-decimal-number-to-rational/PL-I/convert-decimal-number-to-rational.pli new file mode 100644 index 0000000000..1def5eaaba --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/PL-I/convert-decimal-number-to-rational.pli @@ -0,0 +1,54 @@ +(size, fofl): +Convert_Decimal_To_Rational: procedure options (main); /* 14 January 2014, from Ada */ + +Real_To_Rational: procedure (R, Bound, Numerator, Denominator) recursive + options (reorder); + declare R float (18), Bound float, + (Numerator, Denominator) fixed binary (31); + declare Error float; + declare Best fixed binary initial (1); + declare Best_Error float initial (huge(error)); + declare I fixed binary (31); + + if R = 0 then + do; + Numerator = 0; + Denominator = 1; + return; + end; + else if R < 0 then + do; + call Real_To_Rational(-R, Bound, Numerator, Denominator); + Numerator = -Numerator; + return; + end; + else + do I = 1 to Bound; + Error = abs(I * R - trunc(I * R + sign(R)*0.5)); + if Error < Best_Error then + do; + Best = I; + Best_Error = Error; + end; + end; + + Denominator = Best; + Numerator = Denominator * R + sign(R) * 0.5; + +end Real_To_Rational; + + + declare (Num, Denom) fixed binary (31); + declare R float (18); + declare I fixed BINARY; + + do R = 0.75, 0.25, 0.3333333, 0.518518000, 0.905405400, + 0.142857143, 3.141592654, 2.718281828, -0.423310825, + 31.415926536, 0; + put skip edit(R) (f(13,9)); + do I = 0 to 4; + call Real_to_Rational(R, 10**I, Num, Denom); + put edit(' ' || trim(Num) || ' / ' || trim(Denom)) (a); + end; + end; +end Convert_Decimal_To_Rational; diff --git a/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-1.pl6 b/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-1.pl6 new file mode 100644 index 0000000000..a50fa00310 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-1.pl6 @@ -0,0 +1 @@ +say .nude.join('/') for 0.9054054, 0.518518, 0.75; diff --git a/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-2.pl6 b/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-2.pl6 new file mode 100644 index 0000000000..00c60cc2fe --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Perl-6/convert-decimal-number-to-rational-2.pl6 @@ -0,0 +1,18 @@ +sub decimal_to_fraction ( Str $n, Int $rep_digits = 0 ) returns Str { + my ( $int, $dec ) = ( $n ~~ /^ (\d+) \. (\d+) $/ )».Str or die; + + my ( $numer, $denom ) = ( $dec, 10 ** $dec.bytes ); + if $rep_digits { + my $to_move = $dec.bytes - $rep_digits; + $numer -= $dec.substr(0, $to_move); + $denom -= 10 ** $to_move; + } + + my $rat = Rat.new( $numer.Int, $denom.Int ).perl; + return $int ?? "$int $rat" !! $rat; +} + +my @a = ['0.9054', 3], ['0.518', 3], ['0.75', 0], (^4).map({['12.34567', $_]}); +for @a -> [ $n, $d ] { + say "$n with $d repeating digits = ", decimal_to_fraction( $n, $d ); +} diff --git a/Task/Convert-decimal-number-to-rational/Perl/convert-decimal-number-to-rational.pl b/Task/Convert-decimal-number-to-rational/Perl/convert-decimal-number-to-rational.pl new file mode 100644 index 0000000000..4fa13f4538 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Perl/convert-decimal-number-to-rational.pl @@ -0,0 +1,129 @@ +sub gcd { + my ($m, $n) = @_; + ($m, $n) = ($n, $m % $n) while $n; + return $m +} + +sub rat_machine { + my $n = shift; + my $denom = 1; + while ($n != int $n) { + # assuming the machine format is base 2, and multiplying + # by 2 doesn't change the mantissa + $n *= 2; + + # multiply denom by 2, ignoring (very) possible overflow + $denom <<= 1; + } + if ($n) { + my $g = gcd($n, $denom); + $n /= $g; + $denom /= $g; + } + return $n, $denom; +} + +# helper, make continued fraction back into normal fraction +sub get_denom { + my ($num, $denom) = (1, pop @_); + for (reverse @_) { + ($num, $denom) = ($denom, $_ * $denom + $num); + } + wantarray ? ($num, $denom) : $denom +} + +sub best_approx { + my ($n, $limit) = @_; + my ($denom, $neg); + if ($n < 0) { + $neg = 1; + $n = -$n; + } + + my $int = int($n); + my ($num, $denom, @coef) = (1, $n - $int); + + # continued fraction, sort of + while (1) { + # make sure it terminates + last if $limit * $denom < 1; + my $i = int($num / $denom); + + # not the right way to get limit, but it works + push @coef, $i; + + if (get_denom(@coef) > $limit) { + pop @coef; + last; + } + + # we lose precision here, but c'est la vie + ($num, $denom) = ($denom, $num - $i * $denom); + } + + ($num, $denom) = get_denom @coef; + $num += $denom * $int; + + return $neg ? -$num : $num, $denom; +} + +sub rat_string { + my $n = shift; + my $denom = 1; + my $neg; + + # trival xyz.0000 ... case + $n =~ s/\.0+$//; + return $n, 1 unless $n =~ /\./; + + if ($n =~ /^-/) { + $neg = 1; + $n =~ s/^-//; + } + + # shift decimal point to the right till it's gone + $denom *= 10 while $n =~ s/\.(\d)/$1\./; + $n =~ s/\.$//; + + # removing leading zeros lest it looks like octal + $n =~ s/^0*//; + if ($n) { + my $g = gcd($n, $denom); + $n /= $g; + $denom /= $g; + } + return $neg ? -$n : $n, $denom; +} + +my $limit = 1e8; +my $x = 3/8; +print "3/8 = $x:\n"; +printf "machine: %d/%d\n", rat_machine $x; +printf "string: %d/%d\n", rat_string $x; +printf "approx below $limit: %d/%d\n", best_approx $x, $limit; + +$x = 137/4291; +print "\n137/4291 = $x:\n"; +printf "machine: %d/%d\n", rat_machine $x; +printf "string: %d/%d\n", rat_string $x; +printf "approx below $limit: %d/%d\n", best_approx $x, $limit; + +$x = sqrt(1/2); +print "\n1/sqrt(2) = $x\n"; +printf "machine: %d/%d\n", rat_machine $x; +printf "string: %d/%d\n", rat_string $x; +printf "approx below 10: %d/%d\n", best_approx $x, 10; +printf "approx below 100: %d/%d\n", best_approx $x, 100; +printf "approx below 1000: %d/%d\n", best_approx $x, 1000; +printf "approx below 10000: %d/%d\n", best_approx $x, 10000; +printf "approx below 100000: %d/%d\n", best_approx $x, 100000; +printf "approx below $limit: %d/%d\n", best_approx $x, $limit; + +$x = -4 * atan2(1,1); +print "\n-Pi = $x\n"; +printf "machine: %d/%d\n", rat_machine $x; +printf "string: %d/%d\n", rat_string $x; + +for (map { 10 ** $_ } 1 .. 10) { + printf "approx below %g: %d / %d\n", $_, best_approx($x, $_) +} diff --git a/Task/Convert-decimal-number-to-rational/Python/convert-decimal-number-to-rational.py b/Task/Convert-decimal-number-to-rational/Python/convert-decimal-number-to-rational.py new file mode 100644 index 0000000000..8f81ff96b1 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Python/convert-decimal-number-to-rational.py @@ -0,0 +1,12 @@ +>>> from fractions import Fraction +>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100)) + +0.9054054 67/74 +0.518518 14/27 +0.75 3/4 +>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d)) + +0.9054054 4527027/5000000 +0.518518 259259/500000 +0.75 3/4 +>>> diff --git a/Task/Convert-decimal-number-to-rational/README b/Task/Convert-decimal-number-to-rational/README new file mode 100644 index 0000000000..db5975b298 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Convert_decimal_number_to_rational diff --git a/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-1.rexx b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-1.rexx new file mode 100644 index 0000000000..af8d8c7b19 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-1.rexx @@ -0,0 +1,27 @@ +/*REXX program converts a fraction [n/m] to it's simplest (lowest) terms*/ +numeric digits 10 /*use "only" 10 digs of precision*/ +parse arg orig 1 n.1 '/' n.2; if n.2='' then n.2=1 +if n.1='' then call er 'no argument specified.' + do i=1 for 2 /*validate both args: n.1 n.2 */ + if \datatype(n.i,'N') then call er "argument isn't numeric:" n.i + end /*i*/ +if n.2=0 then call er "divisor can't be zero." /*whoa, dividing by 0*/ +say 'old =' space(orig) /*display original. */ +say 'new =' rat(n.1/n.2) /*display the result.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ER subroutine───────────────────────*/ +er: say; say '***error!***'; say; say arg(1); say; exit 13 +/*──────────────────────────────────RAT subroutine──────────────────────*/ +rat: procedure; parse arg x 1 _x,y; if y=='' then y=10**(digits()-1) +b=0; g=0; a=1; h=1 /*Y is the tolerance.*/ + do while a<=y & g<=y; n=trunc(_x) + _=a; a=n*a+b; b=_ + _=g; g=n*g+h; h=_ + if n=_x | a/g=x then do + if a>y | g>y then iterate + b=a; h=g; leave + end + _x= 1 / (_x-n) + end /*while a≤y & g≤y*/ +if h==1 then return b /*don't show number divided by 1 */ + return b'/'h /*show a proper|improper fraction*/ diff --git a/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-2.rexx b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-2.rexx new file mode 100644 index 0000000000..6a8e1859f8 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-2.rexx @@ -0,0 +1,69 @@ +/*REXX program to convert decimal numbers to fractions **************** +* 15.08.2012 Walter Pachl derived from above for readability +* It took me time to understand :-) I need descriptive variable names +* Output shows where the fraction only approximates the number +* due to the limit (high) imposed on nominator and denominator +**********************************************************************/ + Numeric Digits 10 /* use "only" 10 digs of precision */ + Call test '0.9054054054','67/74' + Call test '0.5185185185','14/27' + Call test '0.75' ,'3/4' + Call test '0.905405400',' 693627417/766095958' + Call test '0.9054054054','67/74' + Call test '0.1428571428','1/7' + Call test '35.000','35' + Call test '35.001','35001/1000' + Call test '0.00000000001','?' + Call test '0.000001000001','1/999999' + Exit + +test: +/********************************************************************** +* Test driver for rat +**********************************************************************/ + Parse Arg d,fs /* number and expected fraction */ + fh=rat(d) /* convert number to fracrion */ + Call o ' 'd fh + If fh<>fs Then Call o ' not='fs + interpret 'x='fh /* compute value of fraction */ + If x<>d Then /* not exactly equal to number */ + Call o '> '||x 'is different' + Call o ' ' + Return + +o: Say arg(1); Return + +rat: procedure +/********************************************************************** +* rat(number<,high) returns a fraction or an integer that is equal to +* or approximately equal to number. +* Nominator and denominator must not have more than high digits +* 15.08.2012 Walter Pachl derived from Version 1 +**********************************************************************/ +parse arg in,high + x=in /* working copy */ + if high=='' then + high=10**(digits()-1) /* maximum nominator/denominator */ + nom=0 /* start values nominator */ + den=1 /* denominator */ + tnom=1 /* temp nominator */ + tden=0 /* temp denominator */ + do While tnom<=high & tden<=high /* nominator... not too large */ + n=trunc(x) /* take integer part of x */ + z=tnom; /* save temp nominator */ + tnom=n*tnom+nom; /* compute new temp nominator */ + nom=z /* assign nominator */ + z=tden; /* save temp denominator */ + tden=n*tden+den /* compute new temp denominato*/ + den=z /* assign denominator */ + if n=x | tnom/tden=in then do + if tnom>high | tden>high then /* temp value(s) too large */ + Leave /* don't use them */ + nom=tnom /* otherwise take them as */ + den=tden /* final values */ + leave /* and end the loop */ + end + x=1/(x-n) /* compute x for next round */ + end + if den=1 then return nom /* denominator 1: integer */ + return nom'/'den /* otherwise a fraction */ diff --git a/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx new file mode 100644 index 0000000000..d68e447edc --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx @@ -0,0 +1,62 @@ +/* REXX --------------------------------------------------------------- +* 13.02.2014 Walter Pachl +* specify the number as xxx.yyy(pqr) pqr is the period +* for the number xxx.yyypqrpqrpqrpqrpqr... +*--------------------------------------------------------------------*/ +Numeric Digits 100 +Call test '5.55555','111111/20000' +Call test '3','3' +Call test '0.03','3/100' +Call test '0.9(054)','67/74' +Call test '0.(3)','1/3' +Call test '5.28(571428)','37/7' +Call test '5.28(571428)','38/7 (demonstrate error case)' +Call test '0.(518)','14/27' +Call test '0.75' ,'3/4' +Call test '0.(142857)','1/7' +Call test '0.1(428571)','1/7' +Call test '35.000','35' +Call test '35.001','35001/1000' +Call test '0.00000000001','1/100000000000' +Call test '0.000001000001','1000001/1000000000000' +Exit +test: + Parse Arg z, soll + zin=z + If pos('(',z)=0 Then Do + Parse Var z i '.' f + z=i||f + n=10**length(f) + End + Else Do + lp=pos('(',z)-3 + rp=pos(')',z)-4 + x=space(translate(z,' ','()'),0) + z1=x*10**lp + Parse Var z1 z1 '.' + z2=x*10**rp + z=z2-z1 + n=10**rp-10**lp + End + dd=gcd(z,n) + zz=z/dd + nn=n/dd + If nn=1 Then + fract=zz + Else + fract=zz'/'nn + If fract==soll Then + tag='ok' + Else + tag='should be' soll + say zin '=' fract tag + -- Say left(zz/nn,60) + Return + +GCD: procedure +/********************************************************************** +* Recursive procedure +**********************************************************************/ +Parse Arg a,b +if b = 0 then return abs(a) +return GCD(b,a//b) diff --git a/Task/Convert-decimal-number-to-rational/Racket/convert-decimal-number-to-rational.rkt b/Task/Convert-decimal-number-to-rational/Racket/convert-decimal-number-to-rational.rkt new file mode 100644 index 0000000000..312b2d02f3 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Racket/convert-decimal-number-to-rational.rkt @@ -0,0 +1,7 @@ +#lang racket + +(inexact->exact 0.75) ; -> 3/4 +(exact->inexact 3/4) ; -> 0.75 + +(exact->inexact 67/74) ; -> 0.9054054054054054 +(inexact->exact 0.9054054054054054) ;-> 8155166892806033/9007199254740992 diff --git a/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-1.rb b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-1.rb new file mode 100644 index 0000000000..3f9c2f24e8 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-1.rb @@ -0,0 +1,5 @@ +> '0.9054054 0.518518 0.75'.split.each { |d| puts "%s %s" % [d, Rational(d)] } +0.9054054 4527027/5000000 +0.518518 259259/500000 +0.75 3/4 +=> ["0.9054054", "0.518518", "0.75"] diff --git a/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb new file mode 100644 index 0000000000..3c2fdb7f55 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb @@ -0,0 +1,5 @@ +> [0.9054054, 0.518518, 0.75].each { |d| puts "%s %s" % [d, Rational(d).rationalize(0.0001)] } +0.9054054 67/74 +0.518518 14/27 +0.75 3/4 +=> [0.9054054, 0.518518, 0.75] diff --git a/Task/Convert-decimal-number-to-rational/Seed7/convert-decimal-number-to-rational.seed7 b/Task/Convert-decimal-number-to-rational/Seed7/convert-decimal-number-to-rational.seed7 new file mode 100644 index 0000000000..67c43050e4 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Seed7/convert-decimal-number-to-rational.seed7 @@ -0,0 +1,19 @@ +$ include "seed7_05.s7i"; + include "bigrat.s7i"; + +const proc: main is func + begin + writeln(bigRational parse "0.9(054)"); + writeln(bigRational parse "0.(518)"); + writeln(bigRational parse "0.75"); + writeln(bigRational parse "3.(142857)"); + writeln(bigRational parse "0.(8867924528301)"); + writeln(bigRational parse "0.(846153)"); + writeln(bigRational parse "0.9054054"); + writeln(bigRational parse "0.518518"); + writeln(bigRational parse "0.14285714285714"); + writeln(bigRational parse "3.14159265358979"); + writeln(bigRational parse "2.718281828"); + writeln(bigRational parse "31.415926536"); + writeln(bigRational parse "0.000000000"); + end func; diff --git a/Task/Convert-decimal-number-to-rational/Tcl/convert-decimal-number-to-rational.tcl b/Task/Convert-decimal-number-to-rational/Tcl/convert-decimal-number-to-rational.tcl new file mode 100644 index 0000000000..234327b135 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Tcl/convert-decimal-number-to-rational.tcl @@ -0,0 +1,22 @@ +#!/usr/bin/env tclsh + + proc dbl2frac {dbl {eps 0.000001}} { + for {set den 1} {$den<1024} {incr den} { + set num [expr {round($dbl*$den)}] + if {abs(double($num)/$den - $dbl) < $eps} break + } + list $num $den + } +#-------------------- That's all... the rest is the test suite +if {[file tail $argv0] eq [file tail [info script]]} { + foreach {test -> expected} { + {dbl2frac 0.518518} -> {42 81} + {dbl2frac 0.75} -> {3 4} + {dbl2frac 0.9054054} -> {67 74} + } { + catch $test res + if {$res ne $expected} { + puts "$test -> $res, expected $expected" + } + } +} diff --git a/Task/Currying/00DESCRIPTION b/Task/Currying/00DESCRIPTION new file mode 100644 index 0000000000..ce722c3741 --- /dev/null +++ b/Task/Currying/00DESCRIPTION @@ -0,0 +1,5 @@ +{{Wikipedia|Currying}} +Create a simple demonstrative example of [[wp:Currying|Currying]] in the specific language. + +Add any historic details as to how the feature made its way into the language. + diff --git a/Task/Currying/ALGOL-68/currying.alg b/Task/Currying/ALGOL-68/currying.alg new file mode 100644 index 0000000000..42dd4ca7c6 --- /dev/null +++ b/Task/Currying/ALGOL-68/currying.alg @@ -0,0 +1,10 @@ +# Raising a function to a power # + +MODE FUN = PROC (REAL) REAL; +PROC pow = (FUN f, INT n, REAL x) REAL: f(x) ** n; +OP ** = (FUN f, INT n) FUN: pow (f, n, ); + +# Example: sin (3 x) = 3 sin (x) - 4 sin^3 (x) (follows from DeMoivre's theorem) # + +REAL x = read real; +print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x))) diff --git a/Task/Currying/C-sharp/currying.cs b/Task/Currying/C-sharp/currying.cs new file mode 100644 index 0000000000..050adf46b9 --- /dev/null +++ b/Task/Currying/C-sharp/currying.cs @@ -0,0 +1,9 @@ +public delegate int Plus(int y); +public delegate Plus CurriedPlus(int x); +public static CurriedPlus plus = + delegate(int x) {return delegate(int y) {return x + y;};}; +static void Main() +{ + int sum = plus(3)(4); // sum = 7 + int sum2= plus(2)(plus(3)(4)) // sum2 = 9 +} diff --git a/Task/Currying/Common-Lisp/currying-1.lisp b/Task/Currying/Common-Lisp/currying-1.lisp new file mode 100644 index 0000000000..eba9083ee7 --- /dev/null +++ b/Task/Currying/Common-Lisp/currying-1.lisp @@ -0,0 +1,3 @@ +(defun curry (function &rest args-1) + (lambda (&rest args-2) + (apply function (append args-1 args-2)))) diff --git a/Task/Currying/Common-Lisp/currying-2.lisp b/Task/Currying/Common-Lisp/currying-2.lisp new file mode 100644 index 0000000000..cb4c5ec3c1 --- /dev/null +++ b/Task/Currying/Common-Lisp/currying-2.lisp @@ -0,0 +1,3 @@ +(funcall (curry #'+ 10) 10) + +20 diff --git a/Task/Currying/D/currying.d b/Task/Currying/D/currying.d new file mode 100644 index 0000000000..04563b47b6 --- /dev/null +++ b/Task/Currying/D/currying.d @@ -0,0 +1,11 @@ +void main() { + import std.stdio, std.functional; + + int add(int a, int b) { + return a + b; + } + + alias add2 = curry!(add, 2); + writeln("Add 2 to 3: ", add(2, 3)); + writeln("Add 2 to 3 (curried): ", add2(3)); +} diff --git a/Task/Currying/Erlang/currying.erl b/Task/Currying/Erlang/currying.erl new file mode 100644 index 0000000000..2a00f336de --- /dev/null +++ b/Task/Currying/Erlang/currying.erl @@ -0,0 +1,62 @@ +-module(currying). + +-compile(export_all). + +% Function that curry the first or the second argument of a given function of arity 2 + +curry_first(F,X) -> + fun(Y) -> F(X,Y) end. + +curry_second(F,Y) -> + fun(X) -> F(X,Y) end. + +% Usual curry + +curry(Fun,Arg) -> + case erlang:fun_info(Fun,arity) of + {arity,0} -> + erlang:error(badarg); + {arity,ArityFun} -> + create_ano_fun(ArityFun,Fun,Arg); + _ -> + erlang:error(badarg) + end. + +create_ano_fun(Arity,Fun,Arg) -> + Pars = + [{var,1,list_to_atom(lists:flatten(io_lib:format("X~p", [N])))} + || N <- lists:seq(2,Arity)], + Ano = + {'fun',1, + {clauses,[{clause,1,Pars,[], + [{call,1,{var,1,'Fun'},[{var,1,'Arg'}] ++ Pars}]}]}}, + {_,Result,_} = erl_eval:expr(Ano, [{'Arg',Arg},{'Fun',Fun}]), + Result. + +% Generalization of the currying + +curry_gen(Fun,GivenArgs,PosGivenArgs,PosParArgs) -> + Pos = PosGivenArgs ++ PosParArgs, + case erlang:fun_info(Fun,arity) of + {arity,ArityFun} -> + case ((length(GivenArgs) + length(PosParArgs)) == ArityFun) and + (length(GivenArgs) == length(PosGivenArgs)) and + (length(Pos) == sets:size(sets:from_list(Pos))) of + true -> + fun(ParArgs) -> + case length(ParArgs) == length(PosParArgs) of + true -> + Given = lists:zip(PosGivenArgs,GivenArgs), + Pars = lists:zip(PosParArgs,ParArgs), + {_,Args} = lists:unzip(lists:sort(Given ++ Pars)), + erlang:apply(Fun,Args); + false -> + erlang:error(badarg) + end + end; + false -> + erlang:error(badarg) + end; + _ -> + erlang:error(badarg) + end. diff --git a/Task/Currying/Forth/currying.fth b/Task/Currying/Forth/currying.fth new file mode 100644 index 0000000000..27fdc9fde4 --- /dev/null +++ b/Task/Currying/Forth/currying.fth @@ -0,0 +1,6 @@ +: curry ( x xt1 -- xt2 ) + swap 2>r :noname r> postpone literal r> compile, postpone ; ; + +5 ' + curry constant +5 +5 +5 execute . +7 +5 execute . diff --git a/Task/Currying/Go/currying.go b/Task/Currying/Go/currying.go new file mode 100644 index 0000000000..4bec6e2186 --- /dev/null +++ b/Task/Currying/Go/currying.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "math" +) + +func PowN(b float64) func(float64) float64 { + return func(e float64) float64 { return math.Pow(b, e) } +} + +func PowE(e float64) func(float64) float64 { + return func(b float64) float64 { return math.Pow(b, e) } +} + +type Foo int + +func (f Foo) Method(b int) int { + return int(f) + b +} + +func main() { + pow2 := PowN(2) + cube := PowE(3) + + fmt.Println("2^8 =", pow2(8)) + fmt.Println("4³ =", cube(4)) + + var a Foo = 2 + fn1 := a.Method // A "method value", like currying 'a' + fn2 := Foo.Method // A "method expression", like uncurrying + + fmt.Println("2 + 2 =", a.Method(2)) // regular method call + fmt.Println("2 + 3 =", fn1(3)) + fmt.Println("2 + 4 =", fn2(a, 4)) + fmt.Println("3 + 5 =", fn2(Foo(3), 5)) +} diff --git a/Task/Currying/Groovy/currying-1.groovy b/Task/Currying/Groovy/currying-1.groovy new file mode 100644 index 0000000000..a56c87f5da --- /dev/null +++ b/Task/Currying/Groovy/currying-1.groovy @@ -0,0 +1,7 @@ +def divide = { Number x, Number y -> + x / y +} + +def partsOf120 = divide.curry(120) + +println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}" diff --git a/Task/Currying/Groovy/currying-2.groovy b/Task/Currying/Groovy/currying-2.groovy new file mode 100644 index 0000000000..c781d9d3c6 --- /dev/null +++ b/Task/Currying/Groovy/currying-2.groovy @@ -0,0 +1,5 @@ +def half = divide.rcurry(2) +def third = divide.rcurry(3) +def quarter = divide.rcurry(4) + +println "30: half: ${half(30)}; third: ${third(30)}, quarter: ${quarter(30)}" diff --git a/Task/Currying/Haskell/currying-1.hs b/Task/Currying/Haskell/currying-1.hs new file mode 100644 index 0000000000..048b8b5f89 --- /dev/null +++ b/Task/Currying/Haskell/currying-1.hs @@ -0,0 +1 @@ +\ -> diff --git a/Task/Currying/Haskell/currying-2.hs b/Task/Currying/Haskell/currying-2.hs new file mode 100644 index 0000000000..57ddad2aec --- /dev/null +++ b/Task/Currying/Haskell/currying-2.hs @@ -0,0 +1 @@ +\ diff --git a/Task/Currying/Haskell/currying-3.hs b/Task/Currying/Haskell/currying-3.hs new file mode 100644 index 0000000000..e4400a5afb --- /dev/null +++ b/Task/Currying/Haskell/currying-3.hs @@ -0,0 +1 @@ +-> diff --git a/Task/Currying/Haskell/currying-4.hs b/Task/Currying/Haskell/currying-4.hs new file mode 100644 index 0000000000..926ed6da4c --- /dev/null +++ b/Task/Currying/Haskell/currying-4.hs @@ -0,0 +1 @@ +\x y -> x + y diff --git a/Task/Currying/Haskell/currying-5.hs b/Task/Currying/Haskell/currying-5.hs new file mode 100644 index 0000000000..29d7e5cd74 --- /dev/null +++ b/Task/Currying/Haskell/currying-5.hs @@ -0,0 +1 @@ +\x -> \y -> x + y diff --git a/Task/Currying/Haskell/currying-6.hs b/Task/Currying/Haskell/currying-6.hs new file mode 100644 index 0000000000..08fc2171f1 --- /dev/null +++ b/Task/Currying/Haskell/currying-6.hs @@ -0,0 +1,13 @@ +procedure main(A) + add2 := addN(2) + write("add2(7) = ",add2(7)) + write("add2(1) = ",add2(1)) +end + +procedure addN(n) + return makeProc{ repeat { (x := (x@&source)[1], x +:= n) } } +end + +procedure makeProc(A) + return (@A[1], A[1]) +end diff --git a/Task/Currying/Io/currying.io b/Task/Currying/Io/currying.io new file mode 100644 index 0000000000..e36f98ca20 --- /dev/null +++ b/Task/Currying/Io/currying.io @@ -0,0 +1,12 @@ +curry := method(fn, + a := call evalArgs slice(1) + block( + b := a clone appendSeq(call evalArgs) + performWithArgList("fn", b) + ) +) + +// example: +increment := curry( method(a,b,a+b), 1 ) +increment call(5) +// result => 6 diff --git a/Task/Currying/J/currying.j b/Task/Currying/J/currying.j new file mode 100644 index 0000000000..6c5abb8df3 --- /dev/null +++ b/Task/Currying/J/currying.j @@ -0,0 +1,7 @@ + threePlus=: 3&+ + threePlus 7 +10 + halve =: %&2 NB. % means divide + halve 20 +10 + someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2 diff --git a/Task/Currying/Java/currying.java b/Task/Currying/Java/currying.java new file mode 100644 index 0000000000..dedbabaebf --- /dev/null +++ b/Task/Currying/Java/currying.java @@ -0,0 +1,38 @@ + public class Currier { + public interface CurriableFunctor { + RET evaluate(ARG1 arg1, ARG2 arg2); + } + + public interface CurriedFunctor { + RET evaluate(ARG2 arg); + } + + final CurriableFunctor functor; + + public Currier(CurriableFunctor fn) { functor = fn; } + + public CurriedFunctor curry(final ARG1 arg1) { + return new CurriedFunctor() { + public RET evaluate(ARG2 arg2) { + return functor.evaluate(arg1, arg2); + } + }; + } + + public static void main(String[] args) { + Currier.CurriableFunctor add + = new Currier.CurriableFunctor() { + public Integer evaluate(Integer arg1, Integer arg2) { + return new Integer(arg1.intValue() + arg2.intValue()); + } + }; + + Currier currier + = new Currier(add); + + Currier.CurriedFunctor add5 + = currier.curry(new Integer(5)); + + System.out.println(add5.evaluate(new Integer(2))); + } + } diff --git a/Task/Currying/JavaScript/currying.js b/Task/Currying/JavaScript/currying.js new file mode 100644 index 0000000000..8800c190bd --- /dev/null +++ b/Task/Currying/JavaScript/currying.js @@ -0,0 +1,10 @@ + function addN(n) { + var curry = function(x) { + return x + n; + }; + return curry; + } + + add2 = addN(2); + alert(add2); + alert(add2(7)); diff --git a/Task/Currying/Nemerle/currying.nemerle b/Task/Currying/Nemerle/currying.nemerle new file mode 100644 index 0000000000..6de425618f --- /dev/null +++ b/Task/Currying/Nemerle/currying.nemerle @@ -0,0 +1,20 @@ +using System; +using System.Console; + +module Curry +{ + Curry[T, U, R](f : T * U -> R) : T -> U -> R + { + fun (x) { fun (y) { f(x, y) } } + } + + Main() : void + { + def f(x, y) { x + y } + def g = Curry(f); + def h = Curry(f)(12); // partial application + WriteLine($"$(Curry(f)(20)(22))"); + WriteLine($"$(g(21)(21))"); + WriteLine($"$(h(30))") + } +} diff --git a/Task/Currying/OCaml/currying-1.ocaml b/Task/Currying/OCaml/currying-1.ocaml new file mode 100644 index 0000000000..23437e0247 --- /dev/null +++ b/Task/Currying/OCaml/currying-1.ocaml @@ -0,0 +1,4 @@ +let addnums x y = x+y (* declare a curried function *) + +let add1 = addnums 1 (* bind the first argument to get another function *) +add1 42 (* apply to actually compute a result, 43 *) diff --git a/Task/Currying/OCaml/currying-2.ocaml b/Task/Currying/OCaml/currying-2.ocaml new file mode 100644 index 0000000000..57f08d071a --- /dev/null +++ b/Task/Currying/OCaml/currying-2.ocaml @@ -0,0 +1,2 @@ +let curry f x y = f (x,y) +(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *) diff --git a/Task/Currying/PARI-GP/currying.pari b/Task/Currying/PARI-GP/currying.pari new file mode 100644 index 0000000000..ccaff81732 --- /dev/null +++ b/Task/Currying/PARI-GP/currying.pari @@ -0,0 +1,2 @@ +curriedPlus(x)=y->x+y; +curriedPlus(1)(2) diff --git a/Task/Currying/Perl-6/currying.pl6 b/Task/Currying/Perl-6/currying.pl6 new file mode 100644 index 0000000000..2422169de8 --- /dev/null +++ b/Task/Currying/Perl-6/currying.pl6 @@ -0,0 +1,2 @@ +my &negative = &infix:<->.assuming(0); +say negative 1; diff --git a/Task/Currying/Perl/currying.pl b/Task/Currying/Perl/currying.pl new file mode 100644 index 0000000000..a055f488af --- /dev/null +++ b/Task/Currying/Perl/currying.pl @@ -0,0 +1,15 @@ +sub curry{ + my ($func, @args) = @_; + + sub { + #This @_ is later + &$func(@args, @_); + } +} + +sub plusXY{ + $_[0] + $_[1]; +} + +my $plusXOne = curry(\&plusXY, 1); +print &$plusXOne(3), "\n"; diff --git a/Task/Currying/Python/currying-1.py b/Task/Currying/Python/currying-1.py new file mode 100644 index 0000000000..f69687feab --- /dev/null +++ b/Task/Currying/Python/currying-1.py @@ -0,0 +1,4 @@ + def addN(n): + def adder(x): + return x + n + return adder diff --git a/Task/Currying/Python/currying-2.py b/Task/Currying/Python/currying-2.py new file mode 100644 index 0000000000..2ff1cf9084 --- /dev/null +++ b/Task/Currying/Python/currying-2.py @@ -0,0 +1,5 @@ + >>> add2 = addN(2) + >>> add2 + + >>> add2(7) + 9 diff --git a/Task/Currying/README b/Task/Currying/README new file mode 100644 index 0000000000..79845ab4f5 --- /dev/null +++ b/Task/Currying/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Currying diff --git a/Task/Currying/REXX/currying-1.rexx b/Task/Currying/REXX/currying-1.rexx new file mode 100644 index 0000000000..314658668d --- /dev/null +++ b/Task/Currying/REXX/currying-1.rexx @@ -0,0 +1,7 @@ +/*REXX program demonstrates a REXX currying method to perform addition. */ +say 'add 2 to 3: ' add(2 ,3) +say 'add 2 to 3 (curried):' add2(3) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +add: procedure; $=arg(1); do j=2 to arg(); $=$+arg(j); end; return $ +add2: procedure; return add(arg(1), 2) diff --git a/Task/Currying/REXX/currying-2.rexx b/Task/Currying/REXX/currying-2.rexx new file mode 100644 index 0000000000..2803c5f3fb --- /dev/null +++ b/Task/Currying/REXX/currying-2.rexx @@ -0,0 +1,12 @@ +/*REXX program demonstrates a REXX currying method to perform addition. */ +say 'add 2 to 3: ' add(2 ,3) +say 'add 2 to 3 (curried):' add2(3) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ADD subroutine──────────────────────*/ +add: procedure; $=0; do j=1 for arg() + do k=1 for words(arg(j)); $=$+word(arg(j),k) + end /*k*/ + end /*j*/ +return $ +/*──────────────────────────────────ADD2 subroutine─────────────────────*/ +add2: procedure; return add(arg(1), 2) diff --git a/Task/Currying/Racket/currying-1.rkt b/Task/Currying/Racket/currying-1.rkt new file mode 100644 index 0000000000..8885ca9d5e --- /dev/null +++ b/Task/Currying/Racket/currying-1.rkt @@ -0,0 +1,2 @@ +#lang racket +(((curry +) 3) 2) ; =>5 diff --git a/Task/Currying/Racket/currying-2.rkt b/Task/Currying/Racket/currying-2.rkt new file mode 100644 index 0000000000..60ab379b4c --- /dev/null +++ b/Task/Currying/Racket/currying-2.rkt @@ -0,0 +1,6 @@ +#lang racket + +(define ((curried+ a) b) + (+ a b)) + +((curried+ 3) 2) ; => 5 diff --git a/Task/Currying/Ruby/currying.rb b/Task/Currying/Ruby/currying.rb new file mode 100644 index 0000000000..6b92b44bd3 --- /dev/null +++ b/Task/Currying/Ruby/currying.rb @@ -0,0 +1,13 @@ +b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } +p b.curry[1][2][3] #=> 6 +p b.curry[1, 2][3, 4] #=> 6 +p b.curry(5)[1][2][3][4][5] #=> 6 +p b.curry(5)[1, 2][3, 4][5] #=> 6 +p b.curry(1)[1] #=> 1 + +b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } +p b.curry[1][2][3] #=> 6 +p b.curry[1, 2][3, 4] #=> 10 +p b.curry(5)[1][2][3][4][5] #=> 15 +p b.curry(5)[1, 2][3, 4][5] #=> 15 +p b.curry(1)[1] #=> 1 diff --git a/Task/Currying/Rust/currying.rust b/Task/Currying/Rust/currying.rust new file mode 100644 index 0000000000..550e405f9f --- /dev/null +++ b/Task/Currying/Rust/currying.rust @@ -0,0 +1,9 @@ +#![feature(box_syntax)] +fn add_n(n : i32) -> Box i32 + 'static> { + box move |&: x| n + x +} + +fn main() { + let adder = add_n(40); + println!("The answer to life is {}.", adder(2)); +} diff --git a/Task/Currying/Standard-ML/currying-1.ml b/Task/Currying/Standard-ML/currying-1.ml new file mode 100644 index 0000000000..1d9f56b095 --- /dev/null +++ b/Task/Currying/Standard-ML/currying-1.ml @@ -0,0 +1,4 @@ +fun addnums (x:int) y = x+y (* declare a curried function *) + +val add1 = addnums 1 (* bind the first argument to get another function *) +add1 42 (* apply to actually compute a result, 43 *) diff --git a/Task/Currying/Standard-ML/currying-2.ml b/Task/Currying/Standard-ML/currying-2.ml new file mode 100644 index 0000000000..7890dcd78e --- /dev/null +++ b/Task/Currying/Standard-ML/currying-2.ml @@ -0,0 +1,2 @@ +fun curry f x y = f(x,y) +(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *) diff --git a/Task/Currying/Tcl/currying.tcl b/Task/Currying/Tcl/currying.tcl new file mode 100644 index 0000000000..385d0fb05c --- /dev/null +++ b/Task/Currying/Tcl/currying.tcl @@ -0,0 +1,2 @@ +interp alias {} addone {} ::tcl::mathop::+ 1 +puts [addone 6]; # => 7 diff --git a/Task/Digital-root-Multiplicative-digital-root/00DESCRIPTION b/Task/Digital-root-Multiplicative-digital-root/00DESCRIPTION new file mode 100644 index 0000000000..f172a98ca6 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/00DESCRIPTION @@ -0,0 +1,27 @@ +The [[wp:Multiplicative digital root|multiplicative digital root]] (MDR) and multiplicative persistence (MP) of a number, n, is calculated rather like the [[Digital root]] except digits are multiplied instead of being added: +# Set m to n and i to 0. +# While m has more than one digit: +#* Find a replacement m as the multiplication of the digits of the current value of m. +#* Increment i. +# Return i (= MP) and m (= MDR) + +;Task: +* Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 +* Tabulate MDR versus the first five numbers having that MDR, something like: +
MDR: [n0..n4]
+===  ========
+  0: [0, 10, 20, 25, 30]
+  1: [1, 11, 111, 1111, 11111]
+  2: [2, 12, 21, 26, 34]
+  3: [3, 13, 31, 113, 131]
+  4: [4, 14, 22, 27, 39]
+  5: [5, 15, 35, 51, 53]
+  6: [6, 16, 23, 28, 32]
+  7: [7, 17, 71, 117, 171]
+  8: [8, 18, 24, 29, 36]
+  9: [9, 19, 33, 91, 119]
+Show all output on this page. + +;References: +* [http://mathworld.wolfram.com/MultiplicativeDigitalRoot.html Multiplicative Digital Root] on Wolfram Mathworld. +* [http://oeis.org/A031347 Multiplicative digital root] on The On-Line Encyclopedia of Integer Sequences. diff --git a/Task/Digital-root-Multiplicative-digital-root/00META.yaml b/Task/Digital-root-Multiplicative-digital-root/00META.yaml new file mode 100644 index 0000000000..aed8ff126a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Mathematics diff --git a/Task/Digital-root-Multiplicative-digital-root/ALGOL-68/digital-root-multiplicative-digital-root.alg b/Task/Digital-root-Multiplicative-digital-root/ALGOL-68/digital-root-multiplicative-digital-root.alg new file mode 100644 index 0000000000..e6c014ea44 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/ALGOL-68/digital-root-multiplicative-digital-root.alg @@ -0,0 +1,102 @@ +# Multiplicative Digital Roots # + +# structure to hold the results of calculating the digital root & persistence # +MODE DR = STRUCT( INT root, INT persistence ); + +# calculate the multiplicative digital root and persistence of a number # +PROC md root = ( INT number )DR: +BEGIN + + # calculate the product of the digits of a number # + PROC digit product = ( INT number )INT: + BEGIN + + INT result := 1; + INT rest := number; + + WHILE + result TIMESAB ( rest MOD 10 ); + rest OVERAB 10; + rest > 0 + DO + SKIP + OD; + + result + END; # digit product # + + INT mp := 0; + INT mdr := ABS number; + + WHILE mdr > 9 + DO + mp +:= 1; + mdr := digit product( mdr ) + OD; + + ( mdr, mp ) +END; # md root # + +# prints a number and its MDR and MP # +PROC print md root = ( INT number )VOID: +BEGIN + DR mdr = md root( number ); + print( ( whole( number, -6 ) + , ": MDR: ", whole( root OF mdr, 0 ) + , ", MP: ", whole( persistence OF mdr, -2 ) + , newline + ) + ) +END; # print md root # + +# prints the first few numbers with each possible Multiplicative Digital # +# Root. The number of values to print is specified as a parameter # +PROC tabulate mdr = ( INT number of values )VOID: +BEGIN + + [ 0 : 9, 1 : number of values ]INT mdr values; + [ 0 : 9 ]INT mdr counts; + mdr counts[ AT 1 ] := ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + + # find the first few numbers with each possible mdr # + + INT values found := 0; + INT required values := 10 * number of values; + + FOR value FROM 0 WHILE values found < required values + DO + DR mdr = md root( value ); + IF mdr counts[ root OF mdr ] < number of values + THEN + # need more values with this multiplicative digital root # + values found +:= 1; + mdr counts[ root OF mdr ] +:= 1; + mdr values[ root OF mdr, mdr counts[ root OF mdr ] ] := value + FI + OD; + + # print the values # + + print( ( "MDR: [n0..n" + whole( number of values - 1, 0 ) + "]", newline ) ); + print( ( "=== ========", newline ) ); + FOR mdr pos FROM 1 LWB mdr values TO 1 UPB mdr values + DO + STRING separator := ": ["; + print( ( whole( mdr pos, -3 ) ) ); + FOR val pos FROM 2 LWB mdr values TO 2 UPB mdr values + DO + print( ( separator + whole( mdr values[ mdr pos, val pos ], 0 ) ) ); + separator := ", " + OD; + print( ( "]", newline ) ) + OD + +END; # tabulate mdr # + +main:( + print md root( 123321 ); + print md root( 7739 ); + print md root( 893 ); + print md root( 899998 ); + tabulate mdr( 5 ) +) diff --git a/Task/Digital-root-Multiplicative-digital-root/AWK/digital-root-multiplicative-digital-root.awk b/Task/Digital-root-Multiplicative-digital-root/AWK/digital-root-multiplicative-digital-root.awk new file mode 100644 index 0000000000..75a963c21b --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/AWK/digital-root-multiplicative-digital-root.awk @@ -0,0 +1,76 @@ +# Multiplicative Digital Roots + +BEGIN { + + printMdrAndMp( 123321 ); + printMdrAndMp( 7739 ); + printMdrAndMp( 893 ); + printMdrAndMp( 899998 ); + + tabulateMdr( 5 ); + +} # BEGIN + +function printMdrAndMp( n ) +{ + calculateMdrAndMp( n ); + printf( "%6d: MDR: %d, MP: %2d\n", n, MDR, MP ); +} # printMdrAndMp + +function calculateMdrAndMp( n, mdrStr, digit ) +{ + + MP = 0; # global Multiplicative Persistence + MDR = ( n < 0 ? -n : n ); # global Multiplicative Digital Root + + while( MDR > 9 ) + { + MP ++; + mdrStr = "" MDR; + MDR = 1; + for( digit = 1; digit <= length( mdrStr ); digit ++ ) + { + MDR *= ( substr( mdrStr, digit, 1 ) * 1 ); + } # for digit + } # while MDR > 9 + +} # calculateMdrAndMp + +function tabulateMdr( n, rqdValues, valueCount, value, pos ) +{ + + # generate a table of the first n numbers with each possible MDR + + rqdValues = n * 10; + valueCount = 0; + + for( value = 0; valueCount < rqdValues; value ++ ) + { + calculateMdrAndMp( value ); + if( mdrCount[ MDR ] < n ) + { + # still need another value with this MDR + valueCount ++; + mdrCount[ MDR ] ++; + mdrValues[ MDR ":" mdrCount[ MDR ] ] = value; + } # if mdrCount[ MDR ] < n + } # for value + + # print the table + + printf( "MDR: [n0..n%d]\n", n - 1 ); + printf( "=== ========\n" ); + + for( pos = 0; pos < 10; pos ++ ) + { + printf( "%3d:", pos ); + separator = " ["; + for( value = 1; value <= n; value ++ ) + { + printf( "%s%d", separator, mdrValues[ pos ":" value ] ); + separator = ", " + } # for value + printf( "]\n" ); + } # for pos + +} # tabulateMdr diff --git a/Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada b/Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada new file mode 100644 index 0000000000..24b7e8d612 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada @@ -0,0 +1,47 @@ +with Ada.Text_IO, Generic_Root; use Generic_Root; + +procedure Multiplicative_Root is + + procedure Compute is new Compute_Root("*"); -- "*" for multiplicative roots + + package TIO renames Ada.Text_IO; + package NIO is new TIO.Integer_IO(Number); + + procedure Print_Numbers(Target_Root: Number; How_Many: Natural) is + Current: Number := 0; + Root, Pers: Number; + begin + for I in 1 .. How_Many loop + loop + Compute(Current, Root, Pers); + exit when Root = Target_Root; + Current := Current + 1; + end loop; + NIO.Put(Current, Width => 6); + if I < How_Many then + TIO.Put(","); + end if; + Current := Current + 1; + end loop; + end Print_Numbers; + + Inputs: Number_Array := (123321, 7739, 893, 899998); + Root, Pers: Number; +begin + TIO.Put_Line(" Number MDR MP"); + for I in Inputs'Range loop + Compute(Inputs(I), Root, Pers); + NIO.Put(Inputs(I), Width => 8); + NIO.Put(Root, Width => 6); + NIO.Put(Pers, Width => 6); + TIO.New_Line; + end loop; + TIO.New_Line; + + TIO.Put_Line(" MDR first_five_numbers_with_that_MDR"); + for I in 0 .. 9 loop + TIO.Put(" " & Integer'Image(I) & " "); + Print_Numbers(Target_Root => Number(I), How_Many => 5); + TIO.New_Line; + end loop; +end Multiplicative_Root; diff --git a/Task/Digital-root-Multiplicative-digital-root/Bracmat/digital-root-multiplicative-digital-root.bracmat b/Task/Digital-root-Multiplicative-digital-root/Bracmat/digital-root-multiplicative-digital-root.bracmat new file mode 100644 index 0000000000..b4df78b13f --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Bracmat/digital-root-multiplicative-digital-root.bracmat @@ -0,0 +1,46 @@ +( +& ( MP/MDR + = prod L n + . ( prod + = d + . @(!arg:%@?d ?arg)&!d*prod$!arg + | 1 + ) + & !arg:?L + & whl + ' ( @(!arg:? [>1) + & (prod$!arg:?arg) !L:?L + ) + & !L:? [?n + & (!n+-1.!arg) + ) +& ( test + = n + . !arg:%?n ?arg + & out$(!n "\t:" MP/MDR$!n) + & test$!arg + | + ) +& test$(123321 7739 893 899998) +& 0:?i +& 1:?collecting:?done +& whl + ' ( !i+1:?i + & MP/MDR$!i:(?MP.?MDR) + & ( !done:?*(!MDR.)^((?.)+?)*? + | (!MDR.)^(!i.)*!collecting:?collecting + & ( !collecting:?A*(!MDR.)^(?is+[5)*?Z + & !A*!Z:?collecting + & (!MDR.)^!is*!done:?done + | + ) + ) + & !collecting:~1 + ) +& whl + ' ( !done:(?MDR.)^?is*?done + & put$(!MDR ":") + & whl'(!is:(?i.)+?is&put$(!i " ")) + & put$\n + ) +); diff --git a/Task/Digital-root-Multiplicative-digital-root/C++/digital-root-multiplicative-digital-root.cpp b/Task/Digital-root-Multiplicative-digital-root/C++/digital-root-multiplicative-digital-root.cpp new file mode 100644 index 0000000000..3859b2d921 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/C++/digital-root-multiplicative-digital-root.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +using namespace std; + +void calcMDR( int n, int c, int& a, int& b ) +{ + int m = n % 10; n /= 10; + while( n ) + { + m *= ( n % 10 ); + n /= 10; + } + if( m >= 10 ) calcMDR( m, ++c, a, b ); + else { a = m; b = c; } +} + +void table() +{ + map > mp; + int n = 0, a, b; + bool f = true; + while( f ) + { + f = false; + calcMDR( n, 1, a, b ); + mp[a].push_back( n ); + n++; + for( int x = 0; x < 10; x++ ) + if( mp[x].size() < 5 ) + { f = true; break; } + } + + cout << "| MDR | [n0..n4]\n+-------+------------------------------------+\n"; + for( int x = 0; x < 10; x++ ) + { + cout << right << "| " << setw( 6 ) << x << "| "; + for( vector::iterator i = mp[x].begin(); i != mp[x].begin() + 5; i++ ) + cout << setw( 6 ) << *i << " "; + cout << "|\n"; + } + cout << "+-------+------------------------------------+\n\n"; +} + +int main( int argc, char* argv[] ) +{ + cout << "| NUMBER | MDR | MP |\n+----------+----------+----------+\n"; + int numbers[] = { 123321, 7739, 893, 899998 }, a, b; + for( int x = 0; x < 4; x++ ) + { + cout << right << "| " << setw( 9 ) << numbers[x] << "| "; + calcMDR( numbers[x], 1, a, b ); + cout << setw( 9 ) << a << "| " << setw( 9 ) << b << "|\n"; + } + cout << "+----------+----------+----------+\n\n"; + table(); + return system( "pause" ); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/C/digital-root-multiplicative-digital-root.c b/Task/Digital-root-Multiplicative-digital-root/C/digital-root-multiplicative-digital-root.c new file mode 100644 index 0000000000..3cc31a43cf --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/C/digital-root-multiplicative-digital-root.c @@ -0,0 +1,58 @@ +#include + +#define twidth 5 +#define mdr(rmdr, rmp, n)\ + do { *rmp = 0; _mdr(rmdr, rmp, n); } while (0) + +void _mdr(int *rmdr, int *rmp, long long n) +{ + /* Adjust r if 0 case, so we don't return 1 */ + int r = n ? 1 : 0; + while (n) { + r *= (n % 10); + n /= 10; + } + + (*rmp)++; + if (r >= 10) + _mdr(rmdr, rmp, r); + else + *rmdr = r; +} + +int main(void) +{ + int i, j, vmdr, vmp; + const int values[] = { 123321, 7739, 893, 899998 }; + const int vsize = sizeof(values) / sizeof(values[0]); + + /* Initial test values */ + printf("Number MDR MP\n"); + for (i = 0; i < vsize; ++i) { + mdr(&vmdr, &vmp, values[i]); + printf("%6d %3d %3d\n", values[i], vmdr, vmp); + } + + /* Determine table values */ + int table[10][twidth] = { 0 }; + int tfill[10] = { 0 }; + int total = 0; + for (i = 0; total < 10 * twidth; ++i) { + mdr(&vmdr, &vmp, i); + if (tfill[vmdr] < twidth) { + table[vmdr][tfill[vmdr]++] = i; + total++; + } + } + + /* Print calculated table values */ + printf("\nMDR: [n0..n4]\n"); + for (i = 0; i < 10; ++i) { + printf("%3d: [", i); + for (j = 0; j < twidth; ++j) + printf("%d%s", table[i][j], j != twidth - 1 ? ", " : ""); + printf("]\n"); + } + + return 0; +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Common-Lisp/digital-root-multiplicative-digital-root.lisp b/Task/Digital-root-Multiplicative-digital-root/Common-Lisp/digital-root-multiplicative-digital-root.lisp new file mode 100644 index 0000000000..e18d94c6a8 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Common-Lisp/digital-root-multiplicative-digital-root.lisp @@ -0,0 +1,25 @@ +(defun mdr/p (n) + "Return a list with MDR and MP of n" + (if (< n 10) + (list n 0) + (mdr/p-aux n 1 1))) + +(defun mdr/p-aux (n a c) + (cond ((and (zerop n) (< a 10)) (list a c)) + ((zerop n) (mdr/p-aux a 1 (+ c 1))) + (t (mdr/p-aux (floor n 10) (* (rem n 10) a) c)))) + +(defun first-n-number-for-each-root (n &optional (r 0) (lst nil) (c 0)) + "Return the first m number with MDR = 0 to 9" + (cond ((and (= (length lst) n) (= r 9)) (format t "~3@a: ~a~%" r (reverse lst))) + ((= (length lst) n) (format t "~3@a: ~a~%" r (reverse lst)) + (first-n-number-for-each-root n (+ r 1) nil 0)) + ((= (first (mdr/p c)) r) (first-n-number-for-each-root n r (cons c lst) (+ c 1))) + (t (first-n-number-for-each-root n r lst (+ c 1))))) + +(defun start () + (format t "Number: MDR MD~%") + (loop for el in '(123321 7739 893 899998) + do (format t "~6@a: ~{~3@a ~}~%" el (mdr/p el))) + (format t "~%MDR: [n0..n4]~%") + (first-n-number-for-each-root 5)) diff --git a/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-1.d b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-1.d new file mode 100644 index 0000000000..c76f1ca5c6 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-1.d @@ -0,0 +1,27 @@ +import std.stdio, std.algorithm, std.typecons, std.range, std.conv; + +/// Multiplicative digital root. +auto mdRoot(in int n) pure /*nothrow*/ { + auto mdr = [n]; + while (mdr.back > 9) + mdr ~= reduce!q{a * b}(1, mdr.back.text.map!(d => d - '0')); + //mdr ~= mdr.back.text.map!(d => d - '0').mul; + //mdr ~= mdr.back.reverseDigits.mul; + return tuple(mdr.length - 1, mdr.back); +} + +void main() { + "Number: (MP, MDR)\n====== =========".writeln; + foreach (immutable n; [123321, 7739, 893, 899998]) + writefln("%6d: (%s, %s)", n, n.mdRoot[]); + + auto table = (int[]).init.repeat.enumerate!int.take(10).assocArray; + auto n = 0; + while (table.byValue.map!walkLength.reduce!min < 5) { + table[n.mdRoot[1]] ~= n; + n++; + } + "\nMP: [n0..n4]\n== ========".writeln; + foreach (const mp; table.byKey.array.sort()) + writefln("%2d: %s", mp, table[mp].take(5)); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-2.d b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-2.d new file mode 100644 index 0000000000..db1766d8cd --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-2.d @@ -0,0 +1,34 @@ +import std.stdio, std.algorithm, std.typecons, std.range; + +uint digitsProduct(uint n) pure nothrow @nogc { + typeof(return) result = !!n; + while (n) { + result *= n % 10; + n /= 10; + } + return result; +} + +/// Multiplicative digital root. +Tuple!(size_t, uint) mdRoot(uint m) pure nothrow { + auto mdr = m + .recurrence!((a, n) => a[n - 1].digitsProduct) + .until!q{ a <= 9 }(OpenRight.no).array; + return tuple(mdr.length - 1, mdr.back); +} + +void main() { + "Number: (MP, MDR)\n====== =========".writeln; + foreach (immutable n; [123321, 7739, 893, 899998]) + writefln("%6d: (%s, %s)", n, n.mdRoot[]); + + auto table = (int[]).init.repeat.enumerate!int.take(10).assocArray; + auto n = 0; + while (table.byValue.map!walkLength.reduce!min < 5) { + table[n.mdRoot[1]] ~= n; + n++; + } + "\nMP: [n0..n4]\n== ========".writeln; + foreach (const mp; table.byKey.array.sort()) + writefln("%2d: %s", mp, table[mp].take(5)); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-3.d b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-3.d new file mode 100644 index 0000000000..99e844cb69 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/D/digital-root-multiplicative-digital-root-3.d @@ -0,0 +1,36 @@ +import std.stdio, std.algorithm, std.range; + +/// Multiplicative digital root. +uint[2] mdRoot(in uint n) pure nothrow @nogc { + uint mdr = n; + uint count = 0; + + while (mdr > 9) { + uint m = mdr; + uint digitsMul = !!m; + while (m) { + digitsMul *= m % 10; + m /= 10; + } + mdr = digitsMul; + count++; + } + + return [count, mdr]; +} + +void main() { + "Number: [MP, MDR]\n====== =========".writeln; + foreach (immutable n; [123321, 7739, 893, 899998]) + writefln("%6d: %s", n, n.mdRoot); + + auto table = (int[]).init.repeat.enumerate!int.take(10).assocArray; + auto n = 0; + while (table.byValue.map!walkLength.reduce!min < 5) { + table[n.mdRoot[1]] ~= n; + n++; + } + "\nMP: [n0..n4]\n== ========".writeln; + foreach (const mp; table.byKey.array.sort()) + writefln("%2d: %s", mp, table[mp].take(5)); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Fortran/digital-root-multiplicative-digital-root.f b/Task/Digital-root-Multiplicative-digital-root/Fortran/digital-root-multiplicative-digital-root.f new file mode 100644 index 0000000000..61f6db3146 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Fortran/digital-root-multiplicative-digital-root.f @@ -0,0 +1,90 @@ +!Implemented by Anant Dixit (Oct, 2014) +program mdr +implicit none +integer :: i, mdr, mp, n, j +character(len=*), parameter :: hfmt = '(A18)', nfmt = '(I6)' +character(len=*), parameter :: cfmt = '(A3)', rfmt = '(I3)', ffmt = '(I9)' + +write(*,hfmt) 'Number MDR MP ' +write(*,*) '------------------' + +i = 123321 +call root_pers(i,mdr,mp) +write(*,nfmt,advance='no') i +write(*,cfmt,advance='no') ' ' +write(*,rfmt,advance='no') mdr +write(*,cfmt,advance='no') ' ' +write(*,rfmt) mp + +i = 3939 +call root_pers(i,mdr,mp) +write(*,nfmt,advance='no') i +write(*,cfmt,advance='no') ' ' +write(*,rfmt,advance='no') mdr +write(*,cfmt,advance='no') ' ' +write(*,rfmt) mp + +i = 8822 +call root_pers(i,mdr,mp) +write(*,nfmt,advance='no') i +write(*,cfmt,advance='no') ' ' +write(*,rfmt,advance='no') mdr +write(*,cfmt,advance='no') ' ' +write(*,rfmt) mp + +i = 39398 +call root_pers(i,mdr,mp) +write(*,nfmt,advance='no') i +write(*,cfmt,advance='no') ' ' +write(*,rfmt,advance='no') mdr +write(*,cfmt,advance='no') ' ' +write(*,rfmt) mp + +write(*,*) +write(*,*) +write(*,*) 'First five numbers with MDR in first column: ' +write(*,*) '---------------------------------------------' + +do i = 0,9 + n = 0 + j = 0 + write(*,rfmt,advance='no') i + do + call root_pers(j,mdr,mp) + if(mdr.eq.i) then + n = n+1 + if(n.eq.5) then + write(*,ffmt) j + exit + else + write(*,ffmt,advance='no') j + end if + end if + j = j+1 + end do +end do + +end program + +subroutine root_pers(i,mdr,mp) +implicit none +integer :: N, s, a, i, mdr, mp +n = i +a = 0 +if(n.lt.10) then + mdr = n + mp = 0 + return +end if +do while(n.ge.10) + a = a + 1 + s = 1 + do while(n.gt.0) + s = s * mod(n,10) + n = int(real(n)/10.0D0) + end do + n = s +end do +mdr = s +mp = a +end subroutine diff --git a/Task/Digital-root-Multiplicative-digital-root/Go/digital-root-multiplicative-digital-root.go b/Task/Digital-root-Multiplicative-digital-root/Go/digital-root-multiplicative-digital-root.go new file mode 100644 index 0000000000..9732aa0a19 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Go/digital-root-multiplicative-digital-root.go @@ -0,0 +1,55 @@ +package main + +import "fmt" + +// Only valid for n > 0 && base >= 2 +func mult(n uint64, base int) (mult uint64) { + for mult = 1; mult > 0 && n > 0; n /= uint64(base) { + mult *= n % uint64(base) + } + return +} + +// Only valid for n >= 0 && base >= 2 +func MultDigitalRoot(n uint64, base int) (mp, mdr int) { + var m uint64 + for m = n; m >= uint64(base); mp++ { + m = mult(m, base) + } + return mp, int(m) +} + +func main() { + const base = 10 + const size = 5 + + const testFmt = "%20v %3v %3v\n" + fmt.Printf(testFmt, "Number", "MDR", "MP") + for _, n := range [...]uint64{ + 123321, 7739, 893, 899998, + 18446743999999999999, + // From http://mathworld.wolfram.com/MultiplicativePersistence.html + 3778888999, 277777788888899, + } { + mp, mdr := MultDigitalRoot(n, base) + fmt.Printf(testFmt, n, mdr, mp) + } + fmt.Println() + + var list [base][]uint64 + for i := range list { + list[i] = make([]uint64, 0, size) + } + for cnt, n := size*base, uint64(0); cnt > 0; n++ { + _, mdr := MultDigitalRoot(n, base) + if len(list[mdr]) < size { + list[mdr] = append(list[mdr], n) + cnt-- + } + } + const tableFmt = "%3v: %v\n" + fmt.Printf(tableFmt, "MDR", "First") + for i, l := range list { + fmt.Printf(tableFmt, i, l) + } +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Haskell/digital-root-multiplicative-digital-root.hs b/Task/Digital-root-Multiplicative-digital-root/Haskell/digital-root-multiplicative-digital-root.hs new file mode 100644 index 0000000000..5990b69f14 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Haskell/digital-root-multiplicative-digital-root.hs @@ -0,0 +1,41 @@ +import Control.Arrow +import Data.Array +import Data.LazyArray +import Data.List (unfoldr) +import Data.Tuple +import Text.Printf + +-- The multiplicative persistence (MP) and multiplicative digital root (MDR) of +-- the argument. +mpmdr :: Integer -> (Int, Integer) +mpmdr = (length *** head) . span (> 9) . iterate (product . digits) + +-- Pairs (mdr, ns) where mdr is a multiplicative digital root and ns are the +-- first k numbers having that root. +mdrNums :: Int -> [(Integer, [Integer])] +mdrNums k = assocs $ lArrayMap (take k) (0,9) [(snd $ mpmdr n, n) | n <- [0..]] + +digits :: Integral t => t -> [t] +digits 0 = [0] +digits n = unfoldr step n + where step 0 = Nothing + step k = Just (swap $ quotRem k 10) + +printMpMdrs :: [Integer] -> IO () +printMpMdrs ns = do + putStrLn "Number MP MDR" + putStrLn "====== == ===" + sequence_ [printf "%6d %2d %2d\n" n p r | n <- ns, let (p,r) = mpmdr n] + +printMdrNums:: Int -> IO () +printMdrNums k = do + putStrLn "MDR Numbers" + putStrLn "=== =======" + let showNums = unwords . map show + sequence_ [printf "%2d %s\n" mdr $ showNums ns | (mdr,ns) <- mdrNums k] + +main :: IO () +main = do + printMpMdrs [123321, 7739, 893, 899998] + putStrLn "" + printMdrNums 5 diff --git a/Task/Digital-root-Multiplicative-digital-root/Icon/digital-root-multiplicative-digital-root.icon b/Task/Digital-root-Multiplicative-digital-root/Icon/digital-root-multiplicative-digital-root.icon new file mode 100644 index 0000000000..27c4c863d5 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Icon/digital-root-multiplicative-digital-root.icon @@ -0,0 +1,24 @@ +procedure main(A) + write(right("n",8)," ",right("MP",8),right("MDR",5)) + every r := mdr(n := 123321|7739|893|899998) do + write(right(n,8),":",right(r[1],8),right(r[2],5)) + write() + write(right("MDR",5)," ","[n0..n4]") + every m := 0 to 9 do { + writes(right(m,5),": [") + every writes(right((m = mdr(n := seq(m))[2],.n)\5,6)) + write("]") + } +end + +procedure mdr(m) + i := 0 + while (.m > 10, m := multd(m), i+:=1) + return [i,m] +end + +procedure multd(m) + c := 1 + while m > 0 do c *:= 1(m%10, m/:=10) + return c +end diff --git a/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-1.j b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-1.j new file mode 100644 index 0000000000..ef6db08712 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-1.j @@ -0,0 +1,2 @@ + 10&#.inv 123321 +1 2 3 3 2 1 diff --git a/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-2.j b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-2.j new file mode 100644 index 0000000000..9430c6faa0 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-2.j @@ -0,0 +1,2 @@ + */@(10&#.inv) 123321 +36 diff --git a/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-3.j b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-3.j new file mode 100644 index 0000000000..898ec07465 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-3.j @@ -0,0 +1,2 @@ + */@(10&#.inv)^:a: 123321 +123321 36 18 8 diff --git a/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-4.j b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-4.j new file mode 100644 index 0000000000..5983d63b8c --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-4.j @@ -0,0 +1,8 @@ + (<:@#,{:) */@(10&#.inv)^:a: 123321 +3 8 + (<:@#,{:) */@(10&#.inv)^:a: 7739 +3 8 + (<:@#,{:) */@(10&#.inv)^:a: 893 +3 2 + (<:@#,{:) */@(10&#.inv)^:a: 899998 +2 0 diff --git a/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-5.j b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-5.j new file mode 100644 index 0000000000..0a2c437aed --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/J/digital-root-multiplicative-digital-root-5.j @@ -0,0 +1,11 @@ + (5&{./.~ (*/@(10&#.inv)^:_)"0) i.20000 +0 10 20 25 30 +1 11 111 1111 11111 +2 12 21 26 34 +3 13 31 113 131 +4 14 22 27 39 +5 15 35 51 53 +6 16 23 28 32 +7 17 71 117 171 +8 18 24 29 36 +9 19 33 91 119 diff --git a/Task/Digital-root-Multiplicative-digital-root/Java/digital-root-multiplicative-digital-root.java b/Task/Digital-root-Multiplicative-digital-root/Java/digital-root-multiplicative-digital-root.java new file mode 100644 index 0000000000..570b1bc84e --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Java/digital-root-multiplicative-digital-root.java @@ -0,0 +1,51 @@ +import java.util.*; + +public class MultiplicativeDigitalRoot { + + public static void main(String[] args) { + + System.out.println("NUMBER MDR MP"); + for (long n : new long[]{123321, 7739, 893, 899998}) { + long[] a = multiplicativeDigitalRoot(n); + System.out.printf("%6d %4d %4d%n", a[0], a[1], a[2]); + } + + System.out.println(); + + Map> table = new HashMap<>(); + for (long i = 0; i < 10; i++) + table.put(i, new ArrayList<>()); + + for (long cnt = 0, n = 0; cnt < 10;) { + long[] res = multiplicativeDigitalRoot(n++); + List list = table.get(res[1]); + if (list.size() < 5) { + list.add(res[0]); + cnt = list.size() == 5 ? cnt + 1 : cnt; + } + } + + System.out.println("MDR: first five numbers with same MDR"); + table.forEach((key, lst) -> { + System.out.printf("%3d: ", key); + lst.forEach(e -> System.out.printf("%6s ", e)); + System.out.println(); + }); + } + + public static long[] multiplicativeDigitalRoot(long n) { + int mp = 0; + long mdr = n; + while (mdr > 9) { + long m = mdr; + long total = 1; + while (m > 0) { + total *= m % 10; + m /= 10; + } + mdr = total; + mp++; + } + return new long[]{n, mdr, mp}; + } +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Mathematica/digital-root-multiplicative-digital-root.math b/Task/Digital-root-Multiplicative-digital-root/Mathematica/digital-root-multiplicative-digital-root.math new file mode 100644 index 0000000000..e01b1f2aee --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Mathematica/digital-root-multiplicative-digital-root.math @@ -0,0 +1,9 @@ +ClearAll[mdr, mp, nums]; +mdr[n_] := NestWhile[Times @@ IntegerDigits[#] &, n, # > 9 &]; +mp[n_] := Length@NestWhileList[Times @@ IntegerDigits[#] &, n, # > 9 &] - 1; +TableForm[{#, mdr[#], mp[#]} & /@ {123321, 7739, 893, 899998}, + TableHeadings -> {None, {"Number", "MDR", "MP"}}] +nums = ConstantArray[{}, 10]; +For[i = 0, Min[Length /@ nums] < 5, i++, AppendTo[nums[[mdr[i] + 1]], i]]; +TableForm[Table[{i, Take[nums[[i + 1]], 5]}, {i, 0, 9}], + TableHeadings -> {None, {"MDR", "First 5"}}, TableDepth -> 2] diff --git a/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-1.pli b/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-1.pli new file mode 100644 index 0000000000..86ebd89a85 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-1.pli @@ -0,0 +1,24 @@ +multiple: procedure options (main); /* 29 April 2014 */ + + declare n fixed binary (31); + +find_mdr: procedure; + declare (mdr, mp, p) fixed binary (31); + + mdr = n; + do mp = 1 by 1 until (p <= 9); + p = 1; + do until (mdr = 0); /* Form product of the digits in mdr. */ + p = mod(mdr, 10) * p; + mdr= mdr/10; + end; + mdr = p; + end; + put skip data (n, mdr, mp); +end find_mdr; + + do n = 123321, 7739, 893, 899998; + call find_mdr; + end; + +end multiple; diff --git a/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-2.pli b/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-2.pli new file mode 100644 index 0000000000..dfde1a85c1 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/PL-I/digital-root-multiplicative-digital-root-2.pli @@ -0,0 +1,56 @@ + mdrt: Proc Options(main); + Dcl (x,p,r) Bin Fixed(31); + Put Edit('number persistence multiplicative digital root')(Skip,a); + Put Edit('------- ----------- ---------------------------')(Skip,a); + Call task1(123321); + Call task1( 7739); + Call task1( 893); + Call task1(899998); + + task1: Procedure(x); + Dcl x Bin Fixed(31); + Call mdr(x,p,r); + Put Edit(x,p,r)(Skip,f(8),f(8),f(22)); + End; + + Dcl zn(0:9) Bin Fixed(31); + Dcl z(0:9,5) Bin Fixed(31); + zn=0; + zn(0)=1; + z(0,1)=0; + Do x=1 To 11111; + Call mdr(x,p,r); + If zn(r)<5 Then Do; + zn(r)+=1; + z(r,zn(r))=x; + End; + End; + Put Edit(' ')(Skip,a); + Put Edit('MDR first 5 numbers that have a matching MDR')(Skip,a); + Put Edit('--- ----------------------------------------')(Skip,a); + + Do r=0 To 9; + Put Edit(r,' ')(Skip,f(3),a); + Do i=1 To 5; + Put Edit(z(r,i))(f(6)); + End; + End; + + mdr: Procedure(y,p,r); + Dcl (y,p,r) Bin Fixed(31); + Dcl (k,yy) Bin Fixed(31); + Dcl pic Pic'(10)9'; + Dcl d Pic'9'; + pic=abs(y); + Do p=1 By 1 Until(pic<10); + Do k=1 To 10 Until(substr(pic,k,1)>'0'); + End; + r=1; + Do k=k To 10; + d=substr(pic,k,1); + r=r*d; + End; + pic=r; + End; + End; + End; diff --git a/Task/Digital-root-Multiplicative-digital-root/Perl-6/digital-root-multiplicative-digital-root.pl6 b/Task/Digital-root-Multiplicative-digital-root/Perl-6/digital-root-multiplicative-digital-root.pl6 new file mode 100644 index 0000000000..c9780113db --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Perl-6/digital-root-multiplicative-digital-root.pl6 @@ -0,0 +1,13 @@ +sub multiplicative-digital-root(Int $n) { + return .elems - 1, .[.end] + given $n, {[*] .comb} ... *.chars == 1 +} + +for 123321, 7739, 893, 899998 { + say "$_: ", .&multiplicative-digital-root; +} + +for ^10 -> $d { + say "$d : ", .[^5] + given (1..*).grep: *.&multiplicative-digital-root[1] == $d; +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Perl/digital-root-multiplicative-digital-root.pl b/Task/Digital-root-Multiplicative-digital-root/Perl/digital-root-multiplicative-digital-root.pl new file mode 100644 index 0000000000..c4dc5a5e0c --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Perl/digital-root-multiplicative-digital-root.pl @@ -0,0 +1,28 @@ +use warnings; +use strict; + +sub mdr { + my $n = shift; + my($count, $mdr) = (0, $n); + while ($mdr > 9) { + my($m, $dm) = ($mdr, 1); + while ($m) { + $dm *= $m % 10; + $m = int($m/10); + } + $mdr = $dm; + $count++; + } + ($count, $mdr); +} + +print "Number: (MP, MDR)\n====== =========\n"; +foreach my $n (123321, 7739, 893, 899998) { + printf "%6d: (%d, %d)\n", $n, mdr($n); +} +print "\nMP: [n0..n4]\n== ========\n"; +foreach my $target (0..9) { + my $i = 0; + my @n = map { $i++ while (mdr($i))[1] != $target; $i++; } 1..5; + print " $target: [", join(", ", @n), "]\n"; +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-1.py b/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-1.py new file mode 100644 index 0000000000..c7ecac2095 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-1.py @@ -0,0 +1,25 @@ +try: + from functools import reduce +except: + pass + +def mdroot(n): + 'Multiplicative digital root' + mdr = [n] + while mdr[-1] > 9: + mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1)) + return len(mdr) - 1, mdr[-1] + +if __name__ == '__main__': + print('Number: (MP, MDR)\n====== =========') + for n in (123321, 7739, 893, 899998): + print('%6i: %r' % (n, mdroot(n))) + + table, n = {i: [] for i in range(10)}, 0 + while min(len(row) for row in table.values()) < 5: + mpersistence, mdr = mdroot(n) + table[mdr].append(n) + n += 1 + print('\nMP: [n0..n4]\n== ========') + for mp, val in sorted(table.items()): + print('%2i: %r' % (mp, val[:5])) diff --git a/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-2.py b/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-2.py new file mode 100644 index 0000000000..f58ef70c53 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Python/digital-root-multiplicative-digital-root-2.py @@ -0,0 +1,10 @@ +def mdroot(n): + count, mdr = 0, n + while mdr > 9: + m, digitsMul = mdr, 1 + while m: + m, md = divmod(m, 10) + digitsMul *= md + mdr = digitsMul + count += 1 + return count, mdr diff --git a/Task/Digital-root-Multiplicative-digital-root/README b/Task/Digital-root-Multiplicative-digital-root/README new file mode 100644 index 0000000000..f0883e1047 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root diff --git a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx new file mode 100644 index 0000000000..727cedd81a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx @@ -0,0 +1,28 @@ +/*REXX pgm finds persistence and multiplicative digital root of some #'s*/ +numeric digits 100 /*increase the number of digits. */ +parse arg x /*get some numbers from the C.L. */ +if x='' then x=123321 7739 893 899998 /*use defaults if none specified.*/ +say center('number',8) ' persistence multiplicative digital root' +say copies('─' ,8) ' ─────────── ───────────────────────────' + /* [↑] title and separator. */ + do j=1 for words(x); n=word(x,j) /*process each number in the list*/ + parse value mdr(n) with mp mdr /*obtain the persistence and MDR.*/ + say right(n,8) center(mp,13) center(mdr,30) /*display #, mp, mdr.*/ + end /*j*/ /* [↑] show MP and MDR for each #*/ +say; target=5 +say 'MDR first ' target " numbers that have a matching MDR" +say '═══ ═══════════════════════════════════════════════════' + do k=0 for 10; hits=0; _= /*show #'s that have an MDR of K.*/ + do m=k until hits==target /*find target #s with an MDR of K*/ + if word(mdr(m),2)\==k then iterate /*is the MDR what's wanted? */ + hits=hits+1; _=space(_ m',') /*yes, we got a hit, add to list.*/ + end /*m*/ /* [↑] built a list of MDRs = k */ + say " "k': ['strip(_,,',')"]" /*display the K (mdr) and list.*/ + end /*k*/ /* [↑] done with the K mdr list.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────MDR subroutine──────────────────────*/ +mdr: procedure; parse arg y; y=abs(y) /*get the number and find the MDR*/ + do p=1 until y<10 /*find multiplicative digRoot (Y)*/ + parse var y 1 r 2; do k=2 to length(y); r=r*substr(y,k,1); end; y=r + end /*p*/ /*wash, rinse, repeat ··· */ +return p r /*return the persistence and MDR.*/ diff --git a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx new file mode 100644 index 0000000000..6f6a8f7a7a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx @@ -0,0 +1,72 @@ +/*REXX pgm finds persistence and multiplicative digital root of some #'s*/ +numeric digits 2000 /*increase the number of digits. */ +parse arg target x; if \datatype(target,'W') then target=25 /*default?*/ +if x='' then x=123321 7739 893 899998 /*use the defaults for X ? */ +say center('number',8) ' persistence multiplicative digital root' +say copies('─' ,8) ' ─────────── ───────────────────────────' + /* [↑] title and separator. */ + do j=1 for words(x); n=abs(word(x,j)) /*process each # in list.*/ + parse value mdr(n) with mp mdr /*obtain the persistence and MDR.*/ + say right(n,8) center(mp,13) center(mdr,30) /*display #, mp, mdr.*/ + end /*j*/ /* [↑] show MP and MDR for each #*/ +say /* [↓] show a blank & title line.*/ +say 'MDR first ' target " numbers that have a matching MDR" +say '═══ ' copies("═",(target+(target+1)**2)%2) /*display a sep line.*/ + + do k=0 for 9; hits=0; _= /*show #'s that have an MDR of K.*/ + if k==7 then _=@7; else /*handle special seven case. */ + + do m=k until hits==target /*find target #s with an MDR of K*/ + ?=right(m,1) /*obtain right-most digit of M. */ + if k\==0 then if ?==0 then iterate + if k==5 then if ?//2==0 then iterate + if k==1 then m=copies(1,hits+1) + else if mdr(m,1)\==k then iterate + hits=hits+1; _=space(_ m) /*yes, we got a hit, add to list.*/ + + if k==3 then do; o=strip(m,'T',1) /*strip trailing ones*/ + if o==3 then m=copies(1,length(m))3 /*make new M. */ + else do; t=pos(3,m)-1 /*position of 3*/ + m=overlay(3,translate(m,1,3),t) + end /* [↑] shift the "3" 1 place left*/ + m=m-1 /*adjust for DO index advancement*/ + end /* [↑] a shortcut to do DO index*/ + end /*m*/ /* [↑] built a list of MDRs = k */ + + say " "k': ['_"]" /*display the K (mdr) and list.*/ + if k==3 then @7=translate(_,7,k) /*save for later, special 7 case.*/ + end /*k*/ /* [↑] done with the K mdr list.*/ +@.= /* [↓] handle MDR of 9 special. */ +_=translate(@7,9,7) /*translate a string for MDR 9. */ +@9=translate(_,,',') /*remove trailing commas from #'s*/ +@3= /*assine null string before build*/ + do j=1 for words(@9) /*process each number for MDR 9. */ + _=space(translate(word(@9,j),,9),0) /*remove "9"s using SPACE(x,0)*/ + L=length(_)+1 /*use a "fudged" length of the #.*/ + new= /*this is the new numbers so far.*/ + do k=0 for L; q=insert(3,_,k) /*insert the 1st "3" into the #*/ + do i=k to L; z=insert(3,q,i) /* " " 2nd "3" " " "*/ + if @.z\=='' then iterate /*if already define, ignore the #*/ + @.z=z; new=z new /*define it, and then add to list*/ + end /*i*/ /* [↑] end of 2nd insertion of 3*/ + end /*k*/ /* [↑] " " 1st " " "*/ + @3=space(@3 new) /*remove blanks, then add to list*/ + end /*j*/ /* [↑] end of insertion of "3"s.*/ + +a1=@9; a2=@3; @= /*define three strings for merge.*/ + /* [↓] merge two lists, 3s & 9s.*/ + do while a1\=='' & a2\=='' /*process while the lists ¬empty.*/ + x=word(a1,1); y=word(a2,1); if x=='' | y=='' then leave /*empty?*/ + if x= 5 } +end +puts "", "MDR: [n0..n4]", "=== ========" +10.times{|i| puts "%3d: %p" % [i, counter[i].first(5)]} diff --git a/Task/Digital-root-Multiplicative-digital-root/Scala/digital-root-multiplicative-digital-root.scala b/Task/Digital-root-Multiplicative-digital-root/Scala/digital-root-multiplicative-digital-root.scala new file mode 100644 index 0000000000..6f413fa060 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Scala/digital-root-multiplicative-digital-root.scala @@ -0,0 +1,27 @@ +import Stream._ + +object MDR extends App { + + def mdr(x: BigInt, base: Int = 10): (BigInt, Long) = { + def multiplyDigits(x: BigInt): BigInt = ((x.toString(base) map (_.asDigit)) :\ BigInt(1))(_*_) + def loop(p: BigInt, c: Long): (BigInt, Long) = if (p < base) (p, c) else loop(multiplyDigits(p), c+1) + loop(multiplyDigits(x), 1) + } + + printf("%15s\t%10s\t%s\n","Number","MDR","MP") + printf("%15s\t%10s\t%s\n","======","===","==") + Seq[BigInt](123321, 7739, 893, 899998, BigInt("393900588225"), BigInt("999999999999")) foreach {x => + val (s, c) = mdr(x) + printf("%15s\t%10s\t%2s\n",x,s,c) + } + println + + val mdrs: Stream[Int] => Stream[(Int, BigInt)] = i => i map (x => (x, mdr(x)._1)) + + println("MDR: [n0..n4]") + println("==== ========") + ((for {i <- 0 to 9} yield (mdrs(from(0)) take 11112 toList) filter {_._2 == i}) + .map {_ take 5} map {xs => xs map {_._1}}).zipWithIndex + .foreach{p => printf("%3s: [%s]\n",p._2,p._1.mkString(", "))} + +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-1.tcl b/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-1.tcl new file mode 100644 index 0000000000..5b1aff374b --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-1.tcl @@ -0,0 +1,9 @@ +proc mdr {n} { + if {$n < 0 || ![string is integer $n]} { + error "must be an integer" + } + for {set i 0} {$n > 9} {incr i} { + set n [tcl::mathop::* {*}[split $n ""]] + } + return [list $i $n] +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-2.tcl b/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-2.tcl new file mode 100644 index 0000000000..5b98953914 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Tcl/digital-root-multiplicative-digital-root-2.tcl @@ -0,0 +1,16 @@ +puts "Number: MP MDR" +puts [regsub -all . "Number: MP MDR" -] +foreach n {123321 7739 893 899998} { + puts [format "%6d: %2d %3d" $n {*}[mdr $n]] +} +puts "" +# The longEnough variable counts how many roots have at least 5 values accumulated for them +for {set i [set longEnough 0]} {$longEnough < 10} {incr i} { + set root [lindex [mdr $i] 1] + if {[llength [lappend accum($root) $i]] == 5} {incr longEnough} +} +puts "MDR: \[n\u2080\u2026n\u2084\]" +puts [regsub -all . "MDR: \[n\u2080\u2026n\u2084\]" -] +for {set i 0} {$i < 10} {incr i} { + puts [format "%3d: (%s)" $i [join [lrange $accum($i) 0 4] ", "]] +} diff --git a/Task/Draw-a-clock/00DESCRIPTION b/Task/Draw-a-clock/00DESCRIPTION new file mode 100644 index 0000000000..fbd6668161 --- /dev/null +++ b/Task/Draw-a-clock/00DESCRIPTION @@ -0,0 +1,7 @@ +'''Task''': draw a clock. More specific: +:# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g. a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. +:# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. +:# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the framebuffer in a busy loop even if no redraw is needed, which is very undesirable for this task. +:# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. + +Key points: animate simple object; timed event; polling system resources; code clarity. diff --git a/Task/Draw-a-clock/AWK/draw-a-clock.awk b/Task/Draw-a-clock/AWK/draw-a-clock.awk new file mode 100644 index 0000000000..75d8f9b655 --- /dev/null +++ b/Task/Draw-a-clock/AWK/draw-a-clock.awk @@ -0,0 +1,50 @@ +# syntax: GAWK -f DRAW_A_CLOCK.AWK [-v xc="*"] +BEGIN { +# clearscreen_cmd = "clear" ; sleep_cmd = "sleep 1s" # Unix + clearscreen_cmd = "CLS" ; sleep_cmd = "TIMEOUT /T 1 >NUL" # MS-Windows + clock_build_digits() + while (1) { + now = strftime("%H:%M:%S") + t[1] = substr(now,1,1) + t[2] = substr(now,2,1) + t[3] = 10 + t[4] = substr(now,4,1) + t[5] = substr(now,5,1) + t[6] = 10 + t[7] = substr(now,7,1) + t[8] = substr(now,8,1) + if (prev_now != now) { + system(clearscreen_cmd) + for (v=1; v<=8; v++) { + printf("\t") + for (h=1; h<=8; h++) { + printf("%-8s",a[t[h],v]) + } + printf("\n") + } + prev_now = now + } + system(sleep_cmd) + } + exit(0) +} +function clock_build_digits( arr,i,j,x,y) { + arr[1] = " 0000 1 2222 3333 4 555555 6666 777777 8888 9999 " + arr[2] = "0 0 11 2 2 3 3 44 5 6 7 78 8 9 9 " + arr[3] = "0 00 1 1 2 3 4 4 5 6 7 8 8 9 9 :: " + arr[4] = "0 0 0 1 2 333 4 4 555555 66666 7 8888 9 9 :: " + arr[5] = "0 0 0 1 22 3 444444 5 6 6 7 8 8 99999 " + arr[6] = "00 0 1 2 3 4 5 6 6 7 8 8 9 :: " + arr[7] = "0 0 1 2 3 3 4 5 5 6 6 7 8 8 9 :: " + arr[8] = " 0000 1111111222222 3333 4 5555 6666 7 8888 9999 " + for (i=1; i<=8; i++) { + if (xc != "") { + gsub(/[0-9:]/,substr(xc,1,1),arr[i]) # change "0-9" and ":" to substitution character + } + y++ + x = -1 + for (j=1; j<=77; j=j+7) { + a[++x,y] = substr(arr[i],j,7) + } + } +} diff --git a/Task/Draw-a-clock/ActionScript/draw-a-clock.as b/Task/Draw-a-clock/ActionScript/draw-a-clock.as new file mode 100644 index 0000000000..82af87918f --- /dev/null +++ b/Task/Draw-a-clock/ActionScript/draw-a-clock.as @@ -0,0 +1,138 @@ +package { + + import flash.display.Graphics; + import flash.display.Shape; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.TimerEvent; + import flash.utils.Timer; + + public class Clock extends Sprite { + + // Changes of hands (in degrees) per second + private static const HOUR_HAND_CHANGE:Number = 1 / 120; // 360 / (60 * 60 * 12) + private static const MINUTE_HAND_CHANGE:Number = 0.1; // 360 / (60 * 60) + private static const SECOND_HAND_CHANGE:Number = 6; // 360 / 60 + + private var _timer:Timer; + + private var _hHand:Shape; + private var _mHand:Shape; + private var _sHand:Shape; + + public function Clock() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + private function _init(e:Event = null):void { + + var i:uint; + + var base:Shape = new Shape(), hHand:Shape = new Shape(), mHand:Shape = new Shape(); + var sHand:Shape = new Shape(), hub:Shape = new Shape(); + + var size:Number = 500; + var c:Number = size / 2; + x = 30; + y = 30; + + var baseGraphics:Graphics = base.graphics; + + baseGraphics.lineStyle(5, 0xEE0000); + baseGraphics.beginFill(0xFFDDDD); + baseGraphics.drawCircle(c, c, c); + + var uAngle:Number = Math.PI / 30; + + var markerStart:Number = c - 30; + var markerEnd:Number = c - 15; + + var markerX1:Number, markerY1:Number, markerX2:Number, markerY2:Number; + var angle:Number, angleSin:Number, angleCos:Number; + + baseGraphics.endFill(); + + var isMajorMarker:Boolean = true; + + for ( i = 0; i < 60; i++ ) { + // Draw the markers + + angle = uAngle * i; + angleSin = Math.sin(angle); + angleCos = Math.cos(angle); + + markerX1 = c + markerStart * angleCos; + markerY1 = c + markerStart * angleSin; + markerX2 = c + markerEnd * angleCos; + markerY2 = c + markerEnd * angleSin; + + if ( i % 5 == 0 ) { + baseGraphics.lineStyle(3, 0x000080); + isMajorMarker = true; + } + else if ( isMajorMarker ) { + baseGraphics.lineStyle(1, 0x000080); + isMajorMarker = false; + } + + baseGraphics.moveTo(markerX1, markerY1); + baseGraphics.lineTo(markerX2, markerY2); + } + + addChild(base); + + sHand.graphics.lineStyle(2, 0x00BB00); + sHand.graphics.moveTo(0, 0); + sHand.graphics.lineTo(0, 40 - c); + sHand.x = sHand.y = c; + + mHand.graphics.lineStyle(8, 0x444444); + mHand.graphics.moveTo(0, 0); + mHand.graphics.lineTo(0, 50 - c); + mHand.x = mHand.y = c; + + hHand.graphics.lineStyle(8, 0x777777); + hHand.graphics.moveTo(0, 0); + hHand.graphics.lineTo(0, 120 - c); + hHand.x = hHand.y = c; + + hub.graphics.lineStyle(4, 0x664444); + hub.graphics.beginFill(0xCC9999); + hub.graphics.drawCircle(c, c, 5); + + _hHand = hHand; + _mHand = mHand; + _sHand = sHand; + + addChild(mHand); + addChild(hHand); + addChild(sHand); + addChild(hub); + + var date:Date = new Date(); + + // Since millisecond precision is not needed, round it up to the nearest second. + var seconds:Number = date.seconds + ((date.milliseconds > 500) ? 1 : 0); + var minutes:Number = date.minutes + seconds / 60; + var hours:Number = (date.hours + minutes / 60) % 12; + + sHand.rotation = seconds * 6; + mHand.rotation = minutes * 6; + hHand.rotation = hours * 30; + + _timer = new Timer(1000); // 1 second = 1000 ms + _timer.addEventListener(TimerEvent.TIMER, _onTimerTick); + _timer.start(); + + } + + private function _onTimerTick(e:TimerEvent):void { + _hHand.rotation += HOUR_HAND_CHANGE; + _mHand.rotation += MINUTE_HAND_CHANGE; + _sHand.rotation += SECOND_HAND_CHANGE; + } + + } + +} diff --git a/Task/Draw-a-clock/AutoHotkey/draw-a-clock.ahk b/Task/Draw-a-clock/AutoHotkey/draw-a-clock.ahk new file mode 100644 index 0000000000..b9904d27b2 --- /dev/null +++ b/Task/Draw-a-clock/AutoHotkey/draw-a-clock.ahk @@ -0,0 +1,145 @@ +; gdi+ ahk analogue clock example written by derRaphael +; Parts based on examples from Tic's GDI+ Tutorials and of course on his GDIP.ahk + +; This code has been licensed under the terms of EUPL 1.0 + +#SingleInstance, Force +#NoEnv +SetBatchLines, -1 + +; Uncomment if Gdip.ahk is not in your standard library +;#Include, Gdip.ahk + +If !pToken := Gdip_Startup() +{ + MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system + ExitApp +} +OnExit, Exit + +SysGet, MonitorPrimary, MonitorPrimary +SysGet, WA, MonitorWorkArea, %MonitorPrimary% +WAWidth := WARight-WALeft +WAHeight := WABottom-WATop + +Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, 1: Show, NA +hwnd1 := WinExist() + +ClockDiameter := 180 +Width := Height := ClockDiameter + 2 ; make width and height slightly bigger to avoid cut away edges +CenterX := CenterY := floor(ClockDiameter/2) ; Center x + +; Prepare our pGraphic so we have a 'canvas' to work upon + hbm := CreateDIBSection(Width, Height), hdc := CreateCompatibleDC() + obm := SelectObject(hdc, hbm), G := Gdip_GraphicsFromHDC(hdc) + Gdip_SetSmoothingMode(G, 4) + +; Draw outer circle + Diameter := ClockDiameter + pBrush := Gdip_BrushCreateSolid(0x66008000) + Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) + Gdip_DeleteBrush(pBrush) + +; Draw inner circle + Diameter := ceil(ClockDiameter - ClockDiameter*0.08) ; inner circle is 8 % smaller than clock's diameter + pBrush := Gdip_BrushCreateSolid(0x80008000) + Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) + Gdip_DeleteBrush(pBrush) + +; Draw Second Marks + R1 := Diameter//2-1 ; outer position + R2 := Diameter//2-1-ceil(Diameter//2*0.05) ; inner position + Items := 60 ; we have 60 seconds + pPen := Gdip_CreatePen(0xff00a000, floor((ClockDiameter/100)*1.2)) ; 1.2 % of total diameter is our pen width + GoSub, DrawClockMarks + Gdip_DeletePen(pPen) + +; Draw Hour Marks + R1 := Diameter//2-1 ; outer position + R2 := Diameter//2-1-ceil(Diameter//2*0.1) ; inner position + Items := 12 ; we have 12 hours + pPen := Gdip_CreatePen(0xc0008000, ceil((ClockDiameter//100)*2.3)) ; 2.3 % of total diameter is our pen width + GoSub, DrawClockMarks + Gdip_DeletePen(pPen) + + ; The OnMessage will let us drag the clock + OnMessage(0x201, "WM_LBUTTONDOWN") + UpdateLayeredWindow(hwnd1, hdc, WALeft+((WAWidth-Width)//2), WATop+((WAHeight-Height)//2), Width, Height) + SetTimer, sec, 1000 + +sec: +; prepare to empty previously drawn stuff + Gdip_SetSmoothingMode(G, 1) ; turn off aliasing + Gdip_SetCompositingMode(G, 1) ; set to overdraw + +; delete previous graphic and redraw background + Diameter := ceil(ClockDiameter - ClockDiameter*0.18) ; 18 % less than clock's outer diameter + + ; delete whatever has been drawn here + pBrush := Gdip_BrushCreateSolid(0x00000000) ; fully transparent brush 'eraser' + Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) + Gdip_DeleteBrush(pBrush) + + Gdip_SetCompositingMode(G, 0) ; switch off overdraw + pBrush := Gdip_BrushCreateSolid(0x66008000) + Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) + Gdip_DeleteBrush(pBrush) + pBrush := Gdip_BrushCreateSolid(0x80008000) + Gdip_FillEllipse(G, pBrush, CenterX-(Diameter//2), CenterY-(Diameter//2),Diameter, Diameter) + Gdip_DeleteBrush(pBrush) + +; Draw HoursPointer + Gdip_SetSmoothingMode(G, 4) ; turn on antialiasing + t := A_Hour*360//12 + (A_Min*360//60)//12 +90 + R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.5) ; outer position + pPen := Gdip_CreatePen(0xa0008000, floor((ClockDiameter/100)*3.5)) + Gdip_DrawLine(G, pPen, CenterX, CenterY + , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) + , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) + Gdip_DeletePen(pPen) + +; Draw MinutesPointer + t := A_Min*360//60+90 + R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.25) ; outer position + pPen := Gdip_CreatePen(0xa0008000, floor((ClockDiameter/100)*2.7)) + Gdip_DrawLine(G, pPen, CenterX, CenterY + , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) + , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) + Gdip_DeletePen(pPen) + +; Draw SecondsPointer + t := A_Sec*360//60+90 + R1 := ClockDiameter//2-ceil((ClockDiameter//2)*0.2) ; outer position + pPen := Gdip_CreatePen(0xa000FF00, floor((ClockDiameter/100)*1.2)) + Gdip_DrawLine(G, pPen, CenterX, CenterY + , ceil(CenterX - (R1 * Cos(t * Atan(1) * 4 / 180))) + , ceil(CenterY - (R1 * Sin(t * Atan(1) * 4 / 180)))) + Gdip_DeletePen(pPen) + + UpdateLayeredWindow(hwnd1, hdc) ;, xPos, yPos, ClockDiameter, ClockDiameter) +return + +DrawClockMarks: + Loop, % Items + Gdip_DrawLine(G, pPen + , CenterX - ceil(R1 * Cos(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) + , CenterY - ceil(R1 * Sin(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) + , CenterX - ceil(R2 * Cos(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) + , CenterY - ceil(R2 * Sin(((a_index-1)*360//Items) * Atan(1) * 4 / 180)) ) +return + +WM_LBUTTONDOWN() { + PostMessage, 0xA1, 2 + return +} + +esc:: +Exit: + SelectObject(hdc, obm) + DeleteObject(hbm) + DeleteDC(hdc) + Gdip_DeleteGraphics(G) + Gdip_Shutdown(pToken) + ExitApp +Return diff --git a/Task/Draw-a-clock/C++/draw-a-clock.cpp b/Task/Draw-a-clock/C++/draw-a-clock.cpp new file mode 100644 index 0000000000..95f8885642 --- /dev/null +++ b/Task/Draw-a-clock/C++/draw-a-clock.cpp @@ -0,0 +1,330 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20, + MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20; +const float PI = 3.1415926536f; + +//-------------------------------------------------------------------------------------------------- +class vector2 +{ +public: + vector2() { x = y = 0; } + vector2( int a, int b ) { x = a; y = b; } + void set( int a, int b ) { x = a; y = b; } + void rotate( float angle_r ) + { + float _x = static_cast( x ), + _y = static_cast( y ), + s = sinf( angle_r ), + c = cosf( angle_r ), + a = _x * c - _y * s, + b = _x * s + _y * c; + + x = static_cast( a ); + y = static_cast( b ); + } + int x, y; +}; +//-------------------------------------------------------------------------------------------------- +class myBitmap +{ +public: + myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} + ~myBitmap() + { + DeleteObject( pen ); + DeleteObject( brush ); + DeleteDC( hdc ); + DeleteObject( bmp ); + } + + bool create( int w, int h ) + { + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; + + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; + + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + + width = w; height = h; + return true; + } + + void clear( BYTE clr = 0 ) + { + memset( pBits, clr, width * height * sizeof( DWORD ) ); + } + + void setBrushColor( DWORD bClr ) + { + if( brush ) DeleteObject( brush ); + brush = CreateSolidBrush( bClr ); + SelectObject( hdc, brush ); + } + + void setPenColor( DWORD c ) + { + clr = c; + createPen(); + } + + void setPenWidth( int w ) + { + wid = w; + createPen(); + } + + void saveBitmap( string path ) + { + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD wb; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + + HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); + + delete [] dwpBits; + } + + HDC getDC() const { return hdc; } + int getWidth() const { return width; } + int getHeight() const { return height; } + +private: + void createPen() + { + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, wid, clr ); + SelectObject( hdc, pen ); + } + + HBITMAP bmp; + HDC hdc; + HPEN pen; + HBRUSH brush; + void *pBits; + int width, height, wid; + DWORD clr; +}; +//-------------------------------------------------------------------------------------------------- +class clock +{ +public: + clock() + { + _bmp.create( BMP_SIZE, BMP_SIZE ); + _bmp.clear( 100 ); + _bmp.setPenWidth( 2 ); + _ang = DegToRadian( 6 ); + } + + void setNow() + { + GetLocalTime( &_sysTime ); + draw(); + } + + float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } + + void setHWND( HWND hwnd ) { _hwnd = hwnd; } + +private: + void drawTicks( HDC dc ) + { + vector2 line; + _bmp.setPenWidth( 1 ); + for( int x = 0; x < 60; x++ ) + { + line.set( 0, 50 ); + line.rotate( static_cast( x + 30 ) * _ang ); + MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); + LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); + } + + _bmp.setPenWidth( 3 ); + for( int x = 0; x < 60; x += 5 ) + { + line.set( 0, 50 ); + line.rotate( static_cast( x + 30 ) * _ang ); + MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); + LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); + } + } + + void drawHands( HDC dc ) + { + float hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) / 60.0f ); + int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5; + + _bmp.setPenWidth( 3 ); + _bmp.setPenColor( RGB( 0, 0, 255 ) ); + drawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp ); + + _bmp.setPenColor( RGB( 0, 128, 0 ) ); + drawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) ); + + _bmp.setPenWidth( 2 ); + _bmp.setPenColor( RGB( 255, 0, 0 ) ); + drawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) ); + } + + void drawHand( HDC dc, int len, float ang ) + { + vector2 line; + line.set( 0, len ); + line.rotate( ang ); + MoveToEx( dc, CENTER, CENTER, NULL ); + LineTo( dc, line.x + CENTER, line.y + CENTER ); + } + + void draw() + { + HDC dc = _bmp.getDC(); + + _bmp.setBrushColor( RGB( 250, 250, 250 ) ); + Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); + _bmp.setBrushColor( RGB( 230, 230, 230 ) ); + Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 ); + + drawTicks( dc ); + drawHands( dc ); + + _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); + Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 ); + + _wdc = GetDC( _hwnd ); + BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); + ReleaseDC( _hwnd, _wdc ); + } + + myBitmap _bmp; + HWND _hwnd; + HDC _wdc; + SYSTEMTIME _sysTime; + float _ang; +}; +//-------------------------------------------------------------------------------------------------- +class wnd +{ +public: + wnd() { _inst = this; } + int wnd::Run( HINSTANCE hInst ) + { + _hInst = hInst; + _hwnd = InitAll(); + SetTimer( _hwnd, MY_TIMER, 1000, NULL ); + _clock.setHWND( _hwnd ); + + ShowWindow( _hwnd, SW_SHOW ); + UpdateWindow( _hwnd ); + + MSG msg; + ZeroMemory( &msg, sizeof( msg ) ); + while( msg.message != WM_QUIT ) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + } + return UnregisterClass( "_MY_CLOCK_", _hInst ); + } +private: + void wnd::doPaint( HDC dc ) { _clock.setNow(); } + void wnd::doTimer() { _clock.setNow(); } + static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) + { + switch( msg ) + { + case WM_DESTROY: PostQuitMessage( 0 ); break; + case WM_PAINT: + { + PAINTSTRUCT ps; + HDC dc = BeginPaint( hWnd, &ps ); + _inst->doPaint( dc ); + EndPaint( hWnd, &ps ); + return 0; + } + case WM_TIMER: _inst->doTimer(); break; + default: + return DefWindowProc( hWnd, msg, wParam, lParam ); + } + return 0; + } + + HWND InitAll() + { + WNDCLASSEX wcex; + ZeroMemory( &wcex, sizeof( wcex ) ); + wcex.cbSize = sizeof( WNDCLASSEX ); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = ( WNDPROC )WndProc; + wcex.hInstance = _hInst; + wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); + wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); + wcex.lpszClassName = "_MY_CLOCK_"; + + RegisterClassEx( &wcex ); + + RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; + AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); + int w = rc.right - rc.left, h = rc.bottom - rc.top; + return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); + } + + static wnd* _inst; + HINSTANCE _hInst; + HWND _hwnd; + clock _clock; +}; +wnd* wnd::_inst = 0; +//-------------------------------------------------------------------------------------------------- +int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) +{ + wnd myWnd; + return myWnd.Run( hInstance ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Draw-a-clock/C/draw-a-clock.c b/Task/Draw-a-clock/C/draw-a-clock.c new file mode 100644 index 0000000000..197d668b3d --- /dev/null +++ b/Task/Draw-a-clock/C/draw-a-clock.c @@ -0,0 +1,93 @@ +#include +#include +#include +#include +#include + +#define PI 3.14159265 +const char * shades = " .:-*ca&#%@"; + +/* distance of (x, y) from line segment (0, 0)->(x0, y0) */ +double dist(double x, double y, double x0, double y0) { + double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0); + + if (l > 1) { + x -= x0; + y -= y0; + } else if (l >= 0) { + x -= l * x0; + y -= l * y0; + } + return sqrt(x * x + y * y); +} + +enum { sec = 0, min, hur }; // for subscripts + +void draw(int size) +{ +# define for_i for(int i = 0; i < size; i++) +# define for_j for(int j = 0; j < size * 2; j++) + + double angle, cx = size / 2.; + double sx[3], sy[3], sw[3]; + double fade[] = { 1, .35, .35 }; /* opacity of each arm */ + struct timeval tv; + struct tm *t; + + /* set width of each arm */ + sw[sec] = size * .02; + sw[min] = size * .03; + sw[hur] = size * .05; + +every_second: + gettimeofday(&tv, 0); + t = localtime(&tv.tv_sec); + + angle = t->tm_sec * PI / 30; + sy[sec] = -cx * cos(angle); + sx[sec] = cx * sin(angle); + + angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI; + sy[min] = -cx * cos(angle) * .8; + sx[min] = cx * sin(angle) * .8; + + angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI; + sy[hur] = -cx * cos(angle) * .6; + sx[hur] = cx * sin(angle) * .6; + + printf("\033[s"); /* save cursor position */ + for_i { + printf("\033[%d;0H", i); /* goto row i, col 0 */ + double y = i - cx; + for_j { + double x = (j - 2 * cx) / 2; + + int pix = 0; + /* calcs how far the "pixel" is from each arm and set + * shade, with some anti-aliasing. It's ghetto, but much + * easier than a real scanline conversion. + */ + for (int k = hur; k >= sec; k--) { + double d = dist(x, y, sx[k], sy[k]); + if (d < sw[k] - .5) + pix = 10 * fade[k]; + else if (d < sw[k] + .5) + pix = (5 + (sw[k] - d) * 10) * fade[k]; + } + putchar(shades[pix]); + } + } + printf("\033[u"); /* restore cursor pos so you can bg the job -- value unclear */ + + fflush(stdout); + sleep(1); /* sleep 1 can at times miss a second, but will catch up next update */ + goto every_second; +} + +int main(int argc, char *argv[]) +{ + int s; + if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20; + draw(s); + return 0; +} diff --git a/Task/Draw-a-clock/Fortran/draw-a-clock.f b/Task/Draw-a-clock/Fortran/draw-a-clock.f new file mode 100644 index 0000000000..2fe63b916d --- /dev/null +++ b/Task/Draw-a-clock/Fortran/draw-a-clock.f @@ -0,0 +1,116 @@ +!Digital Text implemented as in C version - Anant Dixit (Oct, 2014) +program clock +implicit none +integer :: t(8) +do + call date_and_time(values=t) + call sleep(1) + call system('clear') + call digital_display(t(5),t(6),t(7)) +end do +end program + +subroutine digital_display(H,M,S) +!arguments +integer :: H, M, S +!local +character(len=*), parameter :: nfmt='(A8)', cfmt='(A6)' +character(len=88), parameter :: d1 = ' 00000 1 22222 33333 4 5555555 66666 7777777 88888 99999 ' +character(len=88), parameter :: d2 = '0 0 11 2 2 3 3 44 5 6 6 7 7 8 8 9 9 :: ' +character(len=88), parameter :: d3 = '0 00 1 1 2 3 4 4 5 6 7 8 8 9 9 :: ' +character(len=88), parameter :: d4 = '0 0 0 1 2 3 4 4 5 6 7 8 8 9 9 :: ' +character(len=88), parameter :: d5 = '0 0 0 1 2 333 4444444 555555 666666 7 88888 999999 ' +character(len=88), parameter :: d6 = '0 0 0 1 2 3 4 5 6 6 7 8 8 9 :: ' +character(len=88), parameter :: d7 = '00 0 1 2 3 4 5 6 6 7 8 8 9 :: ' +character(len=88), parameter :: d8 = '0 0 1 2 3 3 4 5 5 6 6 7 8 8 9 9 :: ' +character(len=88), parameter :: d9 = ' 00000 1111111 2222222 33333 4 55555 66666 7 88888 99999 ' +integer :: h1, h2, m1, m2, s1, s2 +h1 = 1+8*floor(dble(H)/10.D0) +h2 = 1+8*modulo(H,10) +m1 = 1+8*floor(dble(M)/10.D0) +m2 = 1+8*modulo(M,10) +s1 = 1+8*floor(dble(S)/10.D0) +s2 = 1+8*modulo(S,10) + +write(*,nfmt,advance='no') d1(h1:h1+8) +write(*,nfmt,advance='no') d1(h2:h2+8) +write(*,cfmt,advance='no') d1(81:88) +write(*,nfmt,advance='no') d1(m1:m1+8) +write(*,nfmt,advance='no') d1(m2:m2+8) +write(*,cfmt,advance='no') d1(81:88) +write(*,nfmt,advance='no') d1(s1:s1+8) +write(*,nfmt) d1(s2:s2+8) + +write(*,nfmt,advance='no') d2(h1:h1+8) +write(*,nfmt,advance='no') d2(h2:h2+8) +write(*,cfmt,advance='no') d2(81:88) +write(*,nfmt,advance='no') d2(m1:m1+8) +write(*,nfmt,advance='no') d2(m2:m2+8) +write(*,cfmt,advance='no') d2(81:88) +write(*,nfmt,advance='no') d2(s1:s1+8) +write(*,nfmt) d2(s2:s2+8) + +write(*,nfmt,advance='no') d3(h1:h1+8) +write(*,nfmt,advance='no') d3(h2:h2+8) +write(*,cfmt,advance='no') d3(81:88) +write(*,nfmt,advance='no') d3(m1:m1+8) +write(*,nfmt,advance='no') d3(m2:m2+8) +write(*,cfmt,advance='no') d3(81:88) +write(*,nfmt,advance='no') d3(s1:s1+8) +write(*,nfmt) d3(s2:s2+8) + +write(*,nfmt,advance='no') d4(h1:h1+8) +write(*,nfmt,advance='no') d4(h2:h2+8) +write(*,cfmt,advance='no') d4(81:88) +write(*,nfmt,advance='no') d4(m1:m1+8) +write(*,nfmt,advance='no') d4(m2:m2+8) +write(*,cfmt,advance='no') d4(81:88) +write(*,nfmt,advance='no') d4(s1:s1+8) +write(*,nfmt) d4(s2:s2+8) + +write(*,nfmt,advance='no') d5(h1:h1+8) +write(*,nfmt,advance='no') d5(h2:h2+8) +write(*,cfmt,advance='no') d5(81:88) +write(*,nfmt,advance='no') d5(m1:m1+8) +write(*,nfmt,advance='no') d5(m2:m2+8) +write(*,cfmt,advance='no') d5(81:88) +write(*,nfmt,advance='no') d5(s1:s1+8) +write(*,nfmt) d5(s2:s2+8) + +write(*,nfmt,advance='no') d6(h1:h1+8) +write(*,nfmt,advance='no') d6(h2:h2+8) +write(*,cfmt,advance='no') d6(81:88) +write(*,nfmt,advance='no') d6(m1:m1+8) +write(*,nfmt,advance='no') d6(m2:m2+8) +write(*,cfmt,advance='no') d6(81:88) +write(*,nfmt,advance='no') d6(s1:s1+8) +write(*,nfmt) d6(s2:s2+8) + +write(*,nfmt,advance='no') d7(h1:h1+8) +write(*,nfmt,advance='no') d7(h2:h2+8) +write(*,cfmt,advance='no') d7(81:88) +write(*,nfmt,advance='no') d7(m1:m1+8) +write(*,nfmt,advance='no') d7(m2:m2+8) +write(*,cfmt,advance='no') d7(81:88) +write(*,nfmt,advance='no') d7(s1:s1+8) +write(*,nfmt) d7(s2:s2+8) + +write(*,nfmt,advance='no') d8(h1:h1+8) +write(*,nfmt,advance='no') d8(h2:h2+8) +write(*,cfmt,advance='no') d8(81:88) +write(*,nfmt,advance='no') d8(m1:m1+8) +write(*,nfmt,advance='no') d8(m2:m2+8) +write(*,cfmt,advance='no') d8(81:88) +write(*,nfmt,advance='no') d8(s1:s1+8) +write(*,nfmt) d8(s2:s2+8) + +write(*,nfmt,advance='no') d9(h1:h1+8) +write(*,nfmt,advance='no') d9(h2:h2+8) +write(*,cfmt,advance='no') d9(81:88) +write(*,nfmt,advance='no') d9(m1:m1+8) +write(*,nfmt,advance='no') d9(m2:m2+8) +write(*,cfmt,advance='no') d9(81:88) +write(*,nfmt,advance='no') d9(s1:s1+8) +write(*,nfmt) d9(s2:s2+8) + +end subroutine diff --git a/Task/Draw-a-clock/GUISS/draw-a-clock.guiss b/Task/Draw-a-clock/GUISS/draw-a-clock.guiss new file mode 100644 index 0000000000..ab5a6bf507 --- /dev/null +++ b/Task/Draw-a-clock/GUISS/draw-a-clock.guiss @@ -0,0 +1 @@ +Start,Programs,Accessories,Analogue Clock diff --git a/Task/Draw-a-clock/Go/draw-a-clock-1.go b/Task/Draw-a-clock/Go/draw-a-clock-1.go new file mode 100644 index 0000000000..3b45a2348f --- /dev/null +++ b/Task/Draw-a-clock/Go/draw-a-clock-1.go @@ -0,0 +1,88 @@ +package main + +import ( + "golang.org/x/net/websocket" + "flag" + "fmt" + "html/template" + "io" + "math" + "net/http" + "time" +) + +var ( + Portnum string + Hostsite string +) + +type PageSettings struct { + Host string + Port string +} + +const ( + Canvaswidth = 512 + Canvasheight = 512 + //color constants + HourColor = "#ff7373" // pinkish + MinuteColor = "#00b7e4" //light blue + SecondColor = "#b58900" //gold +) + +func main() { + flag.StringVar(&Portnum, "Port", "1234", "Port to host server.") + flag.StringVar(&Hostsite, "Site", "localhost", "Site hosting server") + flag.Parse() + http.HandleFunc("/", webhandler) + http.Handle("/ws", websocket.Handler(wshandle)) + err := http.ListenAndServe(Hostsite+":"+Portnum, nil) + if err != nil { + fmt.Println(err) + } + fmt.Println("server running") +} + +func webhandler(w http.ResponseWriter, r *http.Request) { + wsurl := PageSettings{Host: Hostsite, Port: Portnum} + template, _ := template.ParseFiles("clock.html") + template.Execute(w, wsurl) +} + +//Given a websocket connection, +//serves updating time function +func wshandle(ws *websocket.Conn) { + for { + hour, min, sec := time.Now().Clock() + hourx, houry := HourCords(hour, Canvasheight/2) + minx, miny := MinSecCords(min, Canvasheight/2) + secx, secy := MinSecCords(sec, Canvasheight/2) + msg := "CLEAR\n" + msg += fmt.Sprintf("HOUR %d %d %s\n", hourx, houry, HourColor) + msg += fmt.Sprintf("MIN %d %d %s\n", minx, miny, MinuteColor) + msg += fmt.Sprintf("SEC %d %d %s", secx, secy, SecondColor) + io.WriteString(ws, msg) + time.Sleep(time.Second / 60.0) + } +} + +//Given current minute or second time(i.e 30 min, 60 minutes) +//and the radius, returns pair of cords to draw line to +func MinSecCords(ctime int, radius int) (int, int) { + //converts min/sec to angle and then to radians + + theta := ((float64(ctime)*6 - 90) * (math.Pi / 180)) + x := float64(radius) * math.Cos(theta) + y := float64(radius) * math.Sin(theta) + return int(x) + 256, int(y) + 256 +} + +//Given current hour time(i.e. 12, 8) and the radius, +//returns pair of cords to draw line to +func HourCords(ctime int, radius int) (int, int) { + //converts hours to angle and then to radians + theta := ((float64(ctime)*30 - 90) * (math.Pi / 180)) + x := float64(radius) * math.Cos(theta) + y := float64(radius) * math.Sin(theta) + return int(x) + 256, int(y) + 256 +} diff --git a/Task/Draw-a-clock/Go/draw-a-clock-2.go b/Task/Draw-a-clock/Go/draw-a-clock-2.go new file mode 100644 index 0000000000..5dad3296a3 --- /dev/null +++ b/Task/Draw-a-clock/Go/draw-a-clock-2.go @@ -0,0 +1,101 @@ + + +Clock + + + +

Clock

+ + + Sorry, your browser does not support Canvas + + + Sorry, your browser does not support Canvas + + + Sorry, your browser does not support Canvas + + + Sorry, your browser does not support Canvas + + + + diff --git a/Task/Draw-a-clock/Haskell/draw-a-clock.hs b/Task/Draw-a-clock/Haskell/draw-a-clock.hs new file mode 100644 index 0000000000..f7aafccf84 --- /dev/null +++ b/Task/Draw-a-clock/Haskell/draw-a-clock.hs @@ -0,0 +1,114 @@ +import Control.Concurrent +import Data.List +import System.Time + +-- Library: ansi-terminal +import System.Console.ANSI + +number :: (Integral a) => a -> [String] +number 0 = + ["██████" + ,"██ ██" + ,"██ ██" + ,"██ ██" + ,"██████"] +number 1 = + [" ██" + ," ██" + ," ██" + ," ██" + ," ██"] +number 2 = + ["██████" + ," ██" + ,"██████" + ,"██ " + ,"██████"] +number 3 = + ["██████" + ," ██" + ,"██████" + ," ██" + ,"██████"] +number 4 = + ["██ ██" + ,"██ ██" + ,"██████" + ," ██" + ," ██"] +number 5 = + ["██████" + ,"██ " + ,"██████" + ," ██" + ,"██████"] +number 6 = + ["██████" + ,"██ " + ,"██████" + ,"██ ██" + ,"██████"] +number 7 = + ["██████" + ," ██" + ," ██" + ," ██" + ," ██"] +number 8 = + ["██████" + ,"██ ██" + ,"██████" + ,"██ ██" + ,"██████"] +number 9 = + ["██████" + ,"██ ██" + ,"██████" + ," ██" + ,"██████"] + +colon :: [String] +colon = + [" " + ," ██ " + ," " + ," ██ " + ," "] + +newline :: [String] +newline = + ["\n" + ,"\n" + ,"\n" + ,"\n" + ,"\n"] + +space :: [String] +space = + [" " + ," " + ," " + ," " + ," "] + +leadingZero :: (Integral a) => a -> [[String]] +leadingZero num = + let (tens, ones) = divMod num 10 + in [number tens, space, number ones] + +fancyTime :: CalendarTime -> String +fancyTime time = + let hour = leadingZero $ ctHour time + minute = leadingZero $ ctMin time + second = leadingZero $ ctSec time + nums = hour ++ [colon] ++ minute ++ [colon] ++ second ++ [newline] + in concat $ concat $ transpose nums + +main :: IO () +main = do + time <- getClockTime >>= toCalendarTime + putStr $ fancyTime time + threadDelay 1000000 + setCursorColumn 0 + cursorUp 5 + main diff --git a/Task/Draw-a-clock/J/draw-a-clock-1.j b/Task/Draw-a-clock/J/draw-a-clock-1.j new file mode 100644 index 0000000000..27fb13b2e3 --- /dev/null +++ b/Task/Draw-a-clock/J/draw-a-clock-1.j @@ -0,0 +1,20 @@ +Note'rudimentary 4 second clock' + advances an arrow at roughly 1 second intervals, + accurate to the nearest half second. + Please replace draw with a verb demonstrating one of + j's fantastic graphical capabilities. + x draw y + x are session seconds + y is the initial value, session seconds at tic start in the example + tic^:8 seconds'' +) + +delay=:6!:3 NB. "sleep" +seconds=:6!:1 NB. session time in seconds +Pass_y =: (]`[`)(`:6) NB. adverb that evaluates the verb and returns y + +round =: [: <. 0.5&+ NB. round to nearest integer +PICTURES=: u:16b2190+i.4 NB. whoot arrows +draw=: [: smoutput PICTURES ((|~ #)~ { [) [: round - + +tic=: (>. draw Pass_y <.) ([: seconds 0 $ delay@1:) diff --git a/Task/Draw-a-clock/J/draw-a-clock-2.j b/Task/Draw-a-clock/J/draw-a-clock-2.j new file mode 100644 index 0000000000..e45a05fa41 --- /dev/null +++ b/Task/Draw-a-clock/J/draw-a-clock-2.j @@ -0,0 +1,7 @@ +require'plot' +N=:0.01*i.629 +O=: [: j./ 1 2 o./ ] + +delay=:6!:3 NB. "sleep" +clock=: [: plot (O N),N*/~0.07 0.11 0.15(*O) 2r24p1 2r60p1 2r60p1*_3{.6!:0 bind '' +delay@1:@clock^:9e99'' diff --git a/Task/Draw-a-clock/Java/draw-a-clock.java b/Task/Draw-a-clock/Java/draw-a-clock.java new file mode 100644 index 0000000000..b48704a0d2 --- /dev/null +++ b/Task/Draw-a-clock/Java/draw-a-clock.java @@ -0,0 +1,79 @@ +import java.awt.*; +import java.awt.event.*; +import java.util.Calendar; +import javax.swing.*; + +class Clock extends JPanel { + + final float degrees06 = (float) Math.toRadians(6); + final float degrees30 = degrees06 * 5; + final float degrees90 = degrees30 * 3; + + final int size = 550; + final int spacing = 20; + final int diameter = size - 2 * spacing; + final int x = diameter / 2 + spacing; + final int y = diameter / 2 + spacing; + + public Clock() { + setPreferredSize(new Dimension(size, size)); + setBackground(Color.white); + + new Timer(1000, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + repaint(); + } + }).start(); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + g.setColor(Color.black); + g.drawOval(spacing, spacing, diameter, diameter); + + Calendar date = Calendar.getInstance(); + int hours = date.get(Calendar.HOUR); + int minutes = date.get(Calendar.MINUTE); + int seconds = date.get(Calendar.SECOND); + + float angle = degrees90 - (degrees06 * seconds); + drawHand(g, angle, diameter / 2 - 30, Color.red); + + float minsecs = (minutes + seconds / 60.0F); + angle = degrees90 - (degrees06 * minsecs); + drawHand(g, angle, diameter / 3 + 10, Color.black); + + float hourmins = (hours + minsecs / 60.0F); + angle = degrees90 - (degrees30 * hourmins); + drawHand(g, angle, diameter / 4 + 10, Color.black); + } + + private void drawHand(Graphics2D g, float angle, int radius, Color color) { + int x2 = x + (int) (radius * Math.cos(angle)); + int y2 = y + (int) (radius * Math.sin(-angle)); // flip y-axis + g.setColor(color); + g.drawLine(x, y, x2, y2); + } + + 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("Clock"); + f.setResizable(false); + f.add(new Clock(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + } + }); + } +} diff --git a/Task/Draw-a-clock/JavaScript/draw-a-clock.js b/Task/Draw-a-clock/JavaScript/draw-a-clock.js new file mode 100644 index 0000000000..4a3b8b27f0 --- /dev/null +++ b/Task/Draw-a-clock/JavaScript/draw-a-clock.js @@ -0,0 +1,47 @@ +var sec_old = 0; +function update_clock() { + var t = new Date(); + var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; + if (arms[2] == sec_old) return; + sec_old = arms[2]; + + var c = document.getElementById('clock'); + var ctx = c.getContext('2d'); + ctx.fillStyle = "rgb(0,200,200)"; + ctx.fillRect(0, 0, c.width, c.height); + ctx.fillStyle = "white"; + ctx.fillRect(3, 3, c.width - 6, c.height - 6); + ctx.lineCap = 'round'; + + var orig = { x: c.width / 2, y: c.height / 2 }; + arms[1] += arms[2] / 60; + arms[0] += arms[1] / 60; + draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, "green"); + draw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, "navy"); + draw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, "maroon"); +} + +function draw_arm(ctx, orig, deg, len, w, style) +{ + ctx.save(); + ctx.lineWidth = w; + ctx.lineCap = 'round'; + ctx.translate(orig.x, orig.y); + ctx.rotate((deg - 90) * Math.PI / 180); + ctx.strokeStyle = style; + ctx.beginPath(); + ctx.moveTo(-len / 10, 0); + ctx.lineTo(len, 0); + ctx.stroke(); + ctx.restore(); +} + +function init_clock() { + var clock = document.createElement('canvas'); + clock.width = 100; + clock.height = 100; + clock.id = "clock"; + document.body.appendChild(clock); + + window.setInterval(update_clock, 200); +} diff --git a/Task/Draw-a-clock/Liberty-BASIC/draw-a-clock.liberty b/Task/Draw-a-clock/Liberty-BASIC/draw-a-clock.liberty new file mode 100644 index 0000000000..15423e6760 --- /dev/null +++ b/Task/Draw-a-clock/Liberty-BASIC/draw-a-clock.liberty @@ -0,0 +1,39 @@ + WindowWidth =120 + WindowHeight =144 + nomainwin + + open "Clock" for graphics_nsb_nf as #clock + #clock "trapclose [exit]" + #clock "fill white" + for angle =0 to 330 step 30 + #clock "up ; home ; north ; turn "; angle + #clock "go 40 ; down ; go 5" + next angle + + #clock "flush" + + timer 1000, [display] + wait + +[display] ' called only when seconds have changed + time$ =time$() + seconds =val( right$( time$, 2)) + ' delete the last drawn segment, if there is one + if segId >2 then #clock "delsegment "; segId -1 + ' center the turtle + #clock "up ; home ; down ; north" + ' erase each hand if its position has changed + if oldSeconds <>seconds then #clock, "size 1 ; color white ; turn "; oldSeconds *6 ; " ; go 38 ; home ; color black ; north" : oldSeconds =seconds + ' redraw all three hands, second hand first + #clock "size 1 ; turn "; seconds * 6 ; " ; go 38" + ' flush to end segment, then get the next segment id # + #clock "flush" + #clock "segment" + input #clock, segId + + wait + +[exit] + close #clock + + end diff --git a/Task/Draw-a-clock/Locomotive-Basic/draw-a-clock.locomotive b/Task/Draw-a-clock/Locomotive-Basic/draw-a-clock.locomotive new file mode 100644 index 0000000000..9b62fbda68 --- /dev/null +++ b/Task/Draw-a-clock/Locomotive-Basic/draw-a-clock.locomotive @@ -0,0 +1,46 @@ +10 mode 1:defint a-y:deg +20 input "Current time (HH:MM)";t$ +30 h=val(mid$(t$,1,2)) +40 m=val(mid$(t$,4,2)) +50 cls +60 r=150:s=-1 +70 ph=0:pm=0 +80 origin 320,200 +90 for a=0 to 360 step 6 +100 if a mod 30>0 then z=.9 else z=.8 +110 move z*r*sin(a),z*r*cos(a) +120 draw r*sin(a),r*cos(a) +130 next +140 move 0,r +150 for a=0 to 360 step 6 +160 draw r*sin(a),r*cos(a) +170 next +180 every 50 gosub 220 +190 ' ENDLESS_LOOP +200 goto 200 +210 ' NEW_SEC +220 s=s+1 +230 if s=60 then s=0:m=m+1 +240 if m=60 then m=0:h=h+1 +250 if h=24 then h=0 +260 if s=0 then gosub 300 +270 if s>0 then gosub 420 +280 return +290 ' DRAW_ALL +300 locate 1,1 +310 print using "##";h; +320 print ":"; +330 print using "##";m; +340 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),0,0 +350 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),0,0 +360 frame:move 0,0:draw .8*r*sin(6*59),.8*r*cos(6*59),0,0 +370 pm=6*m +380 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),1,0 +390 ph=30*h+.5*m +400 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),1,0 +410 ' DRAW_SEC +420 a=6*s +430 ' uses "frame" and XOR ink mode for drawing -- requires BASIC 1.1 +440 if a>0 then frame:move 0,0:draw .8*r*sin(a-6),.8*r*cos(a-6),3,1 +450 frame:move 0,0:draw .8*r*sin(a),.8*r*cos(a),3,1 +460 return diff --git a/Task/Draw-a-clock/MATLAB/draw-a-clock.m b/Task/Draw-a-clock/MATLAB/draw-a-clock.m new file mode 100644 index 0000000000..7a59b63dbd --- /dev/null +++ b/Task/Draw-a-clock/MATLAB/draw-a-clock.m @@ -0,0 +1,6 @@ + u = [0:360]*pi/180; + while(1) + s = mod(now*60*24,1)*2*pi; + plot([0,sin(s)],[0,cos(s)],'-',sin(u),cos(u),'k-'); + pause(1); + end; diff --git a/Task/Draw-a-clock/Mathematica/draw-a-clock.math b/Task/Draw-a-clock/Mathematica/draw-a-clock.math new file mode 100644 index 0000000000..b2fff7ef18 --- /dev/null +++ b/Task/Draw-a-clock/Mathematica/draw-a-clock.math @@ -0,0 +1,14 @@ +makeHand[fl_, bl_, fw_, bw_] := Polygon[{{-bw, -bl}, {bw, -bl}, {fw, fl}, {0, fl + 8 fw}, {-fw, fl}}/9]; + +hourHand = makeHand[5, 5/3, .1, .3];minuteHand = makeHand[7, 7/3, .1, .3]; +secondHand = {Red, EdgeForm[Black], makeHand[7, 7/3, .1/2, .3/2]}; + +Graphics[{ + {Thickness[.03], Circle[]},(* Rim *) + {Thickness[.003], Table[Line[{.9 {Cos[a], Sin[a]}, .95 {Cos[a], Sin[a]}}], {a, 0, 2 \[Pi], 2 \[Pi]/60}]}, (* Thin ticks *) + {Thickness[.01], Table[Line[{.9 {Cos[a], Sin[a]}, .95 {Cos[a], Sin[a]}}], {a, 0, 2 \[Pi], 2 \[Pi]/12}]}, (* Thick ticks *) + Style[Table[Text[i, .77 {Cos[-i \[Pi]/6 + \[Pi]/2], Sin[-i \[Pi]/6 + \[Pi]/2]}], {i, 1, 12}], FontFamily -> "Helvetica", FontSize -> 36], (* Numbers *) + Rotate[hourHand, Dynamic[Refresh[-30 Mod[AbsoluteTime[]/3600, 60] \[Degree], UpdateInterval -> 60]], {0, 0}], + Rotate[minuteHand, Dynamic[Refresh[-6 Mod[AbsoluteTime[]/60, 60] \[Degree], UpdateInterval -> 1]], {0, 0}], + Rotate[secondHand, Dynamic[Refresh[-6 Mod[AbsoluteTime[], 60] \[Degree], UpdateInterval -> 1/20]], {0, 0}] + }] diff --git a/Task/Draw-a-clock/NetRexx/draw-a-clock.netrexx b/Task/Draw-a-clock/NetRexx/draw-a-clock.netrexx new file mode 100644 index 0000000000..376123bb25 --- /dev/null +++ b/Task/Draw-a-clock/NetRexx/draw-a-clock.netrexx @@ -0,0 +1,102 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import javax.swing.Timer + +-- .+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 +class RClockSwing public extends JFrame + -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + properties constant + K_TITLE = String "Clock" + isTrue = boolean (1 == 1) + isFalse = \isTrue + properties inheritable + content = Container + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method RClockSwing() public + this(K_TITLE) + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method RClockSwing(title = String) public + super(title) + initFrame() + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method initFrame() private + content = getContentPane() + content.setLayout(BorderLayout()) + content.add(RClockSwing.Panel(), BorderLayout.CENTER) + setResizable(isFalse) + pack() + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method main(args = String[]) public static + clockFace = JFrame + clockFace = RClockSwing() + clockFace.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) + clockFace.setVisible(isTrue) + return + +--..+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 +class RClockSwing.Panel shared extends JPanel implements ActionListener + properties constant + degrees450 = double Math.PI * 2.5 + degrees006 = double Math.PI / 30.0 + degrees030 = double degrees006 * 5 + size = int 350 + spacing = int 10 + diameter = int size - 2 * spacing + x1 = int diameter / 2 + spacing + y1 = int diameter / 2 + spacing + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method Panel() public + super() + initPanel() + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method initPanel() public + setPreferredSize(Dimension(size, size)) + setBackground(Color.WHITE) + ptimer = Timer(1000, this) + ptimer.start() + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method paintComponent(gr = Graphics) public + super.paintComponent(gr) + g2 = Graphics2D gr + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + gr.setColor(Color.black) + gr.drawOval(spacing, spacing, diameter, diameter) + cdate = Calendar.getInstance() + hours = cdate.get(Calendar.HOUR) + minutes = cdate.get(Calendar.MINUTE) + seconds = cdate.get(Calendar.SECOND) + angle = double degrees450 - (degrees006 * seconds) + drawHand(gr, angle, int (diameter / 2 - 10), Color.red) + minsecs = double (minutes + seconds / 60.0) + angle = degrees450 - (degrees006 * minsecs) + drawHand(gr, angle, int (diameter / 3), Color.black) + hourmins = double (hours + minsecs / 60.0) + angle = degrees450 - (degrees030 * hourmins) + drawHand(gr, angle, int (diameter / 4), Color.black) + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method drawHand(gr = Graphics, angle = double, radius = int, color = Color) public + x2 = x1 + (int (radius * Math.cos(angle))) + y2 = y1 + (int (radius * Math.sin(-angle))) + gr.setColor(color) + gr.drawLine(x1, y1, x2, y2) + return + + -- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ + method actionPerformed(evt = ActionEvent) public + repaint() + return diff --git a/Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml b/Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml new file mode 100644 index 0000000000..dc48379100 --- /dev/null +++ b/Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml @@ -0,0 +1,65 @@ +#!/usr/bin/env ocaml +#load "unix.cma" +#load "graphics.cma" +open Graphics + +let pi = 4.0 *. atan 1.0 +let angle v max = float v /. max *. 2.0 *. pi + +let () = + open_graph ""; + set_window_title "OCaml Clock"; + resize_window 256 256; + auto_synchronize false; + let w = size_x () + and h = size_y () in + let rec loop () = + clear_graph (); + + let point radius r a = + let x = int_of_float (radius *. sin a) + and y = int_of_float (radius *. cos a) in + fill_circle (w/2+x) (h/2+y) r; + in + set_color (rgb 192 192 192); + point 84.0 8 0.0; + point 84.0 8 (angle 90 360.0); + point 84.0 8 (angle 180 360.0); + point 84.0 8 (angle 270 360.0); + set_color (rgb 224 224 224); + point 84.0 6 (angle 30 360.0); + point 84.0 6 (angle 60 360.0); + point 84.0 6 (angle 120 360.0); + point 84.0 6 (angle 150 360.0); + point 84.0 6 (angle 210 360.0); + point 84.0 6 (angle 240 360.0); + point 84.0 6 (angle 300 360.0); + point 84.0 6 (angle 330 360.0); + + set_line_width 9; + set_color (rgb 192 192 192); + draw_circle (w/2) (h/2) 100; + + let tm = Unix.localtime (Unix.gettimeofday ()) in + let sec = angle tm.Unix.tm_sec 60.0 in + let min = angle tm.Unix.tm_min 60.0 in + let hour = angle (tm.Unix.tm_hour * 60 + tm.Unix.tm_min) (24.0 *. 60.0) in + let hour = hour *. 2.0 in + + let hand t radius width color = + let x = int_of_float (radius *. sin t) + and y = int_of_float (radius *. cos t) in + set_line_width width; + set_color color; + moveto (w/2) (h/2); rlineto x y; + in + hand sec 90.0 2 (rgb 0 128 255); + hand min 82.0 4 (rgb 0 0 128); + hand hour 72.0 6 (rgb 255 0 128); + + synchronize (); + Unix.sleep 1; + loop () + in + try loop () + with _ -> close_graph () diff --git a/Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml b/Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml new file mode 100644 index 0000000000..9c97082748 --- /dev/null +++ b/Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml @@ -0,0 +1,66 @@ +let pi = 4.0 *. atan 1.0 +let angle v max = float v /. max *. 2.0 *. pi + +let draw area _ = + let cr = Cairo_lablgtk.create area#misc#window in + let { Gtk.width = width; Gtk.height = height } = area#misc#allocation in + let scale p = float (min width height) *. 0.5 *. p in + let center_x, center_y = float width /. 2.0, float height /. 2.0 in + let invert_y y = float height -. y in + + Cairo.set_source_rgb cr 0.8 0.8 0.8; + Cairo.paint cr; (* background *) + + Cairo.set_source_rgb cr 1.0 1.0 1.0; + + Cairo.arc cr center_x center_y (scale 0.9) 0.0 (2.0 *. pi); + Cairo.set_line_width cr (scale 0.02); + Cairo.stroke cr; + + let point a = + let radius = (scale 0.9) in + let x = radius *. sin a + and y = radius *. cos a in + let r = scale 0.04 in + Cairo.arc cr (center_x +. x) (invert_y (center_y +. y)) r 0.0 (2.0 *. pi); + Cairo.fill cr; + in + for i = 0 to pred 12 do + point (angle (i * 30) 360.0) + done; + + let tm = Unix.localtime (Unix.gettimeofday ()) in + let sec = angle tm.Unix.tm_sec 60.0 in + let min = angle tm.Unix.tm_min 60.0 in + let hour = angle (tm.Unix.tm_hour * 60 + tm.Unix.tm_min) (12.0 *. 60.0) in + + Cairo.set_line_cap cr Cairo.LINE_CAP_ROUND; + + let hand t radius lwidth (r, g, b) = + let x = radius *. sin t + and y = radius *. cos t in + Cairo.set_line_width cr (scale lwidth); + Cairo.move_to cr center_x center_y; + Cairo.line_to cr (center_x +. x) (invert_y (center_y +. y)); + Cairo.set_source_rgb cr r g b; + Cairo.stroke cr; + in + hand sec (scale 0.9) 0.04 (0.0, 0.5, 1.0); + hand min (scale 0.7) 0.06 (0.0, 0.0, 0.5); + hand hour (scale 0.6) 0.09 (1.0, 0.0, 0.5); + true + +let animate area = + ignore (GMain.Timeout.add 200 (fun () -> + GtkBase.Widget.queue_draw area#as_widget; true)) + +let () = + let w = GWindow.window ~title:"OCaml GtkCairo Clock" () in + ignore (w#connect#destroy GMain.quit); + let f = GBin.frame ~shadow_type:`IN ~packing:w#add () in + let area = GMisc.drawing_area ~width:200 ~height:200 ~packing:f#add () in + area#misc#set_double_buffered true; + ignore (area#event#connect#expose (draw area)); + animate area; + w#show (); + GMain.main () diff --git a/Task/Draw-a-clock/Perl-6/draw-a-clock.pl6 b/Task/Draw-a-clock/Perl-6/draw-a-clock.pl6 new file mode 100644 index 0000000000..0a0a665d24 --- /dev/null +++ b/Task/Draw-a-clock/Perl-6/draw-a-clock.pl6 @@ -0,0 +1,17 @@ +my ($rows,$cols) = qx/stty size/.words; +my $v = floor $rows / 2; +my $h = floor $cols / 2 - 16; + +my @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>; +my @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>; + +loop { + my @x = DateTime.now.Str.substr(11,8).ords X- ord('0'); + print "\e[H\e[J"; + print "\e[$v;{$h}H"; + print ~@t[@x]; + print "\e[{$v+1};{$h}H"; + print ~@b[@x]; + print "\e[H"; + sleep 1; +} diff --git a/Task/Draw-a-clock/Perl/draw-a-clock.pl b/Task/Draw-a-clock/Perl/draw-a-clock.pl new file mode 100644 index 0000000000..df549b3b3c --- /dev/null +++ b/Task/Draw-a-clock/Perl/draw-a-clock.pl @@ -0,0 +1,29 @@ +use utf8; # interpret source code as UTF8 +binmode STDOUT, ':utf8'; # allow printing wide chars without warning +$|++; # disable output buffering + +my ($rows, $cols) = split /\s+/, `stty size`; +my $x = int($rows / 2 - 1); +my $y = int($cols / 2 - 16); + +my @chars = map {[ /(...)/g ]} + ("┌─┐ ╷╶─┐╶─┐╷ ╷┌─╴┌─╴╶─┐┌─┐┌─┐ ", + "│ │ │┌─┘╶─┤└─┤└─┐├─┐ │├─┤└─┤ : ", + "└─┘ ╵└─╴╶─┘ ╵╶─┘└─┘ ╵└─┘╶─┘ "); + +while (1) { + my @indices = map { ord($_) - ord('0') } split //, + sprintf("%02d:%02d:%02d", (localtime(time))[2,1,0]); + + clear(); + for (0 .. $#chars) { + position($x + $_, $y); + print "@{$chars[$_]}[@indices]"; + } + position(1, 1); + + sleep 1; +} + +sub clear { print "\e[H\e[J" } +sub position { printf "\e[%d;%dH", shift, shift } diff --git a/Task/Draw-a-clock/PicoLisp/draw-a-clock.l b/Task/Draw-a-clock/PicoLisp/draw-a-clock.l new file mode 100644 index 0000000000..1c21905fdb --- /dev/null +++ b/Task/Draw-a-clock/PicoLisp/draw-a-clock.l @@ -0,0 +1,48 @@ +(de draw Lst + (for L Lst + (for X L + (cond + ((num? X) (space X)) + ((sym? X) (prin X)) + (T (do (car X) (prin (cdr X)))) ) ) + (prinl) ) ) + +(de bigBox (N) + (do 2 + (prin "|") + (for I 4 + (prin (if (> I N) " |" " ======== |")) ) + (prinl) ) ) + +(call 'clear) # Clear screen +(call "tput" "civis") # Set cursor invisible + +(push '*Bye '(call "tput" "cnorm")) # Set cursor visible on exit + +(loop + (call "tput" "cup" 0 0) # Cursor to top left + (let Time (time (time)) + (draw (20 (5 . _)) (19 / 5 \\)) + (if (onOff (NIL)) + (draw (18 / 7 \\) (18 \\ 7 /)) + (draw (18 / 2 (3 . "#") 2 \\) (18 \\ 2 (3 . "#") 2 /)) ) + (draw + (19 \\ (5 . _) /) + (+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +) ) + (bigBox (/ (car Time) 5)) + (draw (+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +)) + (bigBox (% (car Time) 5)) + (draw (+ (43 . -) +)) + (do 2 + (prin "|") + (for I `(range 5 55 5) + (prin + (cond + ((> I (cadr Time)) " |") + ((=0 (% I 3)) " # |") + (T " = |") ) ) ) + (prinl) ) + (draw (+ (43 . -) +)) + (bigBox (% (cadr Time) 5)) + (draw (+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +)) ) + (wait 1000) ) diff --git a/Task/Draw-a-clock/PureBasic/draw-a-clock.purebasic b/Task/Draw-a-clock/PureBasic/draw-a-clock.purebasic new file mode 100644 index 0000000000..ef68d11705 --- /dev/null +++ b/Task/Draw-a-clock/PureBasic/draw-a-clock.purebasic @@ -0,0 +1,51 @@ +#MiddleX = 90 + 1 ;x,y must be odd numbers, minimum width is 67 +#MiddleY = #MiddleX +#len_sh = (#MiddleX - 8) * 0.97 ;length of second-hand +#len_mh = (#MiddleX - 8) * 0.88 ;length of minute-hand +#len_hh = (#MiddleX - 8) * 0.66 ;length of hour-hand +#clockFace_img = 0 +#clock_gad = 0 +#clock_win = 0 + +Define cx = #MiddleX, cy = #MiddleY, i, ri.f +Define c_gray = RGB($CC, $CC, $CC), c_mgray = RGB($99, $99, $99) +Define c_white = RGB(255, 255, 255), c_black =RGB(0, 0, 0) +Define c_red = RGB(255, 0, 0), c_blue = RGB(0, 0, 255) +Define c_dcyan = RGB($27, $BC, $D8), c_lgreen = RGB($60, $E0, $9) +Define c_yellow = RGB($F4, $D5, $0B) + +CreateImage(#clockFace_img, cx * 2 - 1, cy * 2 - 1) +StartDrawing(ImageOutput(#clockFace_img)) + Box(0, 0, cx * 2 - 1, cy * 2 - 1, c_mgray) + Circle(cx, cy, cx - 2, c_dcyan) + For i = 0 To 359 Step 30 + ri = Radian(i) + Circle(cx + Sin(ri) * (cx - 5), cy + Cos(ri) * (cx - 5), 3, c_gray) + Next +StopDrawing() +OpenWindow(#clock_win, 0, 0, cx * 2, cy * 2, "Clock") +ImageGadget(#clock_gad, 0, 0, cx * 2, cy * 2, ImageID(#clockFace_img)) + +Define x, y, rad_s.f, rad_m.f, rad_h.f, t$ +Repeat + event = WaitWindowEvent(25) + If event = 0 + rad_s = Radian(360 - (Second(Date()) * 6) + 180) + rad_m = Radian(360 - (Minute(Date()) * 6) + 180) + rad_h = Radian(360 - (((Hour(Date()) - 1) * 30) + 180) - (Minute(Date()) / 2)) + + StartDrawing(ImageOutput(#clockFace_img)) + Circle(cx, cy, cx - 8, c_lgreen) + t$ = FormatDate("%mm-%dd-%yyyy", Date()) + x = cx - (TextWidth(t$) + 2) / 2 + y = (cy - (TextHeight(t$) + 2) - 4) / 2 + Box(x, y, TextWidth(t$) + 2, TextHeight(t$) + 2, c_black) + DrawText(x + 2, y + 2, t$, c_black, c_yellow) + LineXY(cx, cy, cx + Sin(rad_s) * #len_sh, cy + Cos(rad_s) * #len_sh, c_white) + LineXY(cx, cy, cx + Sin(rad_m) * #len_mh, cy + Cos(rad_m) * #len_mh, c_red) + LineXY(cx, cy, cx + Sin(rad_h) * #len_hh, cy + Cos(rad_h) * #len_hh, c_black) + Circle(cx, cy, 4, c_blue) + StopDrawing() + SetGadgetState(#clock_gad, ImageID(#clockFace_img)) + EndIf +Until event = #PB_Event_CloseWindow diff --git a/Task/Draw-a-clock/Python/draw-a-clock.py b/Task/Draw-a-clock/Python/draw-a-clock.py new file mode 100644 index 0000000000..956d785883 --- /dev/null +++ b/Task/Draw-a-clock/Python/draw-a-clock.py @@ -0,0 +1,31 @@ +import time + +def chunks(l, n=5): + return [l[i:i+n] for i in range(0, len(l), n)] + +def binary(n, digits=8): + n=int(n) + return '{0:0{1}b}'.format(n, digits) + +def secs(n): + n=int(n) + h='x' * n + return "|".join(chunks(h)) + +def bin_bit(h): + h=h.replace("1","x") + h=h.replace("0"," ") + return "|".join(list(h)) + + +x=str(time.ctime()).split() +y=x[3].split(":") + +s=y[-1] +y=map(binary,y[:-1]) + +print bin_bit(y[0]) +print +print bin_bit(y[1]) +print +print secs(s) diff --git a/Task/Draw-a-clock/README b/Task/Draw-a-clock/README new file mode 100644 index 0000000000..3a0ce30887 --- /dev/null +++ b/Task/Draw-a-clock/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Draw_a_clock diff --git a/Task/Draw-a-clock/REXX/draw-a-clock.rexx b/Task/Draw-a-clock/REXX/draw-a-clock.rexx new file mode 100644 index 0000000000..3a93a28628 --- /dev/null +++ b/Task/Draw-a-clock/REXX/draw-a-clock.rexx @@ -0,0 +1,59 @@ +/**/trace o;parse arg !;if !all(arg()) then exit;if !cms then address '' +signal on halt; signal on novalue; signal on syntax +parse var ! ops; ops = space(ops) /*obtain command line options. */ +@abc = 'abcdefghijklmnopqrstuvwxyz' /*alphabet str used by ABB/ABBN. */ +blinkSecs = 1 +creep = 1 +tops = '.C=blue .BC=░ .BS=1 .BLOCK=12' + + do while ops\==''; parse var ops _1 2 1 _ . 1 y ops; upper _ + select + when _==',' then nop + when _1=='.' & pos("=",_)\==0 then tops=tops y + when abbn('BLINKSECs') then blinksecs=no() + when abbn('CREEPs') then creep=no() + otherwise call er 55,y + end /*select*/ + end /*while ops¬==''*/ + +if \!pcrexx then blinkSecs=0 /*if ¬PC/REXX, turn off BLINKSECS*/ +tops=space(tops) /*elide extraneous TOPS blanks.*/ +parse value scrsize() with sd sw . /*get the term screens dimensions*/ +oldTime= + do until queued()\==0 + ct=time(); mn=substr(ct,4,2); ss=right(ct,2); i_=0; p_=0 + call blinksec + if ct==oldTime then if !cms then 'CP SLEEP'; else call delay 1 + + if creep then do; p_ = 3 + right(mn,1) + if sd>26 then p_ = p_ + left(mn,1) + if sd>33 then p_ = p_ + left(mn,1) + if sd>44 then p_ = p_ + left(mn,1) +right(mn,1) + end + _p=-p_ + i_=2+left(ct,1); ctt=left(ct,5); if sw>108 then ctt=ct + r=$t('.P='_p ".I="i_ tops ctt); if r\==0 then leave + oldTime=time() + end /*forever*/ +exit /*stick a fork in it, we're done.*/ +/*═════════════════════════════general 1-line subs════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/ +!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;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';call !rex;return +!var: call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env)) +$t: !call=']$T';call "$T" arg(1);!call=;return result +abb: arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) +abbl: return verify(arg(1)'a',@abc,'M')-1 +abbn: parse arg abbn;return abb(abbn)|abb('NO'abbn) +blinksec: if \blinksecs then return;bsec=' ';ss2=right(ss,2);if sw<=80 then bsec=copies(' ',2+ss2) ss2;call scrwrite 1+right(mn,1),1,bsec,,,1;call cursor sd-right(mn,1),sw-length(bsec);return +er: parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result +err: call er '-'arg(1),arg(2);return '' +erx: call er '-'arg(1),arg(2);exit '' +halt: call er .1 +no: if arg(1)\=='' then call er 01,arg(2);return left(_,2)\=='NO' +novalue:!sigl=sigl;call er 17,!fid(2) !fid(3) !sigl condition('D') sourceline(!sigl) +p: return word(arg(1),1) +syntax:!sigl=sigl;call er 13,!fid(2) !fid(3) !sigl !cal() condition('D') sourceline(!sigl) diff --git a/Task/Draw-a-clock/Racket/draw-a-clock.rkt b/Task/Draw-a-clock/Racket/draw-a-clock.rkt new file mode 100644 index 0000000000..9bd1aea190 --- /dev/null +++ b/Task/Draw-a-clock/Racket/draw-a-clock.rkt @@ -0,0 +1,55 @@ +#lang racket/gui + +(require racket/date slideshow/pict) + +(define (clock h m s [r 100]) + (define (draw-hand length angle + #:width [width 1] + #:color [color "black"]) + (dc (λ (dc dx dy) + (define old-pen (send dc get-pen)) + (send dc set-pen (new pen% [width width] [color color])) + (send dc draw-line + (+ dx r) (+ dy r) + (+ dx r (* length (sin angle))) + (+ dy r (* length (cos angle)))) + (send dc set-pen old-pen)) + (* 2 r) (* 2 r))) + (cc-superimpose + (for/fold ([pict (circle (* 2 r))]) + ([angle (in-range 0 (* 2 pi) (/ pi 6))] + [hour (cons 12 (range 1 12))]) + (define angle* angle) + (define r* (* r 0.8)) + (define txt (text (number->string hour) '(bold . "Helvetica"))) + (define x (- (* r* (sin angle*)) (/ (pict-width txt) 2))) + (define y (+ (* r* (cos angle*)) (/ (pict-height txt) 2))) + (pin-over pict (+ r x) (- r y) txt)) + (draw-hand (* r 0.7) (+ pi (* (modulo h 12) (- (/ pi 6)))) + #:width 3) + (draw-hand (* r 0.5) (+ pi (* m (- (/ pi 30)))) + #:width 2) + (draw-hand (* r 0.7) (+ pi (* s (- (/ pi 30)))) + #:color "red") + (disk (* r 0.1)))) + +(define f (new frame% [label "Clock"] [width 300] [height 300])) + +(define c + (new canvas% + [parent f] + [paint-callback + (λ (c dc) + (define date (current-date)) + (draw-pict (clock (date-hour date) + (date-minute date) + (date-second date) + (/ (send c get-width) 2)) + dc 0 0))])) + +(define t + (new timer% + [notify-callback (λ () (send c refresh-now))] + [interval 1000])) + +(send f show #t) diff --git a/Task/Draw-a-clock/Ruby/draw-a-clock-1.rb b/Task/Draw-a-clock/Ruby/draw-a-clock-1.rb new file mode 100644 index 0000000000..777f273cf2 --- /dev/null +++ b/Task/Draw-a-clock/Ruby/draw-a-clock-1.rb @@ -0,0 +1,41 @@ +Shoes.app(:width=>205, :height => 228, :title => "A Clock") do + def draw_ray(width, start, stop, ratio) + angle = Math::PI * 2 * ratio - Math::PI/2 + strokewidth width + cos = Math::cos(angle) + sin = Math::sin(angle) + line 101+cos*start, 101+sin*start, 101+cos*stop, 101+sin*stop + end + + def update + t = Time.now + @time.text = t.strftime("%H:%M:%S") + h, m, s = (t.hour % 12).to_f, t.min.to_f, t.sec.to_f + s += t.to_f - t.to_i # add the fractional seconds + + @hands.clear do + draw_ray(3, 0, 70, (h + m/60)/12) + draw_ray(2, 0, 90, (m + s/60)/60) + draw_ray(1, 0, 95, s/60) + end + end + + # a place for the text display + @time = para(:align=>"center", :family => "monospace") + + # draw the clock face + stack(:width=>203, :height=>203) do + strokewidth 1 + fill gradient(deepskyblue, aqua) + oval 1, 1, 200 + fill black + oval 98, 98, 6 + # draw the minute indicators + 0.upto(59) {|m| draw_ray(1, (m % 5 == 0 ? 96 : 98), 100, m.to_f/60)} + end.move(0,23) + + # the drawing area for the hands + @hands = stack(:width=>203, :height=>203) {}.move(0,23) + + animate(5) {update} +end diff --git a/Task/Draw-a-clock/Ruby/draw-a-clock-2.rb b/Task/Draw-a-clock/Ruby/draw-a-clock-2.rb new file mode 100644 index 0000000000..97b208b854 --- /dev/null +++ b/Task/Draw-a-clock/Ruby/draw-a-clock-2.rb @@ -0,0 +1,45 @@ +Shoes.app(:title => "Berlin-Uhr Clock", :width => 209, :height => 300) do + background lightgrey + + Red = rgb(255, 20, 20) + Yellow = rgb(173, 255, 47) + Green = rgb(154, 205, 50) + Gray = rgb(128, 128, 128) + + @time = para(:align => "center") + stack do + fill Gray + stroke black + strokewidth 2 + @seconds = oval 75, 3, 50 + @hrs_a = 4.times.collect {|i| rect 51*i, 56, 48, 30, 4} + @hrs_b = 4.times.collect {|i| rect 51*i, 89, 48, 30, 4} + @mins_a = 11.times.collect {|i| rect 2+18*i, 122, 15, 30, 4} + @mins_b = 4.times.collect {|i| rect 51*i, 155, 48, 30, 4} + # some decoration + fill white + stroke darkslategray + rect -10, -30, 75, 70, 10 + rect 140, -30, 75, 70, 10 + rect -13, 192, 105, 100, 10 + rect 110, 192, 105, 100, 10 + end.move(3,20) + + animate(1) do + now = Time.now + @time.text = now.strftime("%H:%M:%S") + @seconds.style(:fill => now.sec.even? ? Green : Gray) + a, b = now.hour.divmod(5) + 4.times {|i| @hrs_a[i].style(:fill => i < a ? Red : Gray)} + 4.times {|i| @hrs_b[i].style(:fill => i < b ? Red : Gray)} + a, b = now.min.divmod(5) + 11.times {|i| @mins_a[i].style(:fill => i < a ? (i%3==2 ? Red : Yellow) : Gray)} + 4.times {|i| @mins_b[i].style(:fill => i < b ? Yellow : Gray)} + end + + keypress do |key| + case key + when :control_q, "\x11" then exit + end + end +end diff --git a/Task/Draw-a-clock/Run-BASIC/draw-a-clock.run b/Task/Draw-a-clock/Run-BASIC/draw-a-clock.run new file mode 100644 index 0000000000..ba1d79746f --- /dev/null +++ b/Task/Draw-a-clock/Run-BASIC/draw-a-clock.run @@ -0,0 +1,95 @@ +' -------------------------------------------- +' clock. I got nothing but time +' --------------------------------------------- +n = 12 ' num of points +r = 95 ' radius +pi = 22/7 +alpha = pi * 2 / n +dim points(n) +graphic #g2, 200, 200 +' -------------------------------------- +' Draw the clock +' -------------------------------------- +#g2 size(2) 'pen size +#g2 down() +#g2 font("arial", 20, "bold") +#g2 place(85,30) +#g2 "\12" +#g2 place(170,105) +#g2 "\3" +#g2 place(10,105) +#g2 "\9" +#g2 place(90,185) +#g2 "\6" +for i = 0 to n - 1 + theta = alpha * i + px = cos( theta ) * r + py = sin( theta ) * r + px = px + 100 + py = py + 100 + #g2 place(px,py) + #g2 circle(2) +next i + +[shoTime] +' ------------------------- +' clear previous sec,min,hr +' ------------------------- +r = 63 +p = se +#g2 color("white") +gosub [h2Dot] +r = 50 +p = mi +#g2 color("white") +gosub [h2Dot] +r = 30 ' radius +p = hr * 5 +#g2 color("white") +gosub [h2Dot] + +' ------------------------- +' Show new time +' ------------------------- +a$ = time$() +hr = val(word$(a$,1,":")) +mi = val(word$(a$,2,":")) +se = val(word$(a$,3,":")) + +' put time on the clock - gimme a hand +#g2 size(4) +' second hand +n = 60 +r = 63 +p = se +#g2 color("blue") +gosub [h2Dot] + +' minute hand +r = 50 +p = mi +#g2 color("green") +gosub [h2Dot] + +' hour hand +r = 30 ' radius +p = hr * 5 +#g2 color("red") +gosub [h2Dot] + +render #g2 +end + +' a one liner +[h2Dot] +alpha = pi * 2 / n +i = p - 15 +theta = alpha * i +px = cos( theta ) * r +py = sin( theta ) * r +px = px + 100 +py = py + 100 +#g2 place(px,py) +#g2 circle(2) +#g2 line(100,100,px,py) +RETURN diff --git a/Task/Draw-a-clock/Scala/draw-a-clock-1.scala b/Task/Draw-a-clock/Scala/draw-a-clock-1.scala new file mode 100644 index 0000000000..a58ea1e834 --- /dev/null +++ b/Task/Draw-a-clock/Scala/draw-a-clock-1.scala @@ -0,0 +1,53 @@ +import java.util.{ Timer, TimerTask } +import java.time.LocalTime +import scala.math._ + +object Clock extends App { + private val (width, heigth) = (80, 35) + + def getGrid(localTime: LocalTime): Array[Array[Char]] = { + val (minute, second) = (localTime.getMinute, localTime.getSecond()) + val grid = Array.fill[Char](heigth, width)(' ') + + def toGridCoord(x: Double, y: Double): (Int, Int) = + (floor((y + 1.0) / 2.0 * heigth).toInt, floor((x + 1.0) / 2.0 * width).toInt) + + def makeText(grid: Array[Array[Char]], r: Double, theta: Double, str: String) { + val (row, col) = toGridCoord(r * cos(theta), r * sin(theta)) + (0 until str.length).foreach(i => + if (row >= 0 && row < heigth && col + i >= 0 && col + i < width) grid(row)(col + i) = str(i)) + } + + def makeCircle(grid: Array[Array[Char]], r: Double, c: Char) { + var theta = 0.0 + while (theta < 2 * Pi) { + val (row, col) = toGridCoord(r * cos(theta), r * sin(theta)) + if (row >= 0 && row < heigth && col >= 0 && col < width) grid(row)(col) = c + theta = theta + 0.01 + } + } + + def makeHand(grid: Array[Array[Char]], maxR: Double, theta: Double, c: Char) { + var r = 0.0 + while (r < maxR) { + val (row, col) = toGridCoord(r * cos(theta), r * sin(theta)) + if (row >= 0 && row < heigth && col >= 0 && col < width) grid(row)(col) = c + r = r + 0.01 + } + } + + makeCircle(grid, 0.98, '@') + makeHand(grid, 0.6, (localTime.getHour() + minute / 60.0 + second / 3600.0) * Pi / 6 - Pi / 2, 'O') + makeHand(grid, 0.85, (minute + second / 60.0) * Pi / 30 - Pi / 2, '*') + makeHand(grid, 0.90, second * Pi / 30 - Pi / 2, '.') + + (1 to 12).foreach(n => makeText(grid, 0.87, n * Pi / 6 - Pi / 2, n.toString)) + grid + } // def getGrid( + + private val timerTask = new TimerTask { + private def printGrid(grid: Array[Array[Char]]) = grid.foreach(row => println(row.mkString)) + def run() = printGrid(getGrid(LocalTime.now())) + } + (new Timer).schedule(timerTask, 0, 1000) +} diff --git a/Task/Draw-a-clock/Scala/draw-a-clock-2.scala b/Task/Draw-a-clock/Scala/draw-a-clock-2.scala new file mode 100644 index 0000000000..371407c604 --- /dev/null +++ b/Task/Draw-a-clock/Scala/draw-a-clock-2.scala @@ -0,0 +1,50 @@ +import java.time.LocalTime +import java.awt.{ Color, Graphics } + +/** The Berlin clock as a Java (8.0) applet + */ +class QDclock extends java.applet.Applet with Runnable { + val bclockThread: Thread = new Thread(this, "QDclock") + + override def init() = resize(242, 180) // fixed size, at first... doesn't work... + + override def start() = if (!bclockThread.isAlive()) bclockThread.start() + + def run() { + while (true) { + repaint() + try Thread.sleep(1000) catch { case _: Throwable => sys.exit(-1) } + } + } + + override def update(g: Graphics) { + val now = LocalTime.now + + def booleanToColor(cond: Boolean, colorOn: Color = Color.red): Color = + if (cond) colorOn else Color.black + + g.setColor(booleanToColor(now.getSecond() % 2 == 0, Color.yellow)) + g.fillOval(100, 4, 40, 40) + + val (stu, min) = (now.getHour(), now.getMinute()) match { + case (0, 0) => (24, 0) + case (hrs, min) => (hrs, min) + } + + def drawRectangle(color: Color, rect: (Int, Int, Int, Int)) { + g.setColor(color) + g.fillRoundRect(rect._1, rect._2, rect._3, rect._4, 4, 4) + } + + for (i <- 0 until 4) { + drawRectangle(booleanToColor(stu / ((i + 1) * 5) > 0), (i * 60 + 2, 46, 58, 30)) + drawRectangle(booleanToColor(stu % 5 > i), (i * 60 + 2, 78, 58, 30)) + drawRectangle(booleanToColor(min % 5 > i, Color.yellow), (i * 60 + 2, 142, 58, 30)) + } + + for (i <- 0 until 11) { + drawRectangle(booleanToColor(min / ((i + 1) * 5) > 0, + if (2 to 8 by 3 contains i) Color.red else Color.yellow), (i * 20 + 10, 110, 18, 30)) + } + } +} diff --git a/Task/Draw-a-clock/Seed7/draw-a-clock.seed7 b/Task/Draw-a-clock/Seed7/draw-a-clock.seed7 new file mode 100644 index 0000000000..21481fb4f6 --- /dev/null +++ b/Task/Draw-a-clock/Seed7/draw-a-clock.seed7 @@ -0,0 +1,71 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + include "draw.s7i"; + include "keybd.s7i"; + include "time.s7i"; + include "duration.s7i"; + +const integer: WINDOW_WIDTH is 200; +const integer: WINDOW_HEIGHT is 200; +const color: BACKGROUND is White; +const color: FOREGROUND is Black; +const color: CLOCKCOLOR is Aqua; + +const proc: main is func + local + var char: command is ' '; + var time: start_time is time.value; + var float: alpha is 0.0; + var integer: x is 0; + begin + screen(WINDOW_WIDTH, WINDOW_HEIGHT); + clear(curr_win, BACKGROUND); + KEYBOARD := GRAPH_KEYBOARD; + command := busy_getc(KEYBOARD); + while command <> 'q' do + start_time := truncToSecond(time(NOW)); + clear(curr_win, BACKGROUND); + fcircle(100, 100, 95, CLOCKCOLOR); + circle(100, 100, 95, FOREGROUND); + for x range 0 to 60 do + alpha := flt(x-15) * PI / 30.0; + if x mod 5 = 0 then + lineTo(100 + round(cos(alpha)*95.0), + 100 + round(sin(alpha)*95.0), + 100 + round(cos(alpha)*85.0), + 100 + round(sin(alpha)*85.0), FOREGROUND); + else + lineTo(100 + round(cos(alpha)*95.0), + 100 + round(sin(alpha)*95.0), + 100 + round(cos(alpha)*92.0), + 100 + round(sin(alpha)*92.0), FOREGROUND); + end if; + end for; + alpha := flt(start_time.second-15) * PI / 30.0; + lineTo(100, 100, 100 + round(cos(alpha)*85.0), 100 + round(sin(alpha)*85.0), FOREGROUND); + alpha := flt(start_time.minute-15) * PI / 30.0; + lineTo(100 + round(cos(alpha-PI/2.0)*5.0), + 100 + round(sin(alpha-PI/2.0)*5.0), + 100 + round(cos(alpha)*75.0), + 100 + round(sin(alpha)*75.0), FOREGROUND); + lineTo(100 + round(cos(alpha+PI/2.0)*5.0), + 100 + round(sin(alpha+PI/2.0)*5.0), + 100 + round(cos(alpha)*75.0), + 100 + round(sin(alpha)*75.0), FOREGROUND); + alpha := (flt(start_time.hour)+flt(start_time.minute)/60.0-3.0) * PI / 6.0; + lineTo(100 + round(cos(alpha-PI/2.0)*7.0), + 100 + round(sin(alpha-PI/2.0)*7.0), + 100 + round(cos(alpha)*50.0), + 100 + round(sin(alpha)*50.0), FOREGROUND); + lineTo(100 + round(cos(alpha+PI/2.0)*7.0), + 100 + round(sin(alpha+PI/2.0)*7.0), + 100 + round(cos(alpha)*50.0), + 100 + round(sin(alpha)*50.0), FOREGROUND); + fcircle(100, 100, 7, CLOCKCOLOR); + circle(100, 100, 7, FOREGROUND); + DRAW_FLUSH; + await(start_time + 1 . SECONDS); + command := busy_getc(KEYBOARD); + end while; + end func; diff --git a/Task/Draw-a-clock/Tcl/draw-a-clock.tcl b/Task/Draw-a-clock/Tcl/draw-a-clock.tcl new file mode 100644 index 0000000000..9facb5b050 --- /dev/null +++ b/Task/Draw-a-clock/Tcl/draw-a-clock.tcl @@ -0,0 +1,33 @@ +package require Tcl 8.5 +package require Tk + +# GUI code +pack [canvas .c -width 200 -height 200] +.c create oval 20 20 180 180 -width 10 -fill {} -outline grey70 +.c create line 0 0 1 1 -tags hour -width 6 -cap round -fill black +.c create line 0 0 1 1 -tags minute -width 4 -cap round -fill black +.c create line 0 0 1 1 -tags second -width 2 -cap round -fill grey30 +proc updateClock t { + scan [clock format $t -format "%H %M %S"] "%d%d%d" h m s + # On an analog clock, the hour and minute hands move gradually + set m [expr {$m + $s/60.0}] + set h [expr {($h % 12 + $m/60.0) * 5}] + foreach tag {hour minute second} value [list $h $m $s] len {50 80 80} { + .c coords $tag 100 100 \ + [expr {100 + $len*sin($value/30.0*3.14159)}] \ + [expr {100 - $len*cos($value/30.0*3.14159)}] + } +} + +# Timer code, accurate to within a quarter second +set time 0 +proc ticker {} { + global time + set t [clock seconds] + after 250 ticker + if {$t != $time} { + set time $t + updateClock $t + } +} +ticker diff --git a/Task/Extensible-prime-generator/00DESCRIPTION b/Task/Extensible-prime-generator/00DESCRIPTION new file mode 100644 index 0000000000..591c5dff6e --- /dev/null +++ b/Task/Extensible-prime-generator/00DESCRIPTION @@ -0,0 +1,21 @@ +The task is to write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. + +The routine should demonstrably rely on either: +# Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. +# Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. +# If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. + +The routine should be used to: +* Show the first twenty primes. +* Show the primes between 100 and 150. +* Show the ''number'' of primes between 7,700 and 8,000. +* Show the 10,000th prime. + +Show output on this page. + +'''Note:''' You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). + +'''Note 2:''' If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). + +;See also: +* The task is written so it may be useful in solving task [[Emirp primes]] as well as others (depending on its efficiency). diff --git a/Task/Extensible-prime-generator/Ada/extensible-prime-generator.ada b/Task/Extensible-prime-generator/Ada/extensible-prime-generator.ada new file mode 100644 index 0000000000..756c3145a9 --- /dev/null +++ b/Task/Extensible-prime-generator/Ada/extensible-prime-generator.ada @@ -0,0 +1,71 @@ +with Ada.Text_IO, Miller_Rabin; + +procedure Prime_Gen is + + type Num is range 0 .. 2**63-1; -- maximum for the gnat Ada compiler + + MR_Iterations: constant Positive := 25; + -- the probability Pr[Is_Prime(N, MR_Iterations) = Probably_Prime] + -- is 1 for prime N and < 4**(-MR_Iterations) for composed N + + function Next(P: Num) return Num is + N: Num := P+1; + package MR is new Miller_Rabin(Num); use MR; + begin + while not (Is_Prime(N, MR_Iterations) = Probably_Prime) loop + N := N + 1; + end loop; + return N; + end Next; + + Current: Num; + Count: Num := 0; + +begin + -- show the first twenty primes + Ada.Text_IO.Put("First 20 primes:"); + Current := 1; + for I in 1 .. 20 loop + Current := Next(Current); + Ada.Text_IO.Put(Num'Image(Current)); + end loop; + Ada.Text_IO.New_Line; + + -- show the primes between 100 and 150 + Ada.Text_IO.Put("Primes between 100 and 150:"); + Current := 99; + loop + Current := Next(Current); + exit when Current > 150; + Ada.Text_IO.Put(Num'Image(Current)); + end loop; + Ada.Text_IO.New_Line; + + -- count primes between 7700 and 8000 + Ada.Text_IO.Put("Number of primes between 7700 and 8000:"); + Current := 7699; + loop + Current := Next(Current); + exit when Current > 8000; + Count := Count + 1; + end loop; + Ada.Text_IO.Put_Line(Num'Image(Count)); + + Count := 10; + Ada.Text_IO.Put_Line("Print the K_i'th prime, for $K=10**i:"); + begin + loop + Current := 1; + for I in 1 .. Count loop + Current := Next(Current); + end loop; + Ada.Text_IO.Put(Num'Image(Count) & "th prime:" & + Num'Image(Current)); + Count := Count * 10; + end loop; + exception + when Constraint_Error => + Ada.Text_IO.Put_Line(" can't compute the" & Num'Image(Count) & + "th prime:"); + end; +end; diff --git a/Task/Extensible-prime-generator/AutoHotkey/extensible-prime-generator.ahk b/Task/Extensible-prime-generator/AutoHotkey/extensible-prime-generator.ahk new file mode 100644 index 0000000000..84979061bb --- /dev/null +++ b/Task/Extensible-prime-generator/AutoHotkey/extensible-prime-generator.ahk @@ -0,0 +1,46 @@ +SetBatchLines, -1 +p := 1 ;p functions as the counter +Loop, 10000 { + p := NextPrime(p) + if (A_Index < 21) + a .= p ", " + if (p < 151 && p > 99) + b .= p ", " + if (p < 8001 && p > 7699) + c++ +} +MsgBox, % "First twenty primes: " RTrim(a, ", ") + . "`nPrimes between 100 and 150: " RTrim(b, ", ") + . "`nNumber of primes between 7,700 and 8,000: " RTrim(c, ", ") + . "`nThe 10,000th prime: " p + +NextPrime(n) { + Loop + if (IsPrime(++n)) + return n +} + +IsPrime(n) { + if (n < 2) + return, 0 + else if (n < 4) + return, 1 + else if (!Mod(n, 2)) + return, 0 + else if (n < 9) + return 1 + else if (!Mod(n, 3)) + return, 0 + else { + r := Floor(Sqrt(n)) + f := 5 + while (f <= r) { + if (!Mod(n, f)) + return, 0 + if (!Mod(n, (f + 2))) + return, 0 + f += 6 + } + return, 1 + } +} diff --git a/Task/Extensible-prime-generator/C/extensible-prime-generator.c b/Task/Extensible-prime-generator/C/extensible-prime-generator.c new file mode 100644 index 0000000000..f6e1331c01 --- /dev/null +++ b/Task/Extensible-prime-generator/C/extensible-prime-generator.c @@ -0,0 +1,98 @@ +#include +#include +#include +#include + +#define CHUNK_BYTES (32 << 8) +#define CHUNK_SIZE (CHUNK_BYTES << 6) + +int field[CHUNK_BYTES]; +#define GET(x) (field[(x)>>6] & 1<<((x)>>1&31)) +#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31)) + +typedef unsigned uint; +typedef struct { + uint *e; + uint cap, len; +} uarray; +uarray primes, offset; + +void push(uarray *a, uint n) +{ + if (a->len >= a->cap) { + if (!(a->cap *= 2)) a->cap = 16; + a->e = realloc(a->e, sizeof(uint) * a->cap); + } + a->e[a->len++] = n; +} + +uint low; +void init(void) +{ + uint p, q; + + unsigned char f[1<<16]; + memset(f, 0, sizeof(f)); + push(&primes, 2); + push(&offset, 0); + for (p = 3; p < 1<<16; p += 2) { + if (f[p]) continue; + for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1; + push(&primes, p); + push(&offset, q); + } + low = 1<<16; +} + +void sieve(void) +{ + uint i, p, q, hi, ptop; + if (!low) init(); + + memset(field, 0, sizeof(field)); + + hi = low + CHUNK_SIZE; + ptop = sqrt(hi) * 2 + 1; + + for (i = 1; (p = primes.e[i]*2) < ptop; i++) { + for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p) + SET(q); + offset.e[i] = q + low; + } + + for (p = 1; p < CHUNK_SIZE; p += 2) + if (!GET(p)) push(&primes, low + p); + + low = hi; +} + +int main(void) +{ + uint i, p, c; + + while (primes.len < 20) sieve(); + printf("First 20:"); + for (i = 0; i < 20; i++) + printf(" %u", primes.e[i]); + putchar('\n'); + + while (primes.e[primes.len-1] < 150) sieve(); + printf("Between 100 and 150:"); + for (i = 0; i < primes.len; i++) { + if ((p = primes.e[i]) >= 100 && p < 150) + printf(" %u", primes.e[i]); + } + putchar('\n'); + + while (primes.e[primes.len-1] < 8000) sieve(); + for (i = c = 0; i < primes.len; i++) + if ((p = primes.e[i]) >= 7700 && p < 8000) c++; + printf("%u primes between 7700 and 8000\n", c); + + for (c = 10; c <= 100000000; c *= 10) { + while (primes.len < c) sieve(); + printf("%uth prime: %u\n", c, primes.e[c-1]); + } + + return 0; +} diff --git a/Task/Extensible-prime-generator/D/extensible-prime-generator-1.d b/Task/Extensible-prime-generator/D/extensible-prime-generator-1.d new file mode 100644 index 0000000000..f29e6fac21 --- /dev/null +++ b/Task/Extensible-prime-generator/D/extensible-prime-generator-1.d @@ -0,0 +1,12 @@ +void main() { + import std.stdio, std.range, std.algorithm, sieve_of_eratosthenes3; + + Prime prime; + writeln("First twenty primes:\n", 20.iota.map!prime); + writeln("Primes primes between 100 and 150:\n", + uint.max.iota.map!prime.until!q{a > 150}.filter!q{a > 99}); + writeln("Number of primes between 7,700 and 8,000: ", + uint.max.iota.map!prime.until!q{a > 8_000} + .filter!q{a > 7_699}.walkLength); + writeln("10,000th prime: ", prime(9_999)); +} diff --git a/Task/Extensible-prime-generator/D/extensible-prime-generator-2.d b/Task/Extensible-prime-generator/D/extensible-prime-generator-2.d new file mode 100644 index 0000000000..10462fa316 --- /dev/null +++ b/Task/Extensible-prime-generator/D/extensible-prime-generator-2.d @@ -0,0 +1,111 @@ +/// Prime sieve based on: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf + +import std.container: Array, BinaryHeap, RedBlackTree; + +struct LazyPrimeSieve { + @property bool empty() const pure nothrow @safe @nogc { + return i > 203_280_221; // Pi(2 ^^ 32). + } + + @property auto front() const pure nothrow @safe @nogc { + return prime; + } + + @property void popFront() pure nothrow /*@safe*/ { + prime = sieveOne(); + } + +private: + static struct Wheel2357 { + static immutable ubyte[48] holes = [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, 6, 4, 6, 2, 4, 6, 2, 6, 6, + 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10]; + static immutable ubyte[4] spokes = [2, 3, 5, 7]; + static immutable ubyte first = 11; + uint i; + + auto spin() pure nothrow @safe @nogc { + return holes[i++ % $]; + } + } + + static struct CompositeIterator { + uint prime; + Wheel2357 wheel; + ulong composite; + + this(uint p) pure nothrow @safe @nogc { + prime = p; + composite = p * wheel.first; + } + + void next() pure nothrow @safe @nogc { + composite += prime * wheel.spin; + } + } + + version (heap) // Less memory but slower. + BinaryHeap!(Array!CompositeIterator, "a.composite > b.composite") iterators; + else // Faster but is more GC intensive. + RedBlackTree!(CompositeIterator, "a.composite < b.composite", true) iterators; + + uint prime = 2; + uint i = 1; + Wheel2357 wheel; + uint candidate = wheel.first; + + uint sieveOne() pure nothrow /*@safe*/ { + switch (i) { + case 0: .. case wheel.spokes.length - 1: + return wheel.spokes[i++]; + + case wheel.spokes.length: + i++; + return candidate; + + case wheel.spokes.length + 1: + version (heap) {} + else + iterators = new typeof(iterators); + goto default; + + default: + goto POST_RETURN; + + while (true) { + candidate += wheel.spin; + + while (iterators.front.composite < candidate) { + auto it = iterators.front; + iterators.removeFront; + it.next; + iterators.insert(it); + } + + if (iterators.front.composite != candidate) { + i++; + return candidate; + POST_RETURN: + // Only insert primes that are multiply + // occuring in [0, 2 ^^ 32). + if (candidate < 2 ^^ 16) + iterators.insert(CompositeIterator(candidate)); + } + } + } + } +} + + +void main() /*@safe*/ { + import std.stdio, std.algorithm, std.range; + + writeln("Sum of first 100,000 primes: ", LazyPrimeSieve().take(100_000).sum(0uL)); + + writeln("First twenty primes:\n", LazyPrimeSieve().take(20)); + writeln("Primes primes between 100 and 150:\n", + LazyPrimeSieve().until!q{a > 150}.filter!q{a > 99}); + writeln("Number of primes between 7,700 and 8,000: ", + LazyPrimeSieve().until!q{a > 8_000}.filter!q{a > 7_699}.walkLength); + writeln("10,000th prime: ", LazyPrimeSieve().dropExactly(9999).front); +} diff --git a/Task/Extensible-prime-generator/Go/extensible-prime-generator-1.go b/Task/Extensible-prime-generator/Go/extensible-prime-generator-1.go new file mode 100644 index 0000000000..42293a3c92 --- /dev/null +++ b/Task/Extensible-prime-generator/Go/extensible-prime-generator-1.go @@ -0,0 +1,86 @@ +package main + +import ( + "container/heap" + "fmt" +) + +func main() { + p := newP() + fmt.Print("First twenty: ") + for i := 0; i < 20; i++ { + fmt.Print(p(), " ") + } + fmt.Print("\nBetween 100 and 150: ") + n := p() + for n <= 100 { + n = p() + } + for ; n < 150; n = p() { + fmt.Print(n, " ") + } + for n <= 7700 { + n = p() + } + c := 0 + for ; n < 8000; n = p() { + c++ + } + fmt.Println("\nNumber beween 7,700 and 8,000:", c) + p = newP() + for i := 1; i < 10000; i++ { + p() + } + fmt.Println("10,000th prime:", p()) +} + +func newP() func() int { + n := 1 + var pq pQueue + top := &pMult{2, 4, 0} + return func() int { + for { + n++ + if n < top.pMult { // n is a new prime + heap.Push(&pq, &pMult{prime: n, pMult: n * n}) + top = pq[0] + return n + } + // n was next on the queue, it's a composite + for top.pMult == n { + top.pMult += top.prime + heap.Fix(&pq, 0) + top = pq[0] + } + } + } +} + +type pMult struct { + prime int + pMult int + index int +} + +type pQueue []*pMult + +func (q pQueue) Len() int { return len(q) } +func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult } +func (q pQueue) Swap(i, j int) { + q[i], q[j] = q[j], q[i] + q[i].index = i + q[j].index = j +} +func (p *pQueue) Push(x interface{}) { + q := *p + e := x.(*pMult) + e.index = len(q) + *p = append(q, e) +} +func (p *pQueue) Pop() interface{} { + q := *p + last := len(q) - 1 + e := q[last] + *p = q[:last] + return e +} diff --git a/Task/Extensible-prime-generator/Go/extensible-prime-generator-2.go b/Task/Extensible-prime-generator/Go/extensible-prime-generator-2.go new file mode 100644 index 0000000000..ec18b50e79 --- /dev/null +++ b/Task/Extensible-prime-generator/Go/extensible-prime-generator-2.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "github.com/jbarham/primegen.go" +) + +func main() { + p := primegen.New() + + fmt.Print("First twenty: ") + for i := 0; i < 20; i++ { + fmt.Print(p.Next(), " ") + } + fmt.Print("\nBetween 100 and 150: ") + p.SkipTo(100) + for n := p.Next(); n < 150; n = p.Next() { + fmt.Print(n, " ") + } + p.SkipTo(7700) + fmt.Println("\nNumber beween 7,700 and 8,000:", p.Count(8000)) + p.Reset() + for i := 1; i < 1e4; i++ { + p.Next() + } + fmt.Println("10,000th prime:", p.Next()) +} diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-1.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-1.hs new file mode 100644 index 0000000000..07490b4aec --- /dev/null +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-1.hs @@ -0,0 +1,26 @@ +#!/usr/bin/env runghc + +import Data.List +import Data.Numbers.Primes +import System.IO + +firstNPrimes :: Integer -> [Integer] +firstNPrimes n = genericTake n primes + +primesBetweenInclusive :: Integer -> Integer -> [Integer] +primesBetweenInclusive lo hi = + dropWhile (< lo) $ takeWhile (<= hi) primes + +nthPrime :: Integer -> Integer +nthPrime n = genericIndex primes (n - 1) -- beware 0-based indexing + +main = do + hSetBuffering stdout NoBuffering + putStr "First 20 primes: " + print $ firstNPrimes 20 + putStr "Primes between 100 and 150: " + print $ primesBetweenInclusive 100 150 + putStr "Number of primes between 7700 and 8000: " + print $ genericLength $ primesBetweenInclusive 7700 8000 + putStr "The 10000th prime: " + print $ nthPrime 10000 diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs new file mode 100644 index 0000000000..30c6143d8a --- /dev/null +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs @@ -0,0 +1 @@ +![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345) diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs new file mode 100644 index 0000000000..5dbb6fe349 --- /dev/null +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs @@ -0,0 +1,38 @@ +import Collections # to get the Heap class for use as a Priority Queue +record filter(composite, prime) # next composite involving this prime + +procedure main() + every writes((primes()\20)||" " | "\n") + every p := primes() do if 100 < p < 150 then writes(p," ") else if p >= 150 then break write() + every (n := 0, p := primes()) do if 7700 < p < 8000 then n +:= 1 else if p >= 8000 then break write(n) + every (i := 1, p := primes()) do if (i+:=1) >= 10000 then break write(p) +end + +procedure primes() + local wheel2357, nc + wheel2357 := [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, 6, 4, 6, 2, 4, 6, + 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10] + suspend sieve(Heap(,getCompositeField), ![2,3,5.7] | (nc := 11) | (nc +:= |!wheel2357)) +end + +procedure sieve(pQueue, candidate) + local nc + if 0 = pQueue.size() then { # 2 is prime + pQueue.add(filter(candidate*candidate, candidate)) + return candidate + } + while candidate > (nc := pQueue.get()).composite do { + nc.composite +:= nc.prime + pQueue.add(nc) + } + pQueue.add(filter(nc.composite+nc.prime, nc.prime)) + if candidate < nc.composite then { # new prime found! + pQueue.add(filter(candidate*candidate, candidate)) + return candidate + } + +end + +# Provide a function for comparing filters in the priority queue... +procedure getCompositeField(x); return x.composite; end diff --git a/Task/Extensible-prime-generator/J/extensible-prime-generator.j b/Task/Extensible-prime-generator/J/extensible-prime-generator.j new file mode 100644 index 0000000000..795650d2d5 --- /dev/null +++ b/Task/Extensible-prime-generator/J/extensible-prime-generator.j @@ -0,0 +1,8 @@ + p:i.20 +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 + (#~ >:&100)i.&.(p:inv) 150 +101 103 107 109 113 127 131 137 139 149 + #(#~ >:&7700)i.&.(p:inv) 8000 +30 + p:10000-1 +104729 diff --git a/Task/Extensible-prime-generator/Mathematica/extensible-prime-generator.math b/Task/Extensible-prime-generator/Mathematica/extensible-prime-generator.math new file mode 100644 index 0000000000..d9c468f44e --- /dev/null +++ b/Task/Extensible-prime-generator/Mathematica/extensible-prime-generator.math @@ -0,0 +1,8 @@ +Prime[Range[20]] +{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71} +Select[Range[100,150], PrimeQ] +{101, 103, 107, 109, 113, 127, 131, 137, 139, 149} +PrimePi[8000] - PrimePi[7700] +30 +Prime[10000] +104729 diff --git a/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal new file mode 100644 index 0000000000..10bdff7100 --- /dev/null +++ b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal @@ -0,0 +1,459 @@ +program prime7; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,REGVAR,PEEPHOLE,CSE,ASMCSE} + {$Smartlink ON} + {$CODEALIGN proc=32} +{$ELSE} + {$APPLICATION CONSOLE} +{$ENDIF} +uses + popcount; +const + + InitPrim :array [0..9] of byte = (2,3,5,7,11,13,17,19,23,29); +(* + {MAXANZAHL = 2*3*5*7*11*13*17*19;*PRIM} + MAXANZAHL :array [0..8] of Longint =(2,6,30,210,2310,30030, + 510510,9699690,223092870); + {WIFEMAXLAENGE = 1*2*4*6*10*12*16*18;*PRIM-1} + WIFEMAXLAENGE :array [0..8] of longint =(1,2,8,48,480,5760, + 92160,1658880,36495360); +*) + BIS = 4; + cMaxZahl = 2310; + cRepFldLen = 480; + +{Sieve results: + one billion -- 50,847,534 + two billion -- 98,222,287 + three billion -- 144,449,537 + four billion -- 189,961,812 + ten billion -- 455.052.511 + } + MaxZahl = 20*1000*1000; + //limit for 32 Bit calc tSievenum = LongWord; 20e9 + //MaxZahl = High(LongWord) DIV cRepFldLen *cMaxZahl; + MAXIMUM = ((MaxZahl-1) DIV cMaxZahl+1)*cMaxZahl; + // maximal distance in number wheel + MaxMulFac = 14; {array [0..9] of byte= (2,4,6,10,14,22,26,34,40,50);} + {Auf Mod 32 = 0 bringen} + {MAXSUCHE = MAXIMUM*WIFEMAXLAENGE[BIS]/MAXANZAHl[BIS]} +(* div2,div3,*4div15,*8div35,*16div77,*192 div 1001,*3072div17017.. *) + MAXSUCHE = ((((MAXIMUM-1) div cMaxZahl+1)*cRepFldLen-1)shr 5+1)shl 5; + + +type + tSievenum = Uint32;// Uint64 doubles run-time in 32 Bit + tSegment = record + dOfs, + dSegment :LongWord; + end; + tpSegment = ^tSegment; + tMulFeld = array [0..MaxMulFac shr 1 -1] of tSegment; + tnumberField= array [0..cMaxZahl-1] of Word; + tDiffFeld = array [0..{WIFEMAXLAENGE[BIS]}cRepFldLen-1] of byte; + tRevIdx = array [0..{WIFEMAXLAENGE[BIS]}cRepFldLen-1] of word; + (* numberField as Bit array *) + tsearchFld = array [0..MAXSUCHE shr 5-1] of set of 0..31; + + tRecPrime = record + rpPrime :tSievenum; + rpsvPos, + rpOfs, + rpSeg :LongWord; + end; + +var + MulFeld : tMulFeld; + searchFld : tsearchFld; + number : tnumberField; + DiffFld : tDiffFeld; + RevIdx : tRevIdx; + Quadrat : Uint64; + MaxPos : NativeUint; + +const + two : Array [0..31] Of LongWord = ( + $00000001 , $00000002 , $00000004 , $00000008 + , $00000010 , $00000020 , $00000040 , $00000080 + , $00000100 , $00000200 , $00000400 , $00000800 + , $00001000 , $00002000 , $00004000 , $00008000 + , $00010000 , $00020000 , $00040000 , $00080000 + , $00100000 , $00200000 , $00400000 , $00800000 + , $01000000 , $02000000 , $04000000 , $08000000 + , $10000000 , $20000000 , $40000000 , $80000000 + ) ; + +procedure BuildWheel; +{simple sieve of erathothenes only eliminating small primes} +var + pr,i,j,Ofs : NativeUint; +Begin + Fillchar(number,SizeOf(number),#0); + For i := 0 to BIS do + Begin + pr := InitPrim[i]; + j := (High(number) div pr)*pr; + repeat + number[j] := 1; + dec(j,pr); + until j <= 0; + end; + + i := 1; + j := 0; + RevIdx[0]:= 1; + repeat + Ofs :=0; + repeat + inc(i); + inc(ofs); + until number[i] = 0; + DiffFld[j] := ofs; + inc(j); + RevIdx[j] := i; + until i = High(number); + DiffFld[j] := 2; + + //calculate a bitnumber-index into cRepFldLen + Fillchar(number,SizeOf(number),#0); + Ofs := 1; + for i := 0 to cRepFldLen-2 do + begin + inc(Ofs,DiffFld[i]); + number[Ofs] := i+1; + end; + + For i := 0 to cRepFldLen-1 do + Begin + //direct index to Mulfeld + j := (DiffFld[i] shr 1) -1; + DiffFld[i] := j; + end; +end; + +function CalcPos(m: Uint64): UINt32; +{search right position of m} +var + i,res : Uint32; +Begin + res := m div cMaxZahl; + i := m mod cMaxzahl; + while (number[i]= 0) and (i <>1) do + begin + iF i = 0 THEN + begin + Dec(res,cRepFldLen); + i := cMaxzahl; + end; + dec(i); + end; {while} + CalcPos := res *cRepFldLen +number[i]; +end; + +procedure MulTab(searchPr:Nativeint); +var + k,Segment,Segment0,Rest,Rest0: NativeUint; +Begin + {Multiplikationstabelle der Differenzen} + searchPr := searchPr+searchPr; + Segment0 := searchPr div cMaxzahl; + + Rest0 := searchPr-Segment0*cMaxzahl; + Segment0 := Segment0 * cRepFldLen; + + Segment := Segment0; + Rest := Rest0; + + with MulFeld[0] do + begin + dOfs := Rest0; + dSegment:= Segment0; + end; + + for k := 1 to MaxMulFac shr 1-1 do + begin + Segment := Segment+Segment0; + Rest := Rest+Rest0; + IF Rest >= cMaxzahl then + Begin + Rest:= Rest-cMaxzahl; + Segment := Segment+cRepFldLen; + end; + with MulFeld[k] do + begin + dOfs := Rest; + dSegment:= Segment; + end; + end; +end; + +procedure CalcSqrOfs(searchPr:NativeUint;out + Segment,Ofs :tSievenum); +Begin + Segment := Quadrat div cMaxZahl; + Ofs := Quadrat-Uint64(Segment)*cMaxZahl; //ofs Mod cMaxZahl + Segment := Segment*cRepFldLen; +end; + +procedure Sieben(var sf:tsearchFld;searchPr,MulPos:NativeUint); +//for big sieve Segment,Position,k need to be Uint64 +var + Ofs,Segment,Position,k : tSievenum;//NativeUint; + p : pLongWord; +Begin + MulTab(searchPr); + CalcSqrOfs(searchPr,Segment,Ofs); + Position := Segment+number[ofs]; + + {Primzahlen ausstreichen} + repeat + k:= MulPos+1; + IF k >= cRepFldLen then + dec(k,k);//=0; + mulpos := k; + k := DiffFld[k]; + With MulFeld[k] do + begin + k:= Ofs+dOfs; + Segment := Segment+dSegment; + end; + + If k >= cMaxZahl then + begin + k := k-cMaxZahl; + Segment := Segment+cRepFldLen; + end; + Ofs := k; + k := Segment+number[k]; + p := @sf[Position shr 5]; +// exclude(searchFld[Position shr 5],Position and 31); + p^ := p^ OR two[Position and 31]; + IF k > Position then + Position := k//number[Ofs]+Segment; + else + //case of overflow try 2E10 with 32-Bit + Break; + until Position >= MaxPos; +end; + +procedure SieveAll; +var + i, + searchPr, + PrimPos, + srPrPos : NativeUint; +Begin + BuildWheel; + MaxPos := CalcPos(MaxZahl); + {start of prime sieving} + fillchar(searchFld,SizeOf(searchFld),#0); + {the first prime} + srPrPos := 0; + PrimPos := 0; + searchPr := 1; + Quadrat := searchPr; + repeat + {next prime} + inc(srPrPos); + i := 2*(DiffFld[PrimPos]+1); + //binom (a+b)^2; a^2 already known + Quadrat := Quadrat+(2*searchPr+i)*i; + inc(searchPr,i); + IF Quadrat > MAXIMUM THEN + BREAK; + {if searchPr == prime then sieve with searchPr} + if NOT((srPrPos and 31) in searchFld[srPrPos shr 5] )then + Sieben(searchFld,searchPr,PrimPos); + inc(PrimPos); + if PrimPos = cRepFldLen then + dec(PrimPos,PrimPos);// := 0; + until false; +end; + +function InitRecPrime(pr: tSievenum):tRecPrime; +var + svPos,sg : LongWord; +Begin + svPos := CalcPos(pr); + sg := svPos DIV cRepFldLen; + with result do + Begin + rpsvPos := svPos; + rpSeg := sg; + rpOfs := svPos - sg*cRepFldLen; + rpPrime := RevIdx[rpOfs]+ sg*cMaxZahl; + end; +end; + +function InitPrimeSvPos(svPos: LongWord):tRecPrime; +var + sg : LongWord; +Begin + sg := svPos DIV cRepFldLen; + with result do + Begin + rpsvPos := svPos; + rpSeg := sg; + rpOfs := svPos - sg*cRepFldLen; + rpPrime := RevIdx[rpOfs]+ sg*cMaxZahl; + end; +end; + +Procedure NextPrime(var pr: tRecPrime); +var + ofs,svPos : LongWord; +Begin + with pr do + Begin + svPos := rpsvPos; + Ofs := rpOfs; + repeat + inc(svPos); + if svPos > MaxPos then + EXIT; + inc(Ofs); + IF Ofs >= cRepFldLen then + Begin + ofs := 0; + inc(rpSeg,cRepFldLen); + end; + until NOT((svPos and 31) in searchFld[svPos shr 5] ); + rpPrime := rpSeg*cMaxZahl+RevIdx[Ofs]; + rpSvPos := svPos; + rpOfs := Ofs; + end; +end; + +function GetNthPrime(n: LongWord):tRecPrime; +var + i,cnt : longWord; +Begin + IF n > MaxPos then + EXIT; + + i := 0; + cnt := Bis; + For i := 0 to n shr 5 do + inc(cnt,PopCnt(NOT(Uint32(searchFld[i])))); + i := n shr 5+1; + while cnt < n do + Begin + inc(cnt,PopCnt(NOT(Uint32(searchFld[i])))); + inc(i); + end; + dec(i); + dec(cnt,PopCnt(NOT(Uint32(searchFld[i])))); + result := InitPrimeSvPos(i*32-1); + while cnt < n do + Begin + NextPrime(Result); + inc(cnt); + end; +end; + +procedure ShowPrimes(loLmt,HiLmt: NativeInt); +var + p1 :tRecPrime; +Begin + IF HiLmt < loLmt then + exit; + p1 := InitRecPrime(loLmt); + while p1.rpPrime < LoLmt do + NextPrime(p1); + repeat + write(p1.rpPrime,' '); + NextPrime(p1); + until p1.rpPrime > HiLmt; + writeln; +end; + +function CountPrimes(loLmt,HiLmt: NativeInt):LongWord; +var + p1 :tRecPrime; +Begin + result := 0; + IF HiLmt < loLmt then + exit; + + p1 := InitRecPrime(loLmt); + while p1.rpPrime < LoLmt do + NextPrime(p1); + repeat + inc(result); + NextPrime(p1); + until p1.rpPrime > HiLmt; +end; + +procedure WriteCntSmallPrimes(n: NativeInt); +var + i, p,prPos,svPos : nativeUint; +Begin + dec(n); + IF n < 0 then + EXIT; + write('First ',n+1,' primes '); + IF n < Bis then + Begin + For i := 0 to n do + write(InitPrim[i]:3); + end + else + Begin + For i := 0 to BIS do + write(InitPrim[i],' '); + dec(n,Bis); + + svPos := 0; + PrPos := 0; + p := 1; + while n> 0 do + Begin + {next prime} + inc(svPos); + inc(p,2*(DiffFld[prPos]+1)); + if NOT((svPos and 31) in searchFld[svPos shr 5] )then + Begin + write(p,' '); + dec(n); + end; + inc(prPos); + if prPos = cRepFldLen then + dec(prPos,prPos);// := 0; + end; + end; + writeln; +end; + +var + Anzahl :Uint64; + i : NativeUint; +Begin + SieveAll; + + i := 0; + Anzahl := BIS+1; + //MaxPos = res *cRepFldLen +number[i]; + For i := 0 to MaxPos shr 5-1 do + inc(Anzahl,PopCnt(NOT(Uint32(searchFld[i])))); + i := MaxPos AND 31; + dec(i); + while i>0 do + Begin + IF Not(i in searchFld[MaxPos shr 5]) then + inc(Anzahl); + dec(i); + end; +// Writeln('Bis ',MaxZahl,' sind es ',Anzahl,' Primzahlen'); + WriteCntSmallPrimes(20); + write('Primes between 100 and 150: '); + ShowPrimes(100,150); + write('Number of primes between 7700 and 8000 '); + Writeln(CountPrimes(7700,8000)); + i := 100; + repeat + Writeln('the ',i, ' th prime ',GetNthPrime(i).rpPrime); + i := i * 10; + until i> 1000000; +end. diff --git a/Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 b/Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 new file mode 100644 index 0000000000..8e6a2ff716 --- /dev/null +++ b/Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 @@ -0,0 +1,10 @@ +my @primes := gather for 1 .. * { .take if $_.is-prime } + +say "The first twenty primes:\n ", "[{@primes[^20].fmt("%d", ', ')}]"; +say "The primes between 100 and 150:\n ", "[{@primes.&between(100, 150).fmt("%d", ', ')}]"; +say "The number of primes between 7,700 and 8,000:\n ", +@primes.&between(7700, 8000); +say "The 10,000th prime:\n ", @primes[9999]; + +sub between (@p, $l, $u) { + gather for @p { .take if $l < $_ < $u; last if $_ >= $u } +} diff --git a/Task/Extensible-prime-generator/Perl/extensible-prime-generator-1.pl b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-1.pl new file mode 100644 index 0000000000..2ffd7c2ddd --- /dev/null +++ b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-1.pl @@ -0,0 +1,9 @@ +use Math::Prime::Util qw(nth_prime prime_count primes); +# Direct solutions. +# primes([start],end) returns an array reference with all primes in the range +# prime_count([start],end) uses sieving or LMO to return fast prime counts +# nth_prime(n) does just that. It runs quite fast for native size inputs. +say "First 20: ", join(" ", @{primes(nth_prime(20))}); +say "Between 100 and 150: ", join(" ", @{primes(100,150)}); +say prime_count(7700,8000), " primes between 7700 and 8000"; +say "${_}th prime: ", nth_prime($_) for map { 10**$_ } 1..8; diff --git a/Task/Extensible-prime-generator/Perl/extensible-prime-generator-2.pl b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-2.pl new file mode 100644 index 0000000000..b911f8f42d --- /dev/null +++ b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-2.pl @@ -0,0 +1,12 @@ +use Math::Prime::Util "prime_iterator_object"; +my $it = prime_iterator_object; +say "First 20: ", join(" ", map { $it->iterate() } 1..20); +$it->seek_to_value(100); +print "Between 100 and 150:"; +print " ", $it->iterate() while $it->value() <= 150; +print "\n"; +$it->seek_to_value(7700); +my $c = 0; +$c++ while $it->iterate() <= 8000; +say "$c primes between 7700 and 8000"; +say "${_}th prime: ", $it->ith($_) for map { 10**$_ } 1..8; diff --git a/Task/Extensible-prime-generator/Perl/extensible-prime-generator-3.pl b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-3.pl new file mode 100644 index 0000000000..227eaa9225 --- /dev/null +++ b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-3.pl @@ -0,0 +1,13 @@ +use Math::Prime::Util qw/forprimes/; +use Math::Prime::Util::PrimeArray; +tie my @primes, 'Math::Prime::Util::PrimeArray'; + +say "First 20: @primes[0..19]"; # Slice from the tied array +print "Between 100 and 150: "; forprimes { print " $_"; } 100,150; print "\n"; +# Count with forprimes +my $c = 0; +forprimes { $c++ } 7700,8000; +print "$c primes between 7700 and 8000\n"; +# The tied array tries to do the right thing -- sieve a window if it sees +# forward or backward iteration, and nth_prime if it looks like random access. +say "${_}th prime: ", $primes[$_-1] for map { 10**$_ } 1..8; diff --git a/Task/Extensible-prime-generator/Perl/extensible-prime-generator-4.pl b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-4.pl new file mode 100644 index 0000000000..92aa4c80bf --- /dev/null +++ b/Task/Extensible-prime-generator/Perl/extensible-prime-generator-4.pl @@ -0,0 +1,5 @@ +use bigint; +use Math::Prime::Util qw/forprimes prime_get_config/; +warn "No GMP, expect slow results\n" unless prime_get_config->{gmp}; +my $n = 10**200; +forprimes { say $_-$n } $n,$n+1000; diff --git a/Task/Extensible-prime-generator/Python/extensible-prime-generator-1.py b/Task/Extensible-prime-generator/Python/extensible-prime-generator-1.py new file mode 100644 index 0000000000..44ba33a80b --- /dev/null +++ b/Task/Extensible-prime-generator/Python/extensible-prime-generator-1.py @@ -0,0 +1 @@ +islice(count(7), 0, None, 2) diff --git a/Task/Extensible-prime-generator/Python/extensible-prime-generator-2.py b/Task/Extensible-prime-generator/Python/extensible-prime-generator-2.py new file mode 100644 index 0000000000..e72bbdb2cd --- /dev/null +++ b/Task/Extensible-prime-generator/Python/extensible-prime-generator-2.py @@ -0,0 +1,16 @@ +from __future__ import print_function +from prime_decomposition import primes +from itertools import islice + + +def p_range(lower_inclusive, upper_exclusive): + 'Primes in the range' + for p in primes(): + if p >= upper_exclusive: break + if p >= lower_inclusive: yield p + +if __name__ == '__main__': + print('The first twenty primes:\n ', list(islice(primes(),20))) + print('The primes between 100 and 150:\n ', list(p_range(100, 150))) + print('The ''number'' of primes between 7,700 and 8,000:\n ', len(list(p_range(7700, 8000)))) + print('The 10,000th prime:\n ', next(islice(primes(),10000-1, 10000))) diff --git a/Task/Extensible-prime-generator/README b/Task/Extensible-prime-generator/README new file mode 100644 index 0000000000..d766af0c2a --- /dev/null +++ b/Task/Extensible-prime-generator/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Extensible_prime_generator diff --git a/Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx b/Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx new file mode 100644 index 0000000000..ee0e07d56e --- /dev/null +++ b/Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx @@ -0,0 +1,46 @@ +/*REXX program finds primes using an extendible prime number generator.*/ +parse arg f .; if f=='' then f=20 /*allow specifying # for 1 ──► F.*/ +call primes f; do j=1 for f; $=$ @.j; end +say 'first' f 'primes are:' $ +say +call primes -150; do j=100 to 150; if !.j==0 then iterate; $=$ j; end +say 'the primes between 100 to 150 (inclusive) are:' $ +say +call primes -8000; do j=7700 to 8000; if !.j==0 then iterate; $=$ j; end +say 'the number of primes between 7700 and 8000 (inclusive) is:' words($) +say +call primes 10000 +say 'the 10000th prime is:' @.10000 +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────PRIMES subroutine───────────────────*/ +primes: procedure expose !. s. @. $ #; parse arg H . 1 m .,,$; H=abs(H) +if symbol('!.0')=='LIT' then /*1st time here? Initialize stuff*/ + do; !.=0; @.=0; s.=0 /*!.x=some prime; @.n=Nth prime.*/ + _=2 3 5 7 11 13 17 19 23 /*generate a bunch of low primes.*/ + do #=1 for words(_); p=word(_,#); @.#=p; !.p=1; end + #=#-1; !.0=#; s.#=@.#**2 /*set # to be number of primes.*/ + end /* [↑] done with building low Ps*/ +neg= m<0 /*Neg? Request is for a P value.*/ +if neg then if H<=@.# then return /*Have a high enough P already?*/ + else nop /*used to match the above THEN. */ + else if H<=# then return /*Have a enough primes already ? */ +/*─────────────────────────────────────── [↓] gen more P's within range*/ + do j=@.#+2 by 2 /*find primes until have H Primes*/ + if j//3 ==0 then iterate /*is J divisible by three? */ + if right(j,1)==5 then iterate /*is the right-most digit a "5" ?*/ + if j//7 ==0 then iterate /*is J divisible by seven? */ + if j//11 ==0 then iterate /*is J divisible by eleven? */ + if j//13 ==0 then iterate /*is J divisible by thirteen? */ + if j//17 ==0 then iterate /*is J divisible by seventeen? */ + if j//19 ==0 then iterate /*is J divisible by nineteen? */ + /*[↑] above seven lines saves time*/ + do k=!.0 while s.k<=j /*divide by the known odd primes.*/ + if j//@.k==0 then iterate j /*Is J divisible by P? Not prime.*/ + end /*k*/ /* [↑] divide by odd primes √j.*/ + #=#+1 /*bump number of primes found. */ + @.#=j; s.#=j*j; !.j=1 /*assign to sparse array; prime².*/ + if neg then if H<=@.# then leave /*do we have a high enough prime?*/ + else nop /*used to match the above THEN. */ + else if H<=# then leave /*do we have enough primes yet? */ + end /*j*/ /* [↑] keep generating 'til nuff*/ +return /*return to invoker with more Ps.*/ diff --git a/Task/Extensible-prime-generator/Racket/extensible-prime-generator.rkt b/Task/Extensible-prime-generator/Racket/extensible-prime-generator.rkt new file mode 100644 index 0000000000..e6bf686b66 --- /dev/null +++ b/Task/Extensible-prime-generator/Racket/extensible-prime-generator.rkt @@ -0,0 +1,33 @@ +#lang racket +;; Using the prime functions from: +(require math/number-theory) + +(displayln "Show the first twenty primes.") +(next-primes 1 20) + +(displayln "Show the primes between 100 and 150.") +;; Note that in each of the in-range filters I "add1" to the stop value, so that (in this case) 150 is +;; considered. I'm pretty sure it's not prime... but technology moves so fast nowadays that things +;; might have changed! +(for/list ((i (sequence-filter prime? (in-range 100 (add1 150))))) i) + +(displayln "Show the number of primes between 7,700 and 8,000.") +;; (for/sum (...) 1) counts the values in a sequence +(for/sum ((i (sequence-filter prime? (in-range 7700 (add1 8000))))) 1) + +(displayln "Show the 10,000th prime.") +(nth-prime (sub1 10000)) ; (nth-prime 0) => 2 + +;; If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a +;; system limit, (2^31 or memory overflow for example), then this may be used as long as an +;; explanation of the limits of the prime generator is also given. (Which may include a link +;; to/excerpt from, language documentation). +;; +;; Full details in: +;; [[http://docs.racket-lang.org/math/number-theory.html?q=prime%3F#%28part._primes%29]] +;; When reading the manual, note that "Integer" and "Natural" are unlimited (or bounded by whatever +;; big number representation there is (and the computational complexity of the work being asked). +(define 2^256 (expt 2 256)) +2^256 +(next-prime 2^256) +;; (Oh, and this is a 64-bit laptop, I left my 256-bit PC in the office.) diff --git a/Task/Extensible-prime-generator/Ruby/extensible-prime-generator.rb b/Task/Extensible-prime-generator/Ruby/extensible-prime-generator.rb new file mode 100644 index 0000000000..10d4054d85 --- /dev/null +++ b/Task/Extensible-prime-generator/Ruby/extensible-prime-generator.rb @@ -0,0 +1,6 @@ +require "prime" + +puts Prime.take(20).join(", ") +puts Prime.each(150).drop_while{|pr| pr < 100}.join(", ") +puts Prime.each(8000).drop_while{|pr| pr < 7700}.count +puts Prime.take(10_000).last diff --git a/Task/Extensible-prime-generator/Seed7/extensible-prime-generator.seed7 b/Task/Extensible-prime-generator/Seed7/extensible-prime-generator.seed7 new file mode 100644 index 0000000000..84f1ede0e8 --- /dev/null +++ b/Task/Extensible-prime-generator/Seed7/extensible-prime-generator.seed7 @@ -0,0 +1,64 @@ +$ include "seed7_05.s7i"; + +const func boolean: isPrime (in integer: number) is func + result + var boolean: result is FALSE; + local + var integer: count is 2; + begin + if number = 2 then + result := TRUE; + elsif number > 2 then + while number rem count <> 0 and count * count <= number do + incr(count); + end while; + result := number rem count <> 0; + end if; + end func; + +var integer: currentPrime is 1; +var integer: primeNum is 0; + +const func integer: getPrime is func + result + var integer: prime is 0; + begin + repeat + incr(currentPrime); + until isPrime(currentPrime); + prime := currentPrime; + incr(primeNum); + end func; + +const proc: main is func + local + var integer: aPrime is 0; + var integer: count is 0; + begin + write("First twenty primes:"); + while primeNum < 20 do + write(" " <& getPrime); + end while; + writeln; + repeat + aPrime := getPrime; + until aPrime >= 100; + write("Primes between 100 and 150:"); + while aPrime <= 150 do + write(" " <& aPrime); + aPrime := getPrime; + end while; + writeln; + repeat + aPrime := getPrime; + until aPrime >= 7700; + while aPrime <= 8000 do + incr(count); + aPrime := getPrime; + end while; + writeln("Number of primes between 7,700 and 8,000: " <& count); + repeat + aPrime := getPrime; + until primeNum = 10000; + writeln("The 10,000th prime: " <& getPrime); + end func; diff --git a/Task/Extensible-prime-generator/Tcl/extensible-prime-generator.tcl b/Task/Extensible-prime-generator/Tcl/extensible-prime-generator.tcl new file mode 100644 index 0000000000..e2b36a0664 --- /dev/null +++ b/Task/Extensible-prime-generator/Tcl/extensible-prime-generator.tcl @@ -0,0 +1,54 @@ +package require Tcl 8.6 + +# An iterative version of the Sieve of Eratosthenes. +# Effective limit is the size of memory. +coroutine primes apply {{} { + yield + while 1 {yield [coroutine primes_[incr p] apply {{} { + yield [info coroutine] + set plist {} + for {set n 2} true {incr n} { + set found 0 + foreach p $plist { + if {$n%$p==0} { + set found 1 + break + } + } + if {!$found} { + lappend plist $n + yield $n + } + } + }}]} +}} + +set p [primes] +for {set primes {}} {[llength $primes] < 20} {} { + lappend primes [$p] +} +puts 1st20=[join $primes ,] +rename $p {} + +set p [primes] +for {set primes {}} {[set n [$p]] <= 150} {} { + if {$n >= 100 && $n <= 150} { + lappend primes $n + } +} +puts 100-150=[join $primes ,] +rename $p {} + +set p [primes] +for {set count 0} {[set n [$p]] <= 8000} {} { + incr count [expr {$n>=7700 && $n<=8000}] +} +puts count7700-8000=$count +rename $p {} + +set p [primes] +for {set count 0} {$count < 10000} {incr count} { + set prime [$p] +} +puts prime10000=$prime +rename $p {} diff --git a/Task/Fibonacci-word-fractal/00DESCRIPTION b/Task/Fibonacci-word-fractal/00DESCRIPTION new file mode 100644 index 0000000000..294d009e11 --- /dev/null +++ b/Task/Fibonacci-word-fractal/00DESCRIPTION @@ -0,0 +1,10 @@ +The [[Fibonacci word]] may be represented as a fractal as described [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf here]: + +:For F_wordm start with F_wordCharn=1 +:Draw a segment forward +:If current F_wordChar is 0 +::Turn left if n is even +::Turn right if n is odd +:next n and iterate until end of F_word + +For this task create and display a fractal similar to [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf Fig 1]. diff --git a/Task/Fibonacci-word-fractal/AutoHotkey/fibonacci-word-fractal.ahk b/Task/Fibonacci-word-fractal/AutoHotkey/fibonacci-word-fractal.ahk new file mode 100644 index 0000000000..0c7f7557e4 --- /dev/null +++ b/Task/Fibonacci-word-fractal/AutoHotkey/fibonacci-word-fractal.ahk @@ -0,0 +1,75 @@ +#NoEnv +SetBatchLines, -1 +p := 0.3 ; Segment length (pixels) +F_Word := 30 + +SysGet, Mon, MonitorWorkArea +W := FibWord(F_Word) +d := 1 +x1 := 0 +y1 := MonBottom +Width := A_ScreenWidth +Height := A_ScreenHeight + +If (!pToken := Gdip_Startup()) { + MsgBox, 48, Gdiplus Error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. + ExitApp +} +OnExit, Shutdown + +Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs +Gui, 1: Show, NA + +hwnd1 := WinExist() +hbm := CreateDIBSection(Width, Height) +hdc := CreateCompatibleDC() +obm := SelectObject(hdc, hbm) +G := Gdip_GraphicsFromHDC(hdc) +Gdip_SetSmoothingMode(G, 4) +pPen := Gdip_CreatePen(0xffff0000, 1) + +Loop, Parse, W +{ + if (d = 0) + x2 := x1 + p, y2 := y1 + else if (d = 1 || d = -3) + x2 := x1, y2 := y1 - p + else if (d = 2 || d = -2) + x2 := x1 - p, y2 := y1 + else if (d = 3 || d = -1) + x2 := x1, y2 := y1 + p + Gdip_DrawLine(G, pPen, x1, y1, x2, y2) + if (!Mod(A_Index, 1500)) + UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) + if (A_LoopField = 0) { + if (!Mod(A_Index, 2)) + d += 1 + else + d -= 1 + } + x1 := x2, y1 := y2, d := Mod(d, 4) +} + +Gdip_DeletePen(pPen) +UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height) +SelectObject(hdc, obm) +DeleteObject(hbm) +DeleteDC(hdc) +Gdip_DeleteGraphics(G) +return + +FibWord(n, FW1=1, FW2=0) { + Loop, % n - 2 + FW3 := FW2 FW1, FW1 := FW2, FW2 := FW3 + return FW3 +} + +Esc:: +Shutdown: +Gdip_DeletePen(pPen) +SelectObject(hdc, obm) +DeleteObject(hbm) +DeleteDC(hdc) +Gdip_DeleteGraphics(G) +Gdip_Shutdown(pToken) +ExitApp diff --git a/Task/Fibonacci-word-fractal/C++/fibonacci-word-fractal.cpp b/Task/Fibonacci-word-fractal/C++/fibonacci-word-fractal.cpp new file mode 100644 index 0000000000..3d1e9d6803 --- /dev/null +++ b/Task/Fibonacci-word-fractal/C++/fibonacci-word-fractal.cpp @@ -0,0 +1,168 @@ +#include +#include +using namespace std; + +class myBitmap +{ +public: + myBitmap() : pen( NULL ) {} + ~myBitmap() + { + DeleteObject( pen ); + DeleteDC( hdc ); + DeleteObject( bmp ); + } + + bool create( int w, int h ) + { + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + width = w; height = h; + clear(); + return true; + } + + void clear() + { + ZeroMemory( pBits, width * height * sizeof( DWORD ) ); + } + + void setPenColor( DWORD clr ) + { + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, 1, clr ); + SelectObject( hdc, pen ); + } + + void saveBitmap( string path ) + { + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD* dwpBits; + DWORD wb; + HANDLE file; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + + file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); + + delete [] dwpBits; + } + + HDC getDC() { return hdc; } + int getWidth() { return width; } + int getHeight() { return height; } + +private: + HBITMAP bmp; + HDC hdc; + HPEN pen; + void *pBits; + int width, height; +}; +class fiboFractal +{ +public: + fiboFractal( int l ) + { + bmp.create( 600, 440 ); + bmp.setPenColor( 0x00ff00 ); + createWord( l ); createFractal(); + bmp.saveBitmap( "path_to_save_bitmap" ); + } +private: + void createWord( int l ) + { + string a = "1", b = "0", c; + l -= 2; + while( l-- ) + { c = b + a; a = b; b = c; } + fWord = c; + } + + void createFractal() + { + int n = 1, px = 10, dir, + py = 420, len = 1, + x = 0, y = -len, goingTo = 0; + + HDC dc = bmp.getDC(); + MoveToEx( dc, px, py, NULL ); + for( string::iterator si = fWord.begin(); si != fWord.end(); si++ ) + { + px += x; py += y; + LineTo( dc, px, py ); + if( !( *si - 48 ) ) + { // odd + if( n & 1 ) dir = 1; // right + else dir = 0; // left + switch( goingTo ) + { + case 0: // up + y = 0; + if( dir ){ x = len; goingTo = 1; } + else { x = -len; goingTo = 3; } + break; + case 1: // right + x = 0; + if( dir ) { y = len; goingTo = 2; } + else { y = -len; goingTo = 0; } + break; + case 2: // down + y = 0; + if( dir ) { x = -len; goingTo = 3; } + else { x = len; goingTo = 1; } + break; + case 3: // left + x = 0; + if( dir ) { y = -len; goingTo = 0; } + else { y = len; goingTo = 2; } + } + } + n++; + } + } + + string fWord; + myBitmap bmp; +}; +int main( int argc, char* argv[] ) +{ + fiboFractal ff( 23 ); + return system( "pause" ); +} diff --git a/Task/Fibonacci-word-fractal/D/fibonacci-word-fractal.d b/Task/Fibonacci-word-fractal/D/fibonacci-word-fractal.d new file mode 100644 index 0000000000..f799a17317 --- /dev/null +++ b/Task/Fibonacci-word-fractal/D/fibonacci-word-fractal.d @@ -0,0 +1,22 @@ +import std.range, grayscale_image, turtle; + +void drawFibonacci(Color)(Image!Color img, ref Turtle t, + in string word, in real step) { + foreach (immutable i, immutable c; word) { + t.forward(img, step); + if (c == '0') { + if ((i + 1) % 2 == 0) + t.left(90); + else + t.right(90); + } + } +} + +void main() { + auto img = new Image!Gray(1050, 1050); + auto t = Turtle(30, 1010, -90); + const w = recurrence!q{a[n-1] ~ a[n-2]}("1", "0").drop(24).front; + img.drawFibonacci(t, w, 1); + img.savePGM("fibonacci_word_fractal.pgm"); +} diff --git a/Task/Fibonacci-word-fractal/Icon/fibonacci-word-fractal.icon b/Task/Fibonacci-word-fractal/Icon/fibonacci-word-fractal.icon new file mode 100644 index 0000000000..71ba99dcac --- /dev/null +++ b/Task/Fibonacci-word-fractal/Icon/fibonacci-word-fractal.icon @@ -0,0 +1,57 @@ +global width, height + +procedure main(A) + n := integer(A[1]) | 25 # F_word to use + sl := integer(A[2]) | 1 # Segment length + width := integer(A[3]) | 1050 # Width of plot area + height := integer(A[4]) | 1050 # Height of plot area + w := fword(n) + drawFractal(n,w,sl) +end + +procedure fword(n) + static fcache + initial fcache := table() + /fcache[n] := case n of { + 1: "1" + 2: "0" + default: fword(n-1)||fword(n-2) + } + return fcache[n] +end + +record loc(x,y) + +procedure drawFractal(n,w,sl) + static lTurn, rTurn + initial { + every (lTurn|rTurn) := table() + lTurn["north"] := "west"; lTurn["west"] := "south" + lTurn["south"] := "east"; lTurn["east"] := "north" + rTurn["north"] := "east"; rTurn["east"] := "south" + rTurn["south"] := "west"; rTurn["west"] := "north" + } + + wparms := ["FibFractal "||n,"g","bg=white","canvas=normal", + "fg=black","size="||width||","||height,"dx=10","dy=10"] + &window := open!wparms | stop("Unable to open window") + p := loc(10,10) + d := "north" + every i := 1 to *w do { + p := draw(p,d,sl) + if w[i] == "0" then d := if i%2 = 0 then lTurn[d] else rTurn[d] + } + + until Event() == &lpress + WriteImage("FibFract"||n||".png") + close(&window) +end + +procedure draw(p,d,sl) + if d == "north" then p1 := loc(p.x,p.y+sl) + else if d == "south" then p1 := loc(p.x,p.y-sl) + else if d == "east" then p1 := loc(p.x+sl,p.y) + else p1 := loc(p.x-sl,p.y) + DrawLine(p.x,p.y, p1.x,p1.y) + return p1 +end diff --git a/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-1.j b/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-1.j new file mode 100644 index 0000000000..da03bf05df --- /dev/null +++ b/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-1.j @@ -0,0 +1,2 @@ +require 'plot' +plot }:+/\ 0,*/\(^~ 0j_1 0j1 $~ #)'0'=_1{::F_Words 20 diff --git a/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-2.j b/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-2.j new file mode 100644 index 0000000000..814678dda6 --- /dev/null +++ b/Task/Fibonacci-word-fractal/J/fibonacci-word-fractal-2.j @@ -0,0 +1 @@ +F_Words=: (,<@;@:{~&_1 _2)@]^:(2-~[)&('1';'0') diff --git a/Task/Fibonacci-word-fractal/Logo/fibonacci-word-fractal.logo b/Task/Fibonacci-word-fractal/Logo/fibonacci-word-fractal.logo new file mode 100644 index 0000000000..39a5c508d8 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Logo/fibonacci-word-fractal.logo @@ -0,0 +1,29 @@ +; Return the low 1-bits of :n +; For example if n = binary 10110111 = 183 +; then return binary 111 = 7 +to low.ones :n + output ashift (bitxor :n (:n+1)) -1 +end + +; :fibbinary should be a fibbinary value +; return the next larger fibbinary value +to fibbinary.next :fibbinary + localmake "filled bitor :fibbinary (ashift :fibbinary -1) + localmake "mask low.ones :filled + output (bitor :fibbinary :mask) + 1 +end + +to fibonacci.word.fractal :steps + localmake "step.length 5 ; length of each step + localmake "fibbinary 0 + repeat :steps [ + forward :step.length + if (bitand 1 :fibbinary) = 0 [ + ifelse (bitand repcount 1) = 1 [right 90] [left 90] + ] + make "fibbinary fibbinary.next :fibbinary + ] +end + +setheading 0 ; initial line North +fibonacci.word.fractal 377 diff --git a/Task/Fibonacci-word-fractal/Mathematica/fibonacci-word-fractal.math b/Task/Fibonacci-word-fractal/Mathematica/fibonacci-word-fractal.math new file mode 100644 index 0000000000..6629c641dc --- /dev/null +++ b/Task/Fibonacci-word-fractal/Mathematica/fibonacci-word-fractal.math @@ -0,0 +1,16 @@ +(*note, this usage of Module allows us to memoize FibonacciWord + without exposing it to the global scope*) +Module[{FibonacciWord, step}, + FibonacciWord[1] = "1"; + FibonacciWord[2] = "0"; + FibonacciWord[n_Integer?(# > 2 &)] := + (FibonacciWord[n] = FibonacciWord[n - 1] <> FibonacciWord[n - 2]); + + step["0", {_?EvenQ}] = N@RotationTransform[Pi/2]; + step["0", {_?OddQ}] = N@RotationTransform[-Pi/2]; + step[___] = Identity; + + FibonacciFractal[n_] := Module[{steps, dirs}, + steps = MapIndexed[step, Characters[FibonacciWord[n]]]; + dirs = ComposeList[steps, {0, 1}]; + Graphics[Line[FoldList[Plus, {0, 0}, dirs]]]]]; diff --git a/Task/Fibonacci-word-fractal/Perl-6/fibonacci-word-fractal.pl6 b/Task/Fibonacci-word-fractal/Perl-6/fibonacci-word-fractal.pl6 new file mode 100644 index 0000000000..42cbbb32ba --- /dev/null +++ b/Task/Fibonacci-word-fractal/Perl-6/fibonacci-word-fractal.pl6 @@ -0,0 +1,56 @@ +constant @fib-word = '1', '0', { $^b ~ $^a } ... *; + +sub MAIN($m = 17, $scale = 3) { + (my %world){0}{0} = 1; + my $loc = 0+0i; + my $dir = i; + my $n = 1; + + for @fib-word[$m].comb { + when '0' { + step; + if $n %% 2 { turn-left } + else { turn-right; } + } + $n++; + } + + braille-graphics %world; + + sub step { + for ^$scale { + $loc += $dir; + %world{$loc.im}{$loc.re} = 1; + } + } + + sub turn-left { $dir *= i; } + sub turn-right { $dir *= -i; } + +} + +sub braille-graphics (%a) { + my ($ylo, $yhi, $xlo, $xhi); + for %a.keys -> $y { + $ylo min= +$y; $yhi max= +$y; + for %a{$y}.keys -> $x { + $xlo min= +$x; $xhi max= +$x; + } + } + + for $ylo, $ylo + 4 ...^ * > $yhi -> \y { + for $xlo, $xlo + 2 ...^ * > $xhi -> \x { + my $cell = 0x2800; + $cell += 1 if %a{y + 0}{x + 0}; + $cell += 2 if %a{y + 1}{x + 0}; + $cell += 4 if %a{y + 2}{x + 0}; + $cell += 8 if %a{y + 0}{x + 1}; + $cell += 16 if %a{y + 1}{x + 1}; + $cell += 32 if %a{y + 2}{x + 1}; + $cell += 64 if %a{y + 3}{x + 0}; + $cell += 128 if %a{y + 3}{x + 1}; + print chr($cell); + } + print "\n"; + } +} diff --git a/Task/Fibonacci-word-fractal/Perl/fibonacci-word-fractal.pl b/Task/Fibonacci-word-fractal/Perl/fibonacci-word-fractal.pl new file mode 100644 index 0000000000..66b0768632 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Perl/fibonacci-word-fractal.pl @@ -0,0 +1,36 @@ +use strict; +use warnings; +use GD; + +my @fword = ( undef, 1, 0 ); + +sub fword { + my $n = shift; + return $fword[$n] if $n<3; + return $fword[$n] //= fword($n-1).fword($n-2); +} + +my $size = 3000; +my $im = new GD::Image($size,$size); +my $white = $im->colorAllocate(255,255,255); +my $black = $im->colorAllocate(0,0,0); +$im->transparent($white); +$im->interlaced('true'); + +my @pos = (0,0); +my @dir = (0,5); +my @steps = split //, fword 23; +my $i = 1; +for( @steps ) { + my @next = ( $pos[0]+$dir[0], $pos[1]+$dir[1] ); + $im->line( @pos, @next, $black ); + @dir = ( $dir[1], -$dir[0] ) if 0==$_ && 1==$i%2; # odd + @dir = ( -$dir[1], $dir[0] ) if 0==$_ && 0==$i%2; # even + $i++; + @pos = @next; +} + +open my $out, ">", "fword.png" or die "Cannot open output file.\n"; +binmode $out; +print $out $im->png; +close $out; diff --git a/Task/Fibonacci-word-fractal/Python/fibonacci-word-fractal.py b/Task/Fibonacci-word-fractal/Python/fibonacci-word-fractal.py new file mode 100644 index 0000000000..8dbdbf5978 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Python/fibonacci-word-fractal.py @@ -0,0 +1,58 @@ +from functools import wraps +from turtle import * + +def memoize(obj): + cache = obj.cache = {} + @wraps(obj) + def memoizer(*args, **kwargs): + key = str(args) + str(kwargs) + if key not in cache: + cache[key] = obj(*args, **kwargs) + return cache[key] + return memoizer + +@memoize +def fibonacci_word(n): + assert n > 0 + if n == 1: + return "1" + if n == 2: + return "0" + return fibonacci_word(n - 1) + fibonacci_word(n - 2) + +def draw_fractal(word, step): + for i, c in enumerate(word, 1): + forward(step) + if c == "0": + if i % 2 == 0: + left(90) + else: + right(90) + +def main(): + n = 25 # Fibonacci Word to use. + step = 1 # Segment length. + width = 1050 # Width of plot area. + height = 1050 # Height of plot area. + w = fibonacci_word(n) + + setup(width=width, height=height) + speed(0) + setheading(90) + left(90) + penup() + forward(500) + right(90) + backward(500) + pendown() + tracer(10000) + hideturtle() + + draw_fractal(w, step) + + # Save Poscript image. + getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps") + exitonclick() + +if __name__ == '__main__': + main() diff --git a/Task/Fibonacci-word-fractal/README b/Task/Fibonacci-word-fractal/README new file mode 100644 index 0000000000..2b77518bac --- /dev/null +++ b/Task/Fibonacci-word-fractal/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Fibonacci_word/fractal diff --git a/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx b/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx new file mode 100644 index 0000000000..b3610187cd --- /dev/null +++ b/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx @@ -0,0 +1,36 @@ +/*REXX program generates a Fibonacci word, then plots the fractal curve.*/ +parse arg ord . /*obtain optional arg from the CL*/ +if ord=='' then ord=23 /*Not specified? Then use default*/ +s=fibWord(ord) /*obtain the ORD fib word. */ +x=0; y=0; maxX=0; maxY=0; dx=0; dy=1; @.=' '; xp=0; yp=0; @.0.0=. + + do n=1 for length(s); x=x+dx; y=y+dy /*advance the plot for next point*/ + maxX=max(maxX,x); maxY=max(maxY,y) /*set the maximums for displaying*/ + c='│'; if dx\==0 then c='─'; if n==1 then c='┌' /*1st plot.*/ + @.x.y=c /*assign a plotting character. */ + if @(xp-1,yp)\==' ' & @(xp,yp-1)\==' ' then call @ xp,yp,'┐' /*fixup*/ + if @(xp-1,yp)\==' ' & @(xp,yp+1)\==' ' then call @ xp,yp,'┘' /* " */ + if @(xp+1,yp)\==' ' & @(xp,yp+1)\==' ' then call @ xp,yp,'└' /* " */ + if @(xp+1,yp)\==' ' & @(xp,yp-1)\==' ' then call @ xp,yp,'┌' /* " */ + xp=x; yp=y; z=substr(s,n,1) /*save old x,y; assign plot char*/ + if z==1 then iterate /*if Z is a "one", then skip it.*/ + ox=dx; oy=dy; dx=0; dy=0 /*save DX,DY as the old versions.*/ + d=-n//2; if d==0 then d=1 /*determine sign for chirality. */ + if oy\==0 then dx=-sign(oy)*d /*Going north|south? Go east|west*/ + if ox\==0 then dy= sign(ox)*d /* " east|west? " south|north*/ + end /*n*/ + +call @ x,y,'∙' /*signify the last point plotted.*/ + do r=maxY to 0 by -1; _= /*show a row at a time, top 1st.*/ + do c=0 to maxX; _=_||@.c.r; end /*c*/ + if _\='' then say strip(_,'T') /*if not blank, then show a line.*/ + end /*r*/ /* [↑] only show non-blank rows.*/ +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────@ subroutine─────────────────────────*/ +@: parse arg xx,yy,p; if arg(3)=='' then return @.xx.yy; @.xx.yy=p; return +/*─────────────────────────────────FIBWORD subroutine───────────────────*/ +fibWord: procedure; arg x; !.=0; !.1=1 /*obtain the order of fib word. */ + do k=3 to x; k1=k-1; k2=k-2 /*generate the Kth Fibonacci word*/ + !.k=!.k1 || !.k2 /*construct the next FIB word. */ + end /*k*/ /* [↑] generate Fibonacci words.*/ +return !.x /*return the Xth fib word. */ diff --git a/Task/Fibonacci-word-fractal/Racket/fibonacci-word-fractal.rkt b/Task/Fibonacci-word-fractal/Racket/fibonacci-word-fractal.rkt new file mode 100644 index 0000000000..a74f52a943 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Racket/fibonacci-word-fractal.rkt @@ -0,0 +1,21 @@ +#lang racket +(require "Fibonacci-word.rkt") +(require graphics/value-turtles) + +(define word-order 23) ; is a 3k+2 fractal, shaped like an n +(define height 420) +(define width 600) + +(define the-word + (parameterize ((f-word-max-length #f)) + (F-Word word-order))) + +(for/fold ((T (turtles width height + 0 height ; in BL corner + (/ pi -2)))) ; point north + ((i (in-naturals)) + (j (in-string (f-word-str the-word)))) + (match* (i j) + ((_ #\1) (draw 1 T)) + (((? even?) #\0) (turn -90 (draw 1 T))) + ((_ #\0) (turn 90 (draw 1 T))))) diff --git a/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb b/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb new file mode 100644 index 0000000000..9d67c865ca --- /dev/null +++ b/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb @@ -0,0 +1,32 @@ +def fibonacci_word(n) + words = ["1", "0"] + (words.size..n).each do |i| + words << words[i-1] + words[i-2] + end + words[n] +end + +def print_fractal(word) + area = Hash.new(" ") + x = y = 0 + dx, dy = 0, -1 + area[[x,y]] = "S" + word.each_char.with_index(1) do |c,n| + area[[x+dx, y+dy]] = dx.zero? ? "|" : "-" + x, y = x+2*dx, y+2*dy + area[[x, y]] = "+" + dx,dy = n.even? ? [dy,-dx] : [-dy,dx] if c=="0" + end + + xmin, xmax = area.each_key.map(&:first).minmax + ymin, ymax = area.each_key.map(&:last).minmax + for y in ymin..ymax + for x in xmin..xmax + print area[[x,y]] + end + puts + end +end + +word = fibonacci_word(11) +print_fractal(word) diff --git a/Task/Fibonacci-word-fractal/Scala/fibonacci-word-fractal.scala b/Task/Fibonacci-word-fractal/Scala/fibonacci-word-fractal.scala new file mode 100644 index 0000000000..ce8e455edb --- /dev/null +++ b/Task/Fibonacci-word-fractal/Scala/fibonacci-word-fractal.scala @@ -0,0 +1,47 @@ +def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1) + +def turnLeft(c: Char): Char = c match { + case 'R' => 'U' + case 'U' => 'L' + case 'L' => 'D' + case 'D' => 'R' +} + +def turnRight(c: Char): Char = c match { + case 'R' => 'D' + case 'D' => 'L' + case 'L' => 'U' + case 'U' => 'R' +} + +def directions(xss: List[(Char,Char)], current: Char = 'R'): List[Char] = xss match { + case Nil => current :: Nil + case x :: xs => x._1 match { + case '1' => current :: directions(xs, current) + case '0' => x._2 match { + case 'E' => current :: directions(xs, turnLeft(current)) + case 'O' => current :: directions(xs, turnRight(current)) + } + } +} + +def buildIt(xss: List[Char], old: Char = 'X', count: Int = 1): List[String] = xss match { + case Nil => s"$old$count" :: Nil + case x :: xs if x == old => buildIt(xs,old,count+1) + case x :: xs => s"$old$count" :: buildIt(xs,x) +} + +def convertToLine(s: String, c: Int): String = (s.head, s.tail) match { + case ('R',n) => s"l ${c * n.toInt} 0" + case ('U',n) => s"l 0 ${-c * n.toInt}" + case ('L',n) => s"l ${-c * n.toInt} 0" + case ('D',n) => s"l 0 ${c * n.toInt}" +} + +def drawSVG(xStart: Int, yStart: Int, width: Int, height: Int, fibWord: String, lineMultiplier: Int, color: String): String = { + val xs = fibWord.zipWithIndex.map{case (c,i) => (c, if(c == '1') '_' else i % 2 match{case 0 => 'E'; case 1 => 'O'})}.toList + val fractalPath = buildIt(directions(xs)).tail.map(convertToLine(_,lineMultiplier)) + s"""""" +} + +drawSVG(0,25,550,530,fibIt.drop(18).next,3,"000") diff --git a/Task/Fibonacci-word-fractal/Tcl/fibonacci-word-fractal.tcl b/Task/Fibonacci-word-fractal/Tcl/fibonacci-word-fractal.tcl new file mode 100644 index 0000000000..c94c13386f --- /dev/null +++ b/Task/Fibonacci-word-fractal/Tcl/fibonacci-word-fractal.tcl @@ -0,0 +1,44 @@ +package require Tk + +# OK, this stripped down version doesn't work for n<2… +proc fibword {n} { + set fw {1 0} + while {[llength $fw] < $n} { + lappend fw [lindex $fw end][lindex $fw end-1] + } + return [lindex $fw end] +} +proc drawFW {canv fw {w {[$canv cget -width]}} {h {[$canv cget -height]}}} { + set w [subst $w] + set h [subst $h] + + # Generate the coordinate list using line segments of unit length + set d 3; # Match the orientation in the sample paper + set eo [set x [set y 0]] + set coords [list $x $y] + foreach c [split $fw ""] { + switch $d { + 0 {lappend coords [incr x] $y} + 1 {lappend coords $x [incr y]} + 2 {lappend coords [incr x -1] $y} + 3 {lappend coords $x [incr y -1]} + } + if {$c == 0} { + set d [expr {($d + ($eo ? -1 : 1)) % 4}] + } + set eo [expr {!$eo}] + } + + # Draw, and rescale to fit in canvas + set id [$canv create line $coords] + lassign [$canv bbox $id] x1 y1 x2 y2 + set sf [expr {min(($w-20.) / ($y2-$y1), ($h-20.) / ($x2-$x1))}] + $canv move $id [expr {-$x1}] [expr {-$y1}] + $canv scale $id 0 0 $sf $sf + $canv move $id 10 10 + # Return the item ID to allow user reconfiguration + return $id +} + +pack [canvas .c -width 500 -height 500] +drawFW .c [fibword 23] diff --git a/Task/Fibonacci-word/00DESCRIPTION b/Task/Fibonacci-word/00DESCRIPTION new file mode 100644 index 0000000000..ebca0da00f --- /dev/null +++ b/Task/Fibonacci-word/00DESCRIPTION @@ -0,0 +1,12 @@ +The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence [http://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf as described here]: + +: Define F_Word1 as 1; +: Define F_Word2 as 0; +: Form F_Word3 as F_Word2 concatenated with F_Word1 i.e "01" +: Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 + +For this task we shall do this for n = 37. You may display the first few but not the larger values of n, doing so will get me into trouble with them what be (again!). + +Instead create a table for F_Words 1 to 37 which shows: +:The number of characters in the word +:The word's [[Entropy]]. diff --git a/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg b/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg new file mode 100644 index 0000000000..cdeda9d346 --- /dev/null +++ b/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg @@ -0,0 +1,118 @@ +# calculate some details of "Fibonacci Words" # + +# fibonacci word 1 = "1" # +# fibonacci word 2 = "0" # +# 3 = word 2 cat word 1 = "01" # +# n = word n-1 cat word n-2 # + +# note the words contain only the characters "0" and "1" # +# also # +# C(word n) = C(word n-1) + C(word n-2) # +# where C(x) = the number of characters in x # +# Similarly, # +# C0(word n) = C0(word n-1) + C0(word n-2) # +# and C1(word n) = C1(word n-1) + C1(word n-2) # +# where C0(x) = the number of "0"s in x and # +# C1(x) = the number of "1"s in x # + +# we therefore don't have to calculate the words themselves # + + +# prints the statistics for the fibonacci words from 1 to max number # +PROC print fibonacci word stats = ( INT max number )VOID: +BEGIN + + + # prints some statistics for a fibonacci word: # + # the word number, its length and its entropy # + PROC print one words stats = ( INT word + , INT zeros + , INT ones + )VOID: + BEGIN + + REAL probability := 0; + REAL entropy := 0; + INT word length = zeros + ones; + + IF zeros > 0 + THEN + # the word contains some zeros # + probability := zeros / word length; + entropy -:= probability * log( probability ) + FI; + + IF ones > 0 + THEN + # the word contains some ones # + probability := ones / word length; + entropy -:= probability * log( probability ) + FI; + + # we want entropy in bits so convert to log base 2 # + entropy /:= log( 2 ); + + print( ( ( whole( word, -5 ) + + " " + + whole( word length, -12 ) + + " " + + fixed( entropy, -8, 4 ) + ) + , newline + ) + ) + + + END; # print one words stats # + + + INT zeros one = 0; # number of zeros in word 1 # + INT ones one = 1; # number of ones in word 1 # + INT zeros two = 1; # number of zeros in word 2 # + INT ones two = 0; # number of ones in word 2 # + + print( ( " word length entropy", newline ) ); + + IF max number > 0 + THEN + # we want at least one number's statistics # + print one words stats( 1, zeros one, ones one ); + + IF max number > 1 + THEN + # we want at least 2 number's statistics # + print one words stats( 2, zeros two, ones two ); + + IF max number > 2 + THEN + # we want more statistics # + + INT zeros n minus 1 := zeros two; + INT ones n minus 1 := ones two; + INT zeros n minus 2 := zeros one; + INT ones n minus 2 := ones one; + + FOR word FROM 3 TO max number DO + + INT zeros n := zeros n minus 1 + zeros n minus 2; + INT ones n := ones n minus 1 + ones n minus 2; + + print one words stats( word, zeros n, ones n ); + + zeros n minus 2 := zeros n minus 1; + ones n minus 2 := ones n minus 1; + zeros n minus 1 := zeros n; + ones n minus 1 := ones n + OD + FI + FI + FI + +END; # print fibonacci word stats # + + +main: +( + # print the statistics for the first 37 fibonacci words # + print fibonacci word stats( 37 ) +) diff --git a/Task/Fibonacci-word/Ada/fibonacci-word.ada b/Task/Fibonacci-word/Ada/fibonacci-word.ada new file mode 100644 index 0000000000..85eea4237c --- /dev/null +++ b/Task/Fibonacci-word/Ada/fibonacci-word.ada @@ -0,0 +1,56 @@ +with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded, + Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions, + Ada.Long_Float_Text_IO; +use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded, + Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions, + Ada.Long_Float_Text_IO; + +procedure Fibonacci_Words is + + function Entropy (S : Unbounded_String) return Long_Float is + CF : array (Character) of Natural := (others => 0); + Len : constant Natural := Length (S); + H : Long_Float := 0.0; + Ratio : Long_Float; + begin + for I in 1 .. Len loop + CF (Element (S, I)) := CF (Element (S, I)) + 1; + end loop; + for C in Character loop + Ratio := Long_Float (CF (C)) / Long_Float (Len); + if Ratio /= 0.0 then + H := H - Ratio * Log (Ratio, 2.0); + end if; + end loop; + return H; + end Entropy; + + procedure Print_Line (Word : Unbounded_String; Number : Integer) is + begin + Put (Number, 4); + Put (Length (Word), 10); + Put (Entropy (Word), 2, 15, 0); + if Length (Word) < 35 then + Put (" " & Word); + end if; + New_Line; + end Print_Line; + + First, Second, Result : Unbounded_String; + +begin + Set_Col (4); Put ("N"); + Set_Col (9); Put ("Length"); + Set_Col (16); Put ("Entropy"); + Set_Col (35); Put_Line ("Word"); + First := To_Unbounded_String ("1"); + Print_Line (First, 1); + Second := To_Unbounded_String ("0"); + Print_Line (Second, 2); + for N in 3 .. 37 loop + Result := Second & First; + Print_Line (Result, N); + First := Second; + Second := Result; + end loop; +end Fibonacci_Words; diff --git a/Task/Fibonacci-word/AutoHotkey/fibonacci-word.ahk b/Task/Fibonacci-word/AutoHotkey/fibonacci-word.ahk new file mode 100644 index 0000000000..47340bfcf4 --- /dev/null +++ b/Task/Fibonacci-word/AutoHotkey/fibonacci-word.ahk @@ -0,0 +1,28 @@ +SetFormat, FloatFast, 0.15 +SetBatchLines, -1 +OutPut := "N`tLength`t`tEntropy`n" + . "1`t" 1 "`t`t" Entropy(FW1 := "1") "`n" + . "2`t" 1 "`t`t" Entropy(FW2 := "0") "`n" +Loop, 35 +{ + FW3 := FW2 FW1, FW1 := FW2, FW2 := FW3 + Output .= A_Index + 2 "`t" StrLen(FW3) (A_Index > 33 ? "" : "`t") "`t" Entropy(FW3) "`n" +} +MsgBox, % Output + +Entropy(n) +{ + a := [], len:= StrLen(n), m := n + while StrLen(m) + { + s := SubStr(m, 1, 1) + m := RegExReplace(m, s, "", c) + a[s] := c + } + for key, val in a + { + m := Log(p := val / len) + e -= p * m / Log(2) + } + return, e +} diff --git a/Task/Fibonacci-word/C++/fibonacci-word.cpp b/Task/Fibonacci-word/C++/fibonacci-word.cpp new file mode 100644 index 0000000000..3c7471459d --- /dev/null +++ b/Task/Fibonacci-word/C++/fibonacci-word.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +#include + +double log2( double number ) { + return ( log( number ) / log( 2 ) ) ; +} + +double find_entropy( std::string & fiboword ) { + std::map frequencies ; + std::for_each( fiboword.begin( ) , fiboword.end( ) , + [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; + int numlen = fiboword.length( ) ; + double infocontent = 0 ; + for ( std::pair p : frequencies ) { + double freq = static_cast( p.second ) / numlen ; + infocontent += freq * log2( freq ) ; + } + infocontent *= -1 ; + return infocontent ; +} + +void printLine( std::string &fiboword , int n ) { + std::cout << std::setw( 5 ) << std::left << n ; + std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; + std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) + << std::left << find_entropy( fiboword ) ; + std::cout << "\n" ; +} + +int main( ) { + std::cout << std::setw( 5 ) << std::left << "N" ; + std::cout << std::setw( 12 ) << std::right << "length" ; + std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; + std::cout << "\n" ; + std::string firststring ( "1" ) ; + int n = 1 ; + printLine( firststring , n ) ; + std::string secondstring( "0" ) ; + n++ ; + printLine( secondstring , n ) ; + while ( n < 37 ) { + std::string resultstring = firststring + secondstring ; + firststring.assign( secondstring ) ; + secondstring.assign( resultstring ) ; + n++ ; + printLine( resultstring , n ) ; + } + return 0 ; +} diff --git a/Task/Fibonacci-word/C/fibonacci-word.c b/Task/Fibonacci-word/C/fibonacci-word.c new file mode 100644 index 0000000000..43e627529b --- /dev/null +++ b/Task/Fibonacci-word/C/fibonacci-word.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include + +void print_headings() +{ + printf("%2s", "N"); + printf(" %10s", "Length"); + printf(" %-20s", "Entropy"); + printf(" %-40s", "Word"); + printf("\n"); +} + +double calculate_entropy(int ones, int zeros) +{ + double result = 0; + + int total = ones + zeros; + result -= (double) ones / total * log2((double) ones / total); + result -= (double) zeros / total * log2((double) zeros / total); + + if (result != result) { // NAN + result = 0; + } + + return result; +} + +void print_entropy(char *word) +{ + int ones = 0; + int zeros = 0; + + int i; + for (i = 0; word[i]; i++) { + char c = word[i]; + + switch (c) { + case '0': + zeros++; + break; + case '1': + ones++; + break; + } + } + + double entropy = calculate_entropy(ones, zeros); + printf(" %-20.18f", entropy); +} + +void print_word(int n, char *word) +{ + printf("%2d", n); + + printf(" %10ld", strlen(word)); + + print_entropy(word); + + if (n < 10) { + printf(" %-40s", word); + } else { + printf(" %-40s", "..."); + } + + printf("\n"); +} + +int main(int argc, char *argv[]) +{ + print_headings(); + + char *last_word = malloc(2); + strcpy(last_word, "1"); + + char *current_word = malloc(2); + strcpy(current_word, "0"); + + print_word(1, last_word); + int i; + for (i = 2; i <= 37; i++) { + print_word(i, current_word); + + char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); + strcpy(next_word, current_word); + strcat(next_word, last_word); + + free(last_word); + last_word = current_word; + current_word = next_word; + } + + free(last_word); + free(current_word); + return 0; +} diff --git a/Task/Fibonacci-word/Clojure/fibonacci-word.clj b/Task/Fibonacci-word/Clojure/fibonacci-word.clj new file mode 100644 index 0000000000..61b6c49762 --- /dev/null +++ b/Task/Fibonacci-word/Clojure/fibonacci-word.clj @@ -0,0 +1,18 @@ +(defn entropy [s] + (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 +)))) + +(defn fibonacci [cat a b] + (lazy-seq + (cons a (fibonacci b (cat a b))))) + +; you could also say (fibonacci + 0 1) or (fibonacci concat '(0) '(1)) + +(printf "%2s %10s %17s %s%n" "N" "Length" "Entropy" "Fibword") +(doseq [i (range 1 38) + w (take 37 (fibonacci str "1" "0"))] + (printf "%2d %10d %.15f %s%n" i (count w) (entropy w) (if (<= i 8) w "...")))) diff --git a/Task/Fibonacci-word/D/fibonacci-word.d b/Task/Fibonacci-word/D/fibonacci-word.d new file mode 100644 index 0000000000..0a7750b032 --- /dev/null +++ b/Task/Fibonacci-word/D/fibonacci-word.d @@ -0,0 +1,23 @@ +import std.stdio, std.algorithm, std.math, std.string, std.range; + +real entropy(T)(T[] s) pure nothrow +if (__traits(compiles, s.sort())) { + immutable sLen = s.length; + return s + .sort() + .group + .map!(g => g[1] / real(sLen)) + .map!(p => -p * p.log2) + .sum; +} + +void main() { + enum uint nMax = 37; + + " N Length Entropy Fibword".writeln; + uint n = 1; + foreach (s; recurrence!q{a[n - 1] ~ a[n - 2]}("1", "0").take(nMax)) + writefln("%3d %10d %2.19f %s", n++, s.length, + s.dup.representation.entropy.abs, + s.length < 25 ? s : ""); +} diff --git a/Task/Fibonacci-word/Go/fibonacci-word.go b/Task/Fibonacci-word/Go/fibonacci-word.go new file mode 100644 index 0000000000..97f1576c5a --- /dev/null +++ b/Task/Fibonacci-word/Go/fibonacci-word.go @@ -0,0 +1,61 @@ +package main + +import ( + "fmt" + "math" +) + +// From http://rosettacode.org/wiki/Entropy#Go +func entropy(s string) float64 { + m := map[rune]float64{} + for _, r := range s { + m[r]++ + } + hm := 0. + for _, c := range m { + hm += c * math.Log2(c) + } + l := float64(len(s)) + return math.Log2(l) - hm/l +} + +const F_Word1 = "1" +const F_Word2 = "0" + +func FibonacciWord(n int) string { + a, b := F_Word1, F_Word2 + for ; n > 1; n-- { + a, b = b, b+a + } + return a +} + +func FibonacciWordGen() <-chan string { + ch := make(chan string) + go func() { + a, b := F_Word1, F_Word2 + for { + ch <- a + a, b = b, b+a + } + }() + return ch +} + +func main() { + fibWords := FibonacciWordGen() + fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word") + n := 1 + for ; n < 10; n++ { + s := <-fibWords + // Just to show the function and generator do the same thing: + if s2 := FibonacciWord(n); s != s2 { + fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) + } + fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s) + } + for ; n <= 37; n++ { + s := <-fibWords + fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s)) + } +} diff --git a/Task/Fibonacci-word/Haskell/fibonacci-word.hs b/Task/Fibonacci-word/Haskell/fibonacci-word.hs new file mode 100644 index 0000000000..8ca9a7ec00 --- /dev/null +++ b/Task/Fibonacci-word/Haskell/fibonacci-word.hs @@ -0,0 +1,25 @@ +module Main where + +import Control.Monad +import Data.List +import Data.Monoid +import Text.Printf + +entropy :: (Ord a) => [a] -> Double +entropy = sum + . map (\c -> (c *) . logBase 2 $ 1.0 / c) + . (\cs -> let { sc = sum cs } in map (/ sc) cs) + . map (fromIntegral . length) + . group + . sort + +fibonacci :: (Monoid m) => m -> m -> [m] +fibonacci a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) (a,b) + +main :: IO () +main = do + printf "%2s %10s %17s %s\n" "N" "length" "entropy" "word" + zipWithM_ (\i v -> let { l = length v } in printf "%2d %10d %.15f %s\n" + i l (entropy v) (if l > 40 then "..." else v)) + [1..38::Int] + (take 37 $ fibonacci "1" "0") diff --git a/Task/Fibonacci-word/Icon/fibonacci-word.icon b/Task/Fibonacci-word/Icon/fibonacci-word.icon new file mode 100644 index 0000000000..1cb0f82c2a --- /dev/null +++ b/Task/Fibonacci-word/Icon/fibonacci-word.icon @@ -0,0 +1,27 @@ +procedure main(A) + n := integer(A[1]) | 37 + write(right("N",4)," ",right("length",15)," ",left("Entrophy",15)," ", + " Fibword") + every w := fword(i := 1 to n) do { + writes(right(i,4)," ",right(*w,15)," ",left(H(w),15)) + if i <= 8 then write(": ",w) else write() + } +end + +procedure fword(n) + static fcache + initial fcache := table() + /fcache[n] := case n of { + 1: "1" + 2: "0" + default: fword(n-1)||fword(n-2) + } + return fcache[n] +end + +procedure H(s) + P := table(0.0) + every P[!s] +:= 1.0/*s + every (h := 0.0) -:= P[c := key(P)] * log(P[c],2) + return h +end diff --git a/Task/Fibonacci-word/J/fibonacci-word-1.j b/Task/Fibonacci-word/J/fibonacci-word-1.j new file mode 100644 index 0000000000..814678dda6 --- /dev/null +++ b/Task/Fibonacci-word/J/fibonacci-word-1.j @@ -0,0 +1 @@ +F_Words=: (,<@;@:{~&_1 _2)@]^:(2-~[)&('1';'0') diff --git a/Task/Fibonacci-word/J/fibonacci-word-2.j b/Task/Fibonacci-word/J/fibonacci-word-2.j new file mode 100644 index 0000000000..0d1c9be204 --- /dev/null +++ b/Task/Fibonacci-word/J/fibonacci-word-2.j @@ -0,0 +1 @@ +entropy=: +/@:-@(* 2&^.)@(#/.~ % #) diff --git a/Task/Fibonacci-word/J/fibonacci-word-3.j b/Task/Fibonacci-word/J/fibonacci-word-3.j new file mode 100644 index 0000000000..b8fd3e0c87 --- /dev/null +++ b/Task/Fibonacci-word/J/fibonacci-word-3.j @@ -0,0 +1,38 @@ + (,.~#\)(#,entropy)@> F_Words 37 + 1 1 0 + 2 1 0 + 3 2 1 + 4 3 0.918296 + 5 5 0.970951 + 6 8 0.954434 + 7 13 0.961237 + 8 21 0.958712 + 9 34 0.959687 +10 55 0.959316 +11 89 0.959458 +12 144 0.959404 +13 233 0.959424 +14 377 0.959417 +15 610 0.95942 +16 987 0.959418 +17 1597 0.959419 +18 2584 0.959419 +19 4181 0.959419 +20 6765 0.959419 +21 10946 0.959419 +22 17711 0.959419 +23 28657 0.959419 +24 46368 0.959419 +25 75025 0.959419 +26 121393 0.959419 +27 196418 0.959419 +28 317811 0.959419 +29 514229 0.959419 +30 832040 0.959419 +31 1.34627e6 0.959419 +32 2.17831e6 0.959419 +33 3.52458e6 0.959419 +34 5.70289e6 0.959419 +35 9.22747e6 0.959419 +36 1.49304e7 0.959419 +37 2.41578e7 0.959419 diff --git a/Task/Fibonacci-word/Java/fibonacci-word.java b/Task/Fibonacci-word/Java/fibonacci-word.java new file mode 100644 index 0000000000..a54d3fb0f2 --- /dev/null +++ b/Task/Fibonacci-word/Java/fibonacci-word.java @@ -0,0 +1,50 @@ +import java.util.*; + +public class FWord { + private /*v*/ String fWord0 = ""; + private /*v*/ String fWord1 = ""; + + private String nextFWord () { + final String result; + + if ( "".equals ( fWord1 ) ) result = "1"; + else if ( "".equals ( fWord0 ) ) result = "0"; + else result = fWord1 + fWord0; + + fWord0 = fWord1; + fWord1 = result; + + return result; + } + + public static double entropy ( final String source ) { + final int length = source.length (); + final Map < Character, Integer > counts = new HashMap < Character, Integer > (); + /*v*/ double result = 0.0; + + for ( int i = 0; i < length; i++ ) { + final char c = source.charAt ( i ); + + if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); + else counts.put ( c, 1 ); + } + + for ( final int count : counts.values () ) { + final double proportion = ( double ) count / length; + + result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); + } + + return result; + } + + public static void main ( final String [] args ) { + final FWord fWord = new FWord (); + + for ( int i = 0; i < 37; ) { + final String word = fWord.nextFWord (); + + System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); + } + } +} diff --git a/Task/Fibonacci-word/Mathematica/fibonacci-word.math b/Task/Fibonacci-word/Mathematica/fibonacci-word.math new file mode 100644 index 0000000000..1925ca9b73 --- /dev/null +++ b/Task/Fibonacci-word/Mathematica/fibonacci-word.math @@ -0,0 +1,7 @@ +entropy = (p - 1) Log[2, 1 - p] - p Log[2, p]; + +TableForm[ + Table[{k, Fibonacci[k], + Quiet@Check[N[entropy /. {p -> Fibonacci[k - 1]/Fibonacci[k]}, 15], + 0]}, {k, 37}], + TableHeadings -> {None, {"N", "Length", "Entropy"}}] diff --git a/Task/Fibonacci-word/PARI-GP/fibonacci-word.pari b/Task/Fibonacci-word/PARI-GP/fibonacci-word.pari new file mode 100644 index 0000000000..ae0a1f6214 --- /dev/null +++ b/Task/Fibonacci-word/PARI-GP/fibonacci-word.pari @@ -0,0 +1,4 @@ +ent(a,b)=[a,b]=[a,b]/(a+b);(a*log(if(a,a,1))+b*log(if(b,b,1)))/log(1/2) +allocatemem(75<<20) \\ Allocate 75 MB stack space +F=vector(37);F[1]="1";F[2]="0";for(n=3,37,F[n]=Str(F[n-1],F[n-2])) +for(n=1,37,print(n" "fibonacci(n)" "ent(fibonacci(n-1),fibonacci(n-2)))) diff --git a/Task/Fibonacci-word/PL-I/fibonacci-word.pli b/Task/Fibonacci-word/PL-I/fibonacci-word.pli new file mode 100644 index 0000000000..f9bcf92ba4 --- /dev/null +++ b/Task/Fibonacci-word/PL-I/fibonacci-word.pli @@ -0,0 +1,24 @@ +fibword: procedure options (main); /* 9 October 2013 */ + declare (fn, fnp1, fibword) bit (32000) varying; + declare (i, ln, lnp1, lfibword) fixed binary(31); + + fn = '1'b; fnp1 = '0'b; ln, lnp1 = 1; + put skip edit (1, length(fn), fn) (f(2), f(10), x(1), b); + put skip edit (2, length(fnp1), fnp1) (f(2), f(10), x(1), b); + do i = 3 to 37; + lfibword = lnp1 + ln; + ln = lnp1; + lnp1 = lfibword; + if i <= 10 then + do; + fibword = fnp1 || fn; + put skip edit (i, length(fibword), fibword) (f(2), f(10), x(1), b); + fn = fnp1; fnp1 = fibword; + end; + else + do; + put skip edit (i, lfibword) (f(2), f(10)); + end; + end; + +end fibword; diff --git a/Task/Fibonacci-word/Pascal/fibonacci-word.pascal b/Task/Fibonacci-word/Pascal/fibonacci-word.pascal new file mode 100644 index 0000000000..36be08ff83 --- /dev/null +++ b/Task/Fibonacci-word/Pascal/fibonacci-word.pascal @@ -0,0 +1,109 @@ +program FibWord; +{$IFDEF DELPHI} + {$APPTYPE CONSOLE} +{$ENDIF} +const + FibSMaxLen = 35; +type + tFibString = string[2*FibSMaxLen];//Ansistring; + tFibCnt = longWord; + tFib = record + ZeroCnt, + OneCnt : tFibCnt; +// fibS : tFibString;//didn't work :-( + end; +var + FibSCheck : boolean; + Fib0,Fib1 : tFib; + FibS0,FibS1: tFibString; + +procedure FibInit; +Begin + with Fib0 do + begin + ZeroCnt := 1; + OneCnt := 0; + end; + + with Fib1 do + begin + ZeroCnt := 0; + OneCnt := 1; + end; + FibS0 := '1'; + FibS1 := '0'; + FibSCheck := true; +end; + +Function FibLength(const F:Tfib):tFibCnt; +begin + FibLength := F.ZeroCnt+F.OneCnt; +end; + +function FibEntropy(const F:Tfib):extended; +const + rcpLn2 = 1.0/ln(2); +var + entrp, + ratio: extended; +begin + entrp := 0.0; + ratio := F.ZeroCnt/FibLength(F); + if Ratio <> 0.0 then + entrp := -ratio*ln(ratio)*rcpLn2; + ratio := F.OneCnt/FibLength(F); + if Ratio <> 0.0 then + entrp := entrp-ratio*ln(ratio)*rcpLn2; + FibEntropy:=entrp +end; + +procedure FibSExtend; +var + tmpS : tFibString; +begin + IF FibSCheck then + begin + tmpS := FibS0+FibS1; + FibS0 := FibS1; + FibS1 := tmpS; + FibSCheck := (length(FibS1) < FibSMaxLen); + end; +end; + +procedure FibNext; +var + tmpFib : tFib; +Begin + tmpFib.ZeroCnt := Fib0.ZeroCnt+Fib1.ZeroCnt; + tmpFib.OneCnt := Fib0.OneCnt +Fib1.OneCnt; + Fib0 := Fib1; + Fib1 := tmpFib; + IF FibSCheck then + FibSExtend; +end; + +procedure FibWrite(const F:Tfib); +begin +// With F do +// write(ZeroCnt:10,OneCnt:10,FibLength(F):10,FibEntropy(f):17:14); + write(FibLength(F):10,FibEntropy(F):17:14); + IF FibSCheck then + writeln(' ',FibS1) + else + writeln(' ....'); +end; + +var + i : integer; +BEGIN + FibInit; + writeln('No. Length Entropy Word'); + write(1:4);FibWrite(Fib0); + write(2:4);FibWrite(Fib1); + For i := 3 to 37 do + begin + FibNext; + write(i:4); + FibWrite(Fib1); + end; +END. diff --git a/Task/Fibonacci-word/Perl-6/fibonacci-word-1.pl6 b/Task/Fibonacci-word/Perl-6/fibonacci-word-1.pl6 new file mode 100644 index 0000000000..93a3518f7f --- /dev/null +++ b/Task/Fibonacci-word/Perl-6/fibonacci-word-1.pl6 @@ -0,0 +1,11 @@ +constant @fib-word = 1, 0, { $^b ~ $^a } ... *; + +sub entropy { + -log(2) R/ + [+] map -> \p { p * log p }, + $^string.comb.Bag.values »/» $string.chars +} +for @fib-word[^37] { + printf "%5d\t%10d\t%.8e\t%s\n", + (state $n)++, .chars, .&entropy, $n > 10 ?? '' !! $_; +} diff --git a/Task/Fibonacci-word/Perl-6/fibonacci-word-2.pl6 b/Task/Fibonacci-word/Perl-6/fibonacci-word-2.pl6 new file mode 100644 index 0000000000..b3827a2109 --- /dev/null +++ b/Task/Fibonacci-word/Perl-6/fibonacci-word-2.pl6 @@ -0,0 +1,19 @@ +constant @fib-word = '1', '0', { $^b ~ $^a } ... *; +constant @fib-ones = 1, 0, * + * ... *; +constant @fib-chrs = 1, 1, * + * ... *; + +multi entropy(0) { 0 } +multi entropy(1) { 0 } +multi entropy($n) { + my $chars = @fib-chrs[$n]; + my $ones = @fib-ones[$n]; + my $zeros = $chars - $ones; + -log(2) R/ + [+] map -> \p { p * log p }, + $ones / $chars, $zeros / $chars +} + +for 0..100 -> $n { + printf "%5d\t%21d\t%.15e\t%s\n", + $n, @fib-chrs[$n], entropy($n), $n > 9 ?? '' !! @fib-word[$n]; +} diff --git a/Task/Fibonacci-word/Perl/fibonacci-word.pl b/Task/Fibonacci-word/Perl/fibonacci-word.pl new file mode 100644 index 0000000000..6c5d22fa49 --- /dev/null +++ b/Task/Fibonacci-word/Perl/fibonacci-word.pl @@ -0,0 +1,31 @@ +sub fiboword; +{ + my ($a, $b, $count) = (1, 0, 0); + sub fiboword { + $count++; + return $a if $count == 1; + return $b if $count == 2; + ($a, $b) = ($b, "$b$a"); + return $b; + } +} +sub entropy { + my %c; + $c{$_}++ for split //, my $str = shift; + my $e = 0; + for (values %c) { + my $p = $_ / length $str; + $e -= $p * log $p; + } + return $e / log 2; +} + +my $count; +while ($count++ < 37) { + my $word = fiboword; + printf "%5d\t%10d\t%.8e\t%s\n", + $count, + length($word), + entropy($word), + $count > 9 ? '' : $word +} diff --git a/Task/Fibonacci-word/Python/fibonacci-word.py b/Task/Fibonacci-word/Python/fibonacci-word.py new file mode 100644 index 0000000000..a8a0ab7ed9 --- /dev/null +++ b/Task/Fibonacci-word/Python/fibonacci-word.py @@ -0,0 +1,58 @@ +>>> import math +>>> from collections import Counter +>>> +>>> def entropy(s): +... p, lns = Counter(s), float(len(s)) +... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) +... +>>> +>>> def fibword(nmax=37): +... fwords = ['1', '0'] +... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) +... def pr(n, fwords): +... while len(fwords) < n: +... fwords += [''.join(fwords[-2:][::-1])] +... v = fwords[n-1] +... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '')) +... for n in range(1, nmax+1): pr(n, fwords) +... +>>> fibword() +N Length Entropy Fibword + 1 1 -0 1 + 2 1 -0 0 + 3 2 1 01 + 4 3 0.9182958 010 + 5 5 0.9709506 01001 + 6 8 0.954434 01001010 + 7 13 0.9612366 0100101001001 + 8 21 0.9587119 + 9 34 0.9596869 + 10 55 0.959316 + 11 89 0.9594579 + 12 144 0.9594038 + 13 233 0.9594244 + 14 377 0.9594165 + 15 610 0.9594196 + 16 987 0.9594184 + 17 1597 0.9594188 + 18 2584 0.9594187 + 19 4181 0.9594187 + 20 6765 0.9594187 + 21 10946 0.9594187 + 22 17711 0.9594187 + 23 28657 0.9594187 + 24 46368 0.9594187 + 25 75025 0.9594187 + 26 121393 0.9594187 + 27 196418 0.9594187 + 28 317811 0.9594187 + 29 514229 0.9594187 + 30 832040 0.9594187 + 31 1346269 0.9594187 + 32 2178309 0.9594187 + 33 3524578 0.9594187 + 34 5702887 0.9594187 + 35 9227465 0.9594187 + 36 14930352 0.9594187 + 37 24157817 0.9594187 +>>> diff --git a/Task/Fibonacci-word/R/fibonacci-word.r b/Task/Fibonacci-word/R/fibonacci-word.r new file mode 100644 index 0000000000..0d18b4204b --- /dev/null +++ b/Task/Fibonacci-word/R/fibonacci-word.r @@ -0,0 +1,31 @@ +entropy <- function(s) +{ + if (length(s) > 1) + return(sapply(s, entropy)) + + freq <- prop.table(table(strsplit(s, '')[1])) + ret <- -sum(freq * log(freq, base=2)) + + return(ret) +} + +fibwords <- function(n) +{ + if (n == 1) + fibwords <- "1" + else + fibwords <- c("1", "0") + + if (n > 2) + { + for (i in 3:n) + fibwords <- c(fibwords, paste(fibwords[i-1L], fibwords[i-2L], sep="")) + } + + str <- if (n > 7) replicate(n-7, "too long") else NULL + fibwords.print <- c(fibwords[1:min(n, 7)], str) + + ret <- data.frame(Length=nchar(fibwords), Entropy=entropy(fibwords), Fibwords=fibwords.print) + rownames(ret) <- NULL + return(ret) +} diff --git a/Task/Fibonacci-word/README b/Task/Fibonacci-word/README new file mode 100644 index 0000000000..5dee40027b --- /dev/null +++ b/Task/Fibonacci-word/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Fibonacci_word diff --git a/Task/Fibonacci-word/REXX/fibonacci-word.rexx b/Task/Fibonacci-word/REXX/fibonacci-word.rexx new file mode 100644 index 0000000000..f3b9a1f3a5 --- /dev/null +++ b/Task/Fibonacci-word/REXX/fibonacci-word.rexx @@ -0,0 +1,36 @@ +/*REXX program lists # of chars in a fibonacci word, the word's entropy.*/ +numeric digits 20 /*use more precision, default=9.*/ +parse arg N !.1 !.2 . /*get optional args from the C.L.*/ +if N=='' then N=37 /*Not specified? Then use default*/ +if !.1=='' then !.1=1 /* " " " " " */ +if !.2=='' then !.2=0 /* " " " " " */ +say center('N',5) center('length',12) center('entropy',digits()+6) center('Fib word',35) +say copies('─',5) copies('─' ,12) copies('─' ,digits()+6) copies('─' ,35) + + do j=1 for N; j1=j-1; j2=j-2 /*display N fibonacci words. */ + if j>2 then !.j=!.j1 || !.j2 /*calculate FIBword if we need to*/ + if length(!.j)<35 then Fw= !.j + else Fw= '{the word is too wide to display}' + say right(j,4) right(length(!.j),12) ' ' entropy(!.j) ' ' Fw + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ENTROPY subroutine──────────────────*/ +entropy: procedure; parse arg $; L=length($); d=digits() +if L==1 then return left(0,d+2) /*handle special case of one char*/ +@.0=L-length(space(translate($,,0),0)) /*fast way to count zeroes. */ +@.1=L-@.0 /*and figure the number of ones. */ +S=0 /* [↓] calc entropy for each char*/ + do i=1 for 2; _=i-1 /*construct a chr from the ether.*/ + S = S - @._/L * log2(@._/L) /*add (negatively) the entropies.*/ + end /*i*/ +if S=1 then return left(1,d+2) /*return a left-justified "1". */ +return format(S,,d) /*normalize the number (sum or S). */ +/*──────────────────────────────────LOG2 subroutine───────────────────────────*/ +log2: procedure; parse arg x 1 xx; ig= x>1.5; is=1-2*(ig\==1); ii=0 +numeric digits digits()+5 /* [↓] precision of E must be > digits().*/ +e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535 + do while ig & xx>1.5 | \ig&xx<.5; _=e; do j=-1; iz=xx* _**-is + if j>=0 then if ig & iz<1 | \ig&iz>.5 then leave; _=_*_; izz=iz; end /*j*/ + xx=izz; ii=ii+is*2**j; end /*while*/; x=x* e**-ii-1; z=0; _=-1; p=z + do k=1; _=-_*x; z=z+_/k; if z=p then leave; p=z; end /*k*/ + r=z+ii; if arg()==2 then return r; return r/log2(2,0) diff --git a/Task/Fibonacci-word/Racket/fibonacci-word-1.rkt b/Task/Fibonacci-word/Racket/fibonacci-word-1.rkt new file mode 100644 index 0000000000..e9b1d46031 --- /dev/null +++ b/Task/Fibonacci-word/Racket/fibonacci-word-1.rkt @@ -0,0 +1,62 @@ +#lang racket +(provide F-Word gen-F-Word (struct-out f-word) f-word-max-length) +(require "entropy.rkt") ; save Entropy task implementation as "entropy.rkt" + +(define f-word-max-length (make-parameter 80)) +(define-struct f-word (str length count-0 count-1)) +(define (string->f-word str) + (apply f-word str + (call-with-values + (λ () + (for/fold + ((l 0) (zeros 0) (ones 0)) + ((c str)) + (match c + (#\0 (values (add1 l) (add1 zeros) ones)) + (#\1 (values (add1 l) zeros (add1 ones)))))) + list))) +(define F-Word# (make-hash)) + +(define (gen-F-Word n #:key-id key-id #:word-1 word-1 #:word-2 word-2 #:merge-fn merge-fn) + (define sub-F-Word (match-lambda (1 word-1) (2 word-2) ((? number? n) (merge-fn n)))) + (hash-ref! F-Word# (list key-id (f-word-max-length) n) (λ () (sub-F-Word n)))) + +(define (F-Word n) + (define f-word-1 (string->f-word "1")) + (define f-word-2 (string->f-word "0")) + (define (f-word-merge>2 n) + (define f-1 (F-Word (- n 1))) + (define f-2 (F-Word (- n 2))) + (define length+ (+ (f-word-length f-1) (f-word-length f-2))) + (define count-0+ (+ (f-word-count-0 f-1) (f-word-count-0 f-2))) + (define count-1+ (+ (f-word-count-1 f-1) (f-word-count-1 f-2))) + (define str+ + (if (and (f-word-max-length) + (> length+ (f-word-max-length))) + (format "" length+) + (string-append (f-word-str f-1) (f-word-str f-2)))) + (f-word str+ length+ count-0+ count-1+)) + + (gen-F-Word n + #:key-id 'words + #:word-1 f-word-1 + #:word-2 f-word-2 + #:merge-fn f-word-merge>2)) + +(module+ main + (parameterize ((f-word-max-length 80)) + (for ((n (sequence-map add1 (in-range 37)))) + (define W (F-Word n)) + (define e (hash-entropy (hash 0 (f-word-count-0 W) + 1 (f-word-count-1 W)))) + (printf "~a ~a ~a ~a~%" + (~a n #:width 3 #:align 'right) + (~a (f-word-length W) #:width 9 #:align 'right) + (real->decimal-string e 12) + (~a (f-word-str W)))))) + +(module+ test + (require rackunit) + (check-match (F-Word 4) (f-word "010" _ _ _)) + (check-match (F-Word 5) (f-word "01001" _ _ _)) + (check-match (F-Word 8) (f-word "010010100100101001010" _ _ _))) diff --git a/Task/Fibonacci-word/Racket/fibonacci-word-2.rkt b/Task/Fibonacci-word/Racket/fibonacci-word-2.rkt new file mode 100644 index 0000000000..f331141770 --- /dev/null +++ b/Task/Fibonacci-word/Racket/fibonacci-word-2.rkt @@ -0,0 +1,32 @@ +#lang racket + +(define f-word-max-length (make-parameter 80)) +(define-struct f-word (str length count-0 count-1)) + +(define F-Word# (make-hash)) +(define (F-Word n) + (hash-ref! + F-Word# + (list (f-word-max-length) n) + (λ () + (match n + (1 (f-word "1" 1 0 1)) + (2 (f-word "0" 1 1 0)) + ((? number? n) + (define f-1 (F-Word (- n 1))) + (define f-2 (F-Word (- n 2))) + (define length+ (+ (f-word-length f-1) (f-word-length f-2))) + (define count-0+ (+ (f-word-count-0 f-1) (f-word-count-0 f-2))) + (define count-1+ (+ (f-word-count-1 f-1) (f-word-count-1 f-2))) + (define str+ + (if (and (f-word-max-length) + (> length+ (f-word-max-length))) + (format "" length+) + (string-append (f-word-str f-1) (f-word-str f-2)))) + (f-word str+ length+ count-0+ count-1+)))))) + +(module+ test + (require rackunit) + (check-match (F-Word 4) (f-word "010" _ _ _)) + (check-match (F-Word 5) (f-word "01001" _ _ _)) + (check-match (F-Word 8) (f-word "010010100100101001010" _ _ _))) diff --git a/Task/Fibonacci-word/Ruby/fibonacci-word.rb b/Task/Fibonacci-word/Ruby/fibonacci-word.rb new file mode 100644 index 0000000000..7c7829a11b --- /dev/null +++ b/Task/Fibonacci-word/Ruby/fibonacci-word.rb @@ -0,0 +1,23 @@ +#encoding: ASCII-8BIT + +def entropy(s) + counts = Hash.new(0) + s.each_char { |c| counts[c] += 1 } + + counts.values.reduce(0) do |entropy, count| + freq = count / s.length.to_f + entropy - freq * Math.log2(freq) + end +end + +n_max = 37 +words = ['1', '0'] + +for n in words.length ... n_max + words << words[-1] + words[-2] +end + +puts '%3s %10s %15s %s' % %w[N Length Entropy Fibword] +words.each.with_index(1) do |word, i| + puts '%3i %10i %15.12f %s' % [i, word.length, entropy(word), word.length<30 ? word : ''] +end diff --git a/Task/Fibonacci-word/Scala/fibonacci-word.scala b/Task/Fibonacci-word/Scala/fibonacci-word.scala new file mode 100644 index 0000000000..202b6326e1 --- /dev/null +++ b/Task/Fibonacci-word/Scala/fibonacci-word.scala @@ -0,0 +1,17 @@ +//word iterator +def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1) + +//entropy calculator +def entropy(src: String): Double = { + val xs = src.groupBy(identity).map(_._2.length) + var result = 0.0 + xs.foreach{c => + val p = c.toDouble / src.length + result -= p * (Math.log(p) / Math.log(2)) + } + result +} + +//printing (spaces inserted to get the tabs align properly) +val it = fibIt.zipWithIndex.map(w => (w._2, w._1.length, entropy(w._1))) +println(it.take(37).map{case (n,l,e) => s"$n).\t$l \t$e"}.mkString("\n")) diff --git a/Task/Fibonacci-word/Seed7/fibonacci-word.seed7 b/Task/Fibonacci-word/Seed7/fibonacci-word.seed7 new file mode 100644 index 0000000000..bb11a55e29 --- /dev/null +++ b/Task/Fibonacci-word/Seed7/fibonacci-word.seed7 @@ -0,0 +1,53 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const func float: entropy (in string: stri) is func + result + var float: entropy is 0.0; + local + var hash [char] integer: count is (hash [char] integer).value; + var char: ch is ' '; + var float: p is 0.0; + begin + for ch range stri do + if ch in count then + incr(count[ch]); + else + count @:= [ch] 1; + end if; + end for; + for key ch range count do + p := flt(count[ch]) / flt(length(stri)); + entropy -:= p * log(p) / log(2.0); + end for; + end func ; + +const func string: fibWord (in integer: number) is func + result + var string: fibWord is "1"; + local + var integer: i is 0; + var string: a is "1"; + var string: c is ""; + begin + if number >= 2 then + fibWord := "0"; + for i range 3 to number do + c := a; + a := fibWord; + fibWord &:= c; + end for; + end if; + end func; + +const proc: main is func + local + var integer: index is 0; + var string: fibWord is ""; + begin + for index range 1 to 37 do + fibWord := fibWord(index); + writeln(index lpad 2 <& length(fibWord) lpad 10 <& " " <& entropy(fibWord) digits 15); + end for; + end func; diff --git a/Task/Fibonacci-word/Tcl/fibonacci-word.tcl b/Task/Fibonacci-word/Tcl/fibonacci-word.tcl new file mode 100644 index 0000000000..a5fbcf7848 --- /dev/null +++ b/Task/Fibonacci-word/Tcl/fibonacci-word.tcl @@ -0,0 +1,28 @@ +proc fibwords {n} { + set fw {1 0} + while {[llength $fw] < $n} { + lappend fw [lindex $fw end][lindex $fw end-1] + } + return $fw +} + +proc fibwordinfo {num word} { + # Entropy calculator from Tcl solution of that task + set log2 [expr log(2)] + set len [string length $word] + foreach char [split $word ""] {dict incr counts $char} + set entropy 0.0 + foreach count [dict values $counts] { + set freq [expr {$count / double($len)}] + set entropy [expr {$entropy - $freq * log($freq)/$log2}] + } + # Output formatting from Clojure solution + puts [format "%2d %10d %.15f %s" $num $len $entropy \ + [if {$len < 35} {set word} {subst ""}]] +} + +# Output formatting from Clojure solution +puts [format "%2s %10s %17s %s" N Length Entropy Fibword] +foreach word [fibwords 37] { + fibwordinfo [incr i] $word +} diff --git a/Task/File-IO/README b/Task/File-IO/README deleted file mode 100644 index 795f142446..0000000000 --- a/Task/File-IO/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/File_IO diff --git a/Task/File-IO/REXX/file-io-1.rexx b/Task/File-IO/REXX/file-io-1.rexx deleted file mode 100644 index 2d29a5e33f..0000000000 --- a/Task/File-IO/REXX/file-io-1.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program to read a file and store the contents into an output file*/ - -ifid = 'input.txt' /*name of the input file. */ -ofid = 'output.txt' /*name of the output file. */ -call lineout ofid,,1 /*insure output starts at line 1.*/ - - do while lines(ifid)\==0 /*read until finished. */ - y = linein(ifid) /*read a record from input. */ - call lineout ofid,y /*write a record to output.nt. */ - end - /*stick a fork in it, we're done.*/ diff --git a/Task/File-IO/REXX/file-io-2.rexx b/Task/File-IO/REXX/file-io-2.rexx deleted file mode 100644 index 24cb5a0064..0000000000 --- a/Task/File-IO/REXX/file-io-2.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program to read a file and store the contents into an output file*/ -/*(same as the 1st example, but is faster because no intermediate step.)*/ - -ifid = 'input.txt' /*name of the input file. */ -ofid = 'output.txt' /*name of the output file. */ -call lineout ofid,,1 /*insure output starts at line 1.*/ - - do while lines(ifid)\==0 /*read until finished. */ - call lineout ofid, linein(ifid) /*read & write in one statement. */ - end /*while*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/File-IO/00DESCRIPTION b/Task/File-input-output/00DESCRIPTION similarity index 100% rename from Task/File-IO/00DESCRIPTION rename to Task/File-input-output/00DESCRIPTION diff --git a/Task/File-input-output/00META.yaml b/Task/File-input-output/00META.yaml new file mode 100644 index 0000000000..53d5156105 --- /dev/null +++ b/Task/File-input-output/00META.yaml @@ -0,0 +1,2 @@ +--- +note: File handling diff --git a/Task/File-IO/ACL2/file-io.acl2 b/Task/File-input-output/ACL2/file-input-output.acl2 similarity index 100% rename from Task/File-IO/ACL2/file-io.acl2 rename to Task/File-input-output/ACL2/file-input-output.acl2 diff --git a/Task/File-IO/ALGOL-68/file-io.alg b/Task/File-input-output/ALGOL-68/file-input-output.alg similarity index 100% rename from Task/File-IO/ALGOL-68/file-io.alg rename to Task/File-input-output/ALGOL-68/file-input-output.alg diff --git a/Task/File-IO/AWK/file-io.awk b/Task/File-input-output/AWK/file-input-output.awk similarity index 100% rename from Task/File-IO/AWK/file-io.awk rename to Task/File-input-output/AWK/file-input-output.awk diff --git a/Task/File-IO/Ada/file-io-1.ada b/Task/File-input-output/Ada/file-input-output-1.ada similarity index 76% rename from Task/File-IO/Ada/file-io-1.ada rename to Task/File-input-output/Ada/file-input-output-1.ada index 3359b42b09..626f1b2565 100644 --- a/Task/File-IO/Ada/file-io-1.ada +++ b/Task/File-input-output/Ada/file-input-output-1.ada @@ -17,8 +17,14 @@ begin Put_Line (Output, Line); end; end loop; + Close (Input); + Close (Output); exception when End_Error => - Close (Input); - Close (Output); + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; end Read_And_Write_File_Line_By_Line; diff --git a/Task/File-IO/Ada/file-io-2.ada b/Task/File-input-output/Ada/file-input-output-2.ada similarity index 86% rename from Task/File-IO/Ada/file-io-2.ada rename to Task/File-input-output/Ada/file-input-output-2.ada index e843a6a40d..1c60a9b0e9 100644 --- a/Task/File-IO/Ada/file-io-2.ada +++ b/Task/File-input-output/Ada/file-input-output-2.ada @@ -38,8 +38,14 @@ begin Put_Line (Output, Line); end; end loop; + Close (Input); + Close (Output); exception when End_Error => - Close (Input); - Close (Output); + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; end Read_And_Write_File_Line_By_Line; diff --git a/Task/File-IO/Ada/file-io-3.ada b/Task/File-input-output/Ada/file-input-output-3.ada similarity index 76% rename from Task/File-IO/Ada/file-io-3.ada rename to Task/File-input-output/Ada/file-input-output-3.ada index 5abb54e502..2ad4edd6a8 100644 --- a/Task/File-IO/Ada/file-io-3.ada +++ b/Task/File-input-output/Ada/file-input-output-3.ada @@ -13,8 +13,14 @@ begin Read (File => Input, Item => Buffer); Write (File => Output, Item => Buffer); end loop; + Close (Input); + Close (Output); exception when End_Error => - Close (Input); - Close (Output); + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; end Read_And_Write_File_Character_By_Character; diff --git a/Task/File-IO/Ada/file-io-4.ada b/Task/File-input-output/Ada/file-input-output-4.ada similarity index 75% rename from Task/File-IO/Ada/file-io-4.ada rename to Task/File-input-output/Ada/file-input-output-4.ada index 43268042a9..61ad4cf3ea 100644 --- a/Task/File-IO/Ada/file-io-4.ada +++ b/Task/File-input-output/Ada/file-input-output-4.ada @@ -11,8 +11,14 @@ begin Buffer := Character'Input (Stream (Input)); Character'Write (Stream (Output), Buffer); end loop; + Close (Input); + Close (Output); exception when End_Error => - Close (Input); - Close (Output); + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; end Using_Text_Streams; diff --git a/Task/File-IO/Aime/file-io.aime b/Task/File-input-output/Aime/file-input-output.aime similarity index 100% rename from Task/File-IO/Aime/file-io.aime rename to Task/File-input-output/Aime/file-input-output.aime diff --git a/Task/File-IO/AppleScript/file-io.applescript b/Task/File-input-output/AppleScript/file-input-output.applescript similarity index 100% rename from Task/File-IO/AppleScript/file-io.applescript rename to Task/File-input-output/AppleScript/file-input-output.applescript diff --git a/Task/File-IO/AutoHotkey/file-io-1.ahk b/Task/File-input-output/AutoHotkey/file-input-output-1.ahk similarity index 100% rename from Task/File-IO/AutoHotkey/file-io-1.ahk rename to Task/File-input-output/AutoHotkey/file-input-output-1.ahk diff --git a/Task/File-IO/AutoHotkey/file-io-2.ahk b/Task/File-input-output/AutoHotkey/file-input-output-2.ahk similarity index 100% rename from Task/File-IO/AutoHotkey/file-io-2.ahk rename to Task/File-input-output/AutoHotkey/file-input-output-2.ahk diff --git a/Task/File-IO/AutoHotkey/file-io-3.ahk b/Task/File-input-output/AutoHotkey/file-input-output-3.ahk similarity index 100% rename from Task/File-IO/AutoHotkey/file-io-3.ahk rename to Task/File-input-output/AutoHotkey/file-input-output-3.ahk diff --git a/Task/File-IO/BASIC/file-io-1.basic b/Task/File-input-output/BASIC/file-input-output-1.basic similarity index 100% rename from Task/File-IO/BASIC/file-io-1.basic rename to Task/File-input-output/BASIC/file-input-output-1.basic diff --git a/Task/File-IO/BASIC/file-io-2.basic b/Task/File-input-output/BASIC/file-input-output-2.basic similarity index 100% rename from Task/File-IO/BASIC/file-io-2.basic rename to Task/File-input-output/BASIC/file-input-output-2.basic diff --git a/Task/File-IO/BBC-BASIC/file-io-1.bbc b/Task/File-input-output/BBC-BASIC/file-input-output-1.bbc similarity index 100% rename from Task/File-IO/BBC-BASIC/file-io-1.bbc rename to Task/File-input-output/BBC-BASIC/file-input-output-1.bbc diff --git a/Task/File-IO/BBC-BASIC/file-io-2.bbc b/Task/File-input-output/BBC-BASIC/file-input-output-2.bbc similarity index 100% rename from Task/File-IO/BBC-BASIC/file-io-2.bbc rename to Task/File-input-output/BBC-BASIC/file-input-output-2.bbc diff --git a/Task/File-IO/Babel/file-io.pb b/Task/File-input-output/Babel/file-input-output.pb similarity index 73% rename from Task/File-IO/Babel/file-io.pb rename to Task/File-input-output/Babel/file-input-output.pb index f91d91223e..ae15960c55 100644 --- a/Task/File-IO/Babel/file-io.pb +++ b/Task/File-input-output/Babel/file-input-output.pb @@ -1,4 +1,4 @@ -main: +(main { "input.txt" >>> -- File is now on stack foo set -- File is now in 'foo' - foo "output.txt" <<< } + foo "output.txt" <<< }) diff --git a/Task/File-IO/Batch-File/file-io-1.bat b/Task/File-input-output/Batch-File/file-input-output-1.bat similarity index 100% rename from Task/File-IO/Batch-File/file-io-1.bat rename to Task/File-input-output/Batch-File/file-input-output-1.bat diff --git a/Task/File-IO/Batch-File/file-io-2.bat b/Task/File-input-output/Batch-File/file-input-output-2.bat similarity index 100% rename from Task/File-IO/Batch-File/file-io-2.bat rename to Task/File-input-output/Batch-File/file-input-output-2.bat diff --git a/Task/File-IO/Batch-File/file-io-3.bat b/Task/File-input-output/Batch-File/file-input-output-3.bat similarity index 100% rename from Task/File-IO/Batch-File/file-io-3.bat rename to Task/File-input-output/Batch-File/file-input-output-3.bat diff --git a/Task/File-IO/Befunge/file-io.bf b/Task/File-input-output/Befunge/file-input-output.bf similarity index 100% rename from Task/File-IO/Befunge/file-io.bf rename to Task/File-input-output/Befunge/file-input-output.bf diff --git a/Task/File-IO/Bracmat/file-io.bracmat b/Task/File-input-output/Bracmat/file-input-output.bracmat similarity index 100% rename from Task/File-IO/Bracmat/file-io.bracmat rename to Task/File-input-output/Bracmat/file-input-output.bracmat diff --git a/Task/File-IO/C++/file-io-1.cpp b/Task/File-input-output/C++/file-input-output-1.cpp similarity index 100% rename from Task/File-IO/C++/file-io-1.cpp rename to Task/File-input-output/C++/file-input-output-1.cpp diff --git a/Task/File-IO/C++/file-io-2.cpp b/Task/File-input-output/C++/file-input-output-2.cpp similarity index 100% rename from Task/File-IO/C++/file-io-2.cpp rename to Task/File-input-output/C++/file-input-output-2.cpp diff --git a/Task/File-IO/C++/file-io-3.cpp b/Task/File-input-output/C++/file-input-output-3.cpp similarity index 100% rename from Task/File-IO/C++/file-io-3.cpp rename to Task/File-input-output/C++/file-input-output-3.cpp diff --git a/Task/File-IO/C++/file-io-4.cpp b/Task/File-input-output/C++/file-input-output-4.cpp similarity index 100% rename from Task/File-IO/C++/file-io-4.cpp rename to Task/File-input-output/C++/file-input-output-4.cpp diff --git a/Task/File-IO/C/file-io-1.c b/Task/File-input-output/C/file-input-output-1.c similarity index 100% rename from Task/File-IO/C/file-io-1.c rename to Task/File-input-output/C/file-input-output-1.c diff --git a/Task/File-IO/C/file-io-2.c b/Task/File-input-output/C/file-input-output-2.c similarity index 100% rename from Task/File-IO/C/file-io-2.c rename to Task/File-input-output/C/file-input-output-2.c diff --git a/Task/File-IO/C/file-io-3.c b/Task/File-input-output/C/file-input-output-3.c similarity index 100% rename from Task/File-IO/C/file-io-3.c rename to Task/File-input-output/C/file-input-output-3.c diff --git a/Task/File-IO/COBOL/file-io-1.cobol b/Task/File-input-output/COBOL/file-input-output-1.cobol similarity index 100% rename from Task/File-IO/COBOL/file-io-1.cobol rename to Task/File-input-output/COBOL/file-input-output-1.cobol diff --git a/Task/File-IO/COBOL/file-io-2.cobol b/Task/File-input-output/COBOL/file-input-output-2.cobol similarity index 100% rename from Task/File-IO/COBOL/file-io-2.cobol rename to Task/File-input-output/COBOL/file-input-output-2.cobol diff --git a/Task/File-IO/COBOL/file-io-3.cobol b/Task/File-input-output/COBOL/file-input-output-3.cobol similarity index 100% rename from Task/File-IO/COBOL/file-io-3.cobol rename to Task/File-input-output/COBOL/file-input-output-3.cobol diff --git a/Task/File-IO/Clean/file-io-1.clean b/Task/File-input-output/Clean/file-input-output-1.clean similarity index 100% rename from Task/File-IO/Clean/file-io-1.clean rename to Task/File-input-output/Clean/file-input-output-1.clean diff --git a/Task/File-IO/Clean/file-io-2.clean b/Task/File-input-output/Clean/file-input-output-2.clean similarity index 100% rename from Task/File-IO/Clean/file-io-2.clean rename to Task/File-input-output/Clean/file-input-output-2.clean diff --git a/Task/File-IO/Clojure/file-io-1.clj b/Task/File-input-output/Clojure/file-input-output-1.clj similarity index 100% rename from Task/File-IO/Clojure/file-io-1.clj rename to Task/File-input-output/Clojure/file-input-output-1.clj diff --git a/Task/File-IO/Clojure/file-io-2.clj b/Task/File-input-output/Clojure/file-input-output-2.clj similarity index 100% rename from Task/File-IO/Clojure/file-io-2.clj rename to Task/File-input-output/Clojure/file-input-output-2.clj diff --git a/Task/File-IO/ColdFusion/file-io.cfm b/Task/File-input-output/ColdFusion/file-input-output.cfm similarity index 100% rename from Task/File-IO/ColdFusion/file-io.cfm rename to Task/File-input-output/ColdFusion/file-input-output.cfm diff --git a/Task/File-IO/Common-Lisp/file-io-1.lisp b/Task/File-input-output/Common-Lisp/file-input-output-1.lisp similarity index 100% rename from Task/File-IO/Common-Lisp/file-io-1.lisp rename to Task/File-input-output/Common-Lisp/file-input-output-1.lisp diff --git a/Task/File-IO/Common-Lisp/file-io-2.lisp b/Task/File-input-output/Common-Lisp/file-input-output-2.lisp similarity index 100% rename from Task/File-IO/Common-Lisp/file-io-2.lisp rename to Task/File-input-output/Common-Lisp/file-input-output-2.lisp diff --git a/Task/File-IO/D/file-io-1.d b/Task/File-input-output/D/file-input-output-1.d similarity index 100% rename from Task/File-IO/D/file-io-1.d rename to Task/File-input-output/D/file-input-output-1.d diff --git a/Task/File-input-output/D/file-input-output-2.d b/Task/File-input-output/D/file-input-output-2.d new file mode 100644 index 0000000000..2316dc604c --- /dev/null +++ b/Task/File-input-output/D/file-input-output-2.d @@ -0,0 +1,15 @@ +import std.stdio; + +int main() { + auto from = File("input.txt", "rb"); + scope(exit) from.close(); + + auto to = File("output.txt", "wb"); + scope(exit) to.close(); + + foreach(buffer; from.byChunk(new ubyte[4096*1024])) { + to.rawWrite(buffer); + } + + return 0; +} diff --git a/Task/File-IO/D/file-io-2.d b/Task/File-input-output/D/file-input-output-3.d similarity index 100% rename from Task/File-IO/D/file-io-2.d rename to Task/File-input-output/D/file-input-output-3.d diff --git a/Task/File-IO/D/file-io-3.d b/Task/File-input-output/D/file-input-output-4.d similarity index 100% rename from Task/File-IO/D/file-io-3.d rename to Task/File-input-output/D/file-input-output-4.d diff --git a/Task/File-IO/Delphi/file-io-1.delphi b/Task/File-input-output/Delphi/file-input-output-1.delphi similarity index 100% rename from Task/File-IO/Delphi/file-io-1.delphi rename to Task/File-input-output/Delphi/file-input-output-1.delphi diff --git a/Task/File-IO/Delphi/file-io-2.delphi b/Task/File-input-output/Delphi/file-input-output-2.delphi similarity index 100% rename from Task/File-IO/Delphi/file-io-2.delphi rename to Task/File-input-output/Delphi/file-input-output-2.delphi diff --git a/Task/File-IO/Delphi/file-io-3.delphi b/Task/File-input-output/Delphi/file-input-output-3.delphi similarity index 100% rename from Task/File-IO/Delphi/file-io-3.delphi rename to Task/File-input-output/Delphi/file-input-output-3.delphi diff --git a/Task/File-IO/E/file-io.e b/Task/File-input-output/E/file-input-output.e similarity index 100% rename from Task/File-IO/E/file-io.e rename to Task/File-input-output/E/file-input-output.e diff --git a/Task/File-IO/Eiffel/file-io.e b/Task/File-input-output/Eiffel/file-input-output.e similarity index 100% rename from Task/File-IO/Eiffel/file-io.e rename to Task/File-input-output/Eiffel/file-input-output.e diff --git a/Task/File-IO/Erlang/file-io.erl b/Task/File-input-output/Erlang/file-input-output.erl similarity index 100% rename from Task/File-IO/Erlang/file-io.erl rename to Task/File-input-output/Erlang/file-input-output.erl diff --git a/Task/File-IO/Euphoria/file-io-1.euphoria b/Task/File-input-output/Euphoria/file-input-output-1.euphoria similarity index 100% rename from Task/File-IO/Euphoria/file-io-1.euphoria rename to Task/File-input-output/Euphoria/file-input-output-1.euphoria diff --git a/Task/File-IO/Euphoria/file-io-2.euphoria b/Task/File-input-output/Euphoria/file-input-output-2.euphoria similarity index 100% rename from Task/File-IO/Euphoria/file-io-2.euphoria rename to Task/File-input-output/Euphoria/file-input-output-2.euphoria diff --git a/Task/File-IO/Factor/file-io-1.factor b/Task/File-input-output/Factor/file-input-output-1.factor similarity index 100% rename from Task/File-IO/Factor/file-io-1.factor rename to Task/File-input-output/Factor/file-input-output-1.factor diff --git a/Task/File-IO/Factor/file-io-2.factor b/Task/File-input-output/Factor/file-input-output-2.factor similarity index 100% rename from Task/File-IO/Factor/file-io-2.factor rename to Task/File-input-output/Factor/file-input-output-2.factor diff --git a/Task/File-IO/Factor/file-io-3.factor b/Task/File-input-output/Factor/file-input-output-3.factor similarity index 100% rename from Task/File-IO/Factor/file-io-3.factor rename to Task/File-input-output/Factor/file-input-output-3.factor diff --git a/Task/File-IO/Forth/file-io.fth b/Task/File-input-output/Forth/file-input-output.fth similarity index 100% rename from Task/File-IO/Forth/file-io.fth rename to Task/File-input-output/Forth/file-input-output.fth diff --git a/Task/File-IO/Fortran/file-io.f b/Task/File-input-output/Fortran/file-input-output.f similarity index 100% rename from Task/File-IO/Fortran/file-io.f rename to Task/File-input-output/Fortran/file-input-output.f diff --git a/Task/File-IO/Frink/file-io.frink b/Task/File-input-output/Frink/file-input-output.frink similarity index 100% rename from Task/File-IO/Frink/file-io.frink rename to Task/File-input-output/Frink/file-input-output.frink diff --git a/Task/File-IO/GAP/file-io.gap b/Task/File-input-output/GAP/file-input-output.gap similarity index 100% rename from Task/File-IO/GAP/file-io.gap rename to Task/File-input-output/GAP/file-input-output.gap diff --git a/Task/File-IO/GML/file-io.gml b/Task/File-input-output/GML/file-input-output.gml similarity index 60% rename from Task/File-IO/GML/file-io.gml rename to Task/File-input-output/GML/file-input-output.gml index 42d83a3faa..0c8c5cea60 100644 --- a/Task/File-IO/GML/file-io.gml +++ b/Task/File-input-output/GML/file-input-output.gml @@ -1,16 +1,13 @@ var file, str; file = file_text_open_read("input.txt"); str = ""; -while (true) +while (!file_text_eof(file)) { str += file_text_read_string(file); - if (file_text_eof(file)) + if (!file_text_eof(file)) { - break; - } - else - { - str += chr(vk_enter); + str += " +"; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind file_text_readln(file); } } diff --git a/Task/File-IO/GUISS/file-io.guiss b/Task/File-input-output/GUISS/file-input-output.guiss similarity index 100% rename from Task/File-IO/GUISS/file-io.guiss rename to Task/File-input-output/GUISS/file-input-output.guiss diff --git a/Task/File-IO/Go/file-io-1.go b/Task/File-input-output/Go/file-input-output-1.go similarity index 100% rename from Task/File-IO/Go/file-io-1.go rename to Task/File-input-output/Go/file-input-output-1.go diff --git a/Task/File-IO/Go/file-io-2.go b/Task/File-input-output/Go/file-input-output-2.go similarity index 100% rename from Task/File-IO/Go/file-io-2.go rename to Task/File-input-output/Go/file-input-output-2.go diff --git a/Task/File-IO/Groovy/file-io-1.groovy b/Task/File-input-output/Groovy/file-input-output-1.groovy similarity index 100% rename from Task/File-IO/Groovy/file-io-1.groovy rename to Task/File-input-output/Groovy/file-input-output-1.groovy diff --git a/Task/File-IO/Groovy/file-io-2.groovy b/Task/File-input-output/Groovy/file-input-output-2.groovy similarity index 100% rename from Task/File-IO/Groovy/file-io-2.groovy rename to Task/File-input-output/Groovy/file-input-output-2.groovy diff --git a/Task/File-IO/Groovy/file-io-3.groovy b/Task/File-input-output/Groovy/file-input-output-3.groovy similarity index 100% rename from Task/File-IO/Groovy/file-io-3.groovy rename to Task/File-input-output/Groovy/file-input-output-3.groovy diff --git a/Task/File-IO/Haskell/file-io.hs b/Task/File-input-output/Haskell/file-input-output.hs similarity index 100% rename from Task/File-IO/Haskell/file-io.hs rename to Task/File-input-output/Haskell/file-input-output.hs diff --git a/Task/File-IO/HicEst/file-io-1.hicest b/Task/File-input-output/HicEst/file-input-output-1.hicest similarity index 100% rename from Task/File-IO/HicEst/file-io-1.hicest rename to Task/File-input-output/HicEst/file-input-output-1.hicest diff --git a/Task/File-IO/HicEst/file-io-2.hicest b/Task/File-input-output/HicEst/file-input-output-2.hicest similarity index 100% rename from Task/File-IO/HicEst/file-io-2.hicest rename to Task/File-input-output/HicEst/file-input-output-2.hicest diff --git a/Task/File-IO/HicEst/file-io-3.hicest b/Task/File-input-output/HicEst/file-input-output-3.hicest similarity index 100% rename from Task/File-IO/HicEst/file-io-3.hicest rename to Task/File-input-output/HicEst/file-input-output-3.hicest diff --git a/Task/File-IO/IDL/file-io.idl b/Task/File-input-output/IDL/file-input-output.idl similarity index 100% rename from Task/File-IO/IDL/file-io.idl rename to Task/File-input-output/IDL/file-input-output.idl diff --git a/Task/File-IO/Icon/file-io.icon b/Task/File-input-output/Icon/file-input-output.icon similarity index 100% rename from Task/File-IO/Icon/file-io.icon rename to Task/File-input-output/Icon/file-input-output.icon diff --git a/Task/File-IO/Io/file-io.io b/Task/File-input-output/Io/file-input-output.io similarity index 100% rename from Task/File-IO/Io/file-io.io rename to Task/File-input-output/Io/file-input-output.io diff --git a/Task/File-IO/J/file-io-1.j b/Task/File-input-output/J/file-input-output-1.j similarity index 100% rename from Task/File-IO/J/file-io-1.j rename to Task/File-input-output/J/file-input-output-1.j diff --git a/Task/File-IO/J/file-io-2.j b/Task/File-input-output/J/file-input-output-2.j similarity index 100% rename from Task/File-IO/J/file-io-2.j rename to Task/File-input-output/J/file-input-output-2.j diff --git a/Task/File-IO/Java/file-io-1.java b/Task/File-input-output/Java/file-input-output-1.java similarity index 100% rename from Task/File-IO/Java/file-io-1.java rename to Task/File-input-output/Java/file-input-output-1.java diff --git a/Task/File-IO/Java/file-io-2.java b/Task/File-input-output/Java/file-input-output-2.java similarity index 100% rename from Task/File-IO/Java/file-io-2.java rename to Task/File-input-output/Java/file-input-output-2.java diff --git a/Task/File-IO/Java/file-io-3.java b/Task/File-input-output/Java/file-input-output-3.java similarity index 100% rename from Task/File-IO/Java/file-io-3.java rename to Task/File-input-output/Java/file-input-output-3.java diff --git a/Task/File-IO/Java/file-io-4.java b/Task/File-input-output/Java/file-input-output-4.java similarity index 100% rename from Task/File-IO/Java/file-io-4.java rename to Task/File-input-output/Java/file-input-output-4.java diff --git a/Task/File-IO/Java/file-io-5.java b/Task/File-input-output/Java/file-input-output-5.java similarity index 100% rename from Task/File-IO/Java/file-io-5.java rename to Task/File-input-output/Java/file-input-output-5.java diff --git a/Task/File-IO/JavaScript/file-io-1.js b/Task/File-input-output/JavaScript/file-input-output-1.js similarity index 100% rename from Task/File-IO/JavaScript/file-io-1.js rename to Task/File-input-output/JavaScript/file-input-output-1.js diff --git a/Task/File-IO/JavaScript/file-io-2.js b/Task/File-input-output/JavaScript/file-input-output-2.js similarity index 100% rename from Task/File-IO/JavaScript/file-io-2.js rename to Task/File-input-output/JavaScript/file-input-output-2.js diff --git a/Task/File-input-output/Julia/file-input-output-1.julia b/Task/File-input-output/Julia/file-input-output-1.julia new file mode 100644 index 0000000000..9abbf8ab39 --- /dev/null +++ b/Task/File-input-output/Julia/file-input-output-1.julia @@ -0,0 +1,2 @@ +string = open(readall, "file1", "r") +open(io->write(io, string), "file2", "w") diff --git a/Task/File-input-output/Julia/file-input-output-2.julia b/Task/File-input-output/Julia/file-input-output-2.julia new file mode 100644 index 0000000000..304139641a --- /dev/null +++ b/Task/File-input-output/Julia/file-input-output-2.julia @@ -0,0 +1 @@ +cp("file1","file2") diff --git a/Task/File-input-output/Julia/file-input-output-3.julia b/Task/File-input-output/Julia/file-input-output-3.julia new file mode 100644 index 0000000000..90a64659d0 --- /dev/null +++ b/Task/File-input-output/Julia/file-input-output-3.julia @@ -0,0 +1,5 @@ +infile = open("file1", "r") +outfile = open("file2", "w") +write(outfile, readall(infile)) +close(outfile) +close(infile) diff --git a/Task/File-input-output/Julia/file-input-output-4.julia b/Task/File-input-output/Julia/file-input-output-4.julia new file mode 100644 index 0000000000..62e6874d4a --- /dev/null +++ b/Task/File-input-output/Julia/file-input-output-4.julia @@ -0,0 +1 @@ +open(IO ->write(IO, open(readall, "file1", "r")), "file2", "w") diff --git a/Task/File-IO/K/file-io.k b/Task/File-input-output/K/file-input-output.k similarity index 100% rename from Task/File-IO/K/file-io.k rename to Task/File-input-output/K/file-input-output.k diff --git a/Task/File-IO/Lang5/file-io.lang5 b/Task/File-input-output/Lang5/file-input-output.lang5 similarity index 100% rename from Task/File-IO/Lang5/file-io.lang5 rename to Task/File-input-output/Lang5/file-input-output.lang5 diff --git a/Task/File-IO/Liberty-BASIC/file-io.liberty b/Task/File-input-output/Liberty-BASIC/file-input-output.liberty similarity index 100% rename from Task/File-IO/Liberty-BASIC/file-io.liberty rename to Task/File-input-output/Liberty-BASIC/file-input-output.liberty diff --git a/Task/File-IO/Lisaac/file-io.lisaac b/Task/File-input-output/Lisaac/file-input-output.lisaac similarity index 100% rename from Task/File-IO/Lisaac/file-io.lisaac rename to Task/File-input-output/Lisaac/file-input-output.lisaac diff --git a/Task/File-IO/Logo/file-io.logo b/Task/File-input-output/Logo/file-input-output.logo similarity index 100% rename from Task/File-IO/Logo/file-io.logo rename to Task/File-input-output/Logo/file-input-output.logo diff --git a/Task/File-IO/Lua/file-io.lua b/Task/File-input-output/Lua/file-input-output.lua similarity index 100% rename from Task/File-IO/Lua/file-io.lua rename to Task/File-input-output/Lua/file-input-output.lua diff --git a/Task/File-IO/MAXScript/file-io.max b/Task/File-input-output/MAXScript/file-input-output.max similarity index 100% rename from Task/File-IO/MAXScript/file-io.max rename to Task/File-input-output/MAXScript/file-input-output.max diff --git a/Task/File-IO/Mathematica/file-io.math b/Task/File-input-output/Mathematica/file-input-output.math similarity index 100% rename from Task/File-IO/Mathematica/file-io.math rename to Task/File-input-output/Mathematica/file-input-output.math diff --git a/Task/File-IO/Mercury/file-io.mercury b/Task/File-input-output/Mercury/file-input-output.mercury similarity index 100% rename from Task/File-IO/Mercury/file-io.mercury rename to Task/File-input-output/Mercury/file-input-output.mercury diff --git a/Task/File-IO/Modula-3/file-io.mod3 b/Task/File-input-output/Modula-3/file-input-output.mod3 similarity index 100% rename from Task/File-IO/Modula-3/file-io.mod3 rename to Task/File-input-output/Modula-3/file-input-output.mod3 diff --git a/Task/File-IO/NetRexx/file-io.netrexx b/Task/File-input-output/NetRexx/file-input-output.netrexx similarity index 100% rename from Task/File-IO/NetRexx/file-io.netrexx rename to Task/File-input-output/NetRexx/file-input-output.netrexx diff --git a/Task/File-IO/OCaml/file-io-1.ocaml b/Task/File-input-output/OCaml/file-input-output-1.ocaml similarity index 100% rename from Task/File-IO/OCaml/file-io-1.ocaml rename to Task/File-input-output/OCaml/file-input-output-1.ocaml diff --git a/Task/File-IO/OCaml/file-io-2.ocaml b/Task/File-input-output/OCaml/file-input-output-2.ocaml similarity index 100% rename from Task/File-IO/OCaml/file-io-2.ocaml rename to Task/File-input-output/OCaml/file-input-output-2.ocaml diff --git a/Task/File-IO/Objeck/file-io.objeck b/Task/File-input-output/Objeck/file-input-output.objeck similarity index 100% rename from Task/File-IO/Objeck/file-io.objeck rename to Task/File-input-output/Objeck/file-input-output.objeck diff --git a/Task/File-IO/Object-Pascal/file-io.object b/Task/File-input-output/Object-Pascal/file-input-output.object similarity index 100% rename from Task/File-IO/Object-Pascal/file-io.object rename to Task/File-input-output/Object-Pascal/file-input-output.object diff --git a/Task/File-input-output/Objective-C/file-input-output-1.m b/Task/File-input-output/Objective-C/file-input-output-1.m new file mode 100644 index 0000000000..36818cf327 --- /dev/null +++ b/Task/File-input-output/Objective-C/file-input-output-1.m @@ -0,0 +1 @@ +[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL]; diff --git a/Task/File-IO/Objective-C/file-io.m b/Task/File-input-output/Objective-C/file-input-output-2.m similarity index 100% rename from Task/File-IO/Objective-C/file-io.m rename to Task/File-input-output/Objective-C/file-input-output-2.m diff --git a/Task/File-input-output/Octave/file-input-output.octave b/Task/File-input-output/Octave/file-input-output.octave new file mode 100644 index 0000000000..41e0321e7c --- /dev/null +++ b/Task/File-input-output/Octave/file-input-output.octave @@ -0,0 +1,27 @@ +in = fopen("input.txt", "r", "native"); +out = fopen("output.txt", "w","native"); +if (in == -1) + disp("Error opening input.txt for reading."); +else +if (out == -1) + disp("Error opening output.txt for writing."); +else +while (1) + [val,count]=fread(in,1,"uchar",0,"native"); + if (count > 0) + count=fwrite(out,val,"uchar",0,"native"); + if (count == 0) + disp("Error writing to output.txt."); + end + else + break; + end +endwhile +end +end +if (in != -1) + fclose(in); +end +if (out != -1) + fclose(out); +end diff --git a/Task/File-IO/OpenEdge-Progress/file-io.openedge b/Task/File-input-output/OpenEdge-Progress/file-input-output.openedge similarity index 100% rename from Task/File-IO/OpenEdge-Progress/file-io.openedge rename to Task/File-input-output/OpenEdge-Progress/file-input-output.openedge diff --git a/Task/File-IO/Oz/file-io.oz b/Task/File-input-output/Oz/file-input-output.oz similarity index 100% rename from Task/File-IO/Oz/file-io.oz rename to Task/File-input-output/Oz/file-input-output.oz diff --git a/Task/File-IO/PARI-GP/file-io.pari b/Task/File-input-output/PARI-GP/file-input-output.pari similarity index 100% rename from Task/File-IO/PARI-GP/file-io.pari rename to Task/File-input-output/PARI-GP/file-input-output.pari diff --git a/Task/File-IO/PHP/file-io-1.php b/Task/File-input-output/PHP/file-input-output-1.php similarity index 100% rename from Task/File-IO/PHP/file-io-1.php rename to Task/File-input-output/PHP/file-input-output-1.php diff --git a/Task/File-IO/PHP/file-io-2.php b/Task/File-input-output/PHP/file-input-output-2.php similarity index 100% rename from Task/File-IO/PHP/file-io-2.php rename to Task/File-input-output/PHP/file-input-output-2.php diff --git a/Task/File-IO/PL-I/file-io.pli b/Task/File-input-output/PL-I/file-input-output.pli similarity index 100% rename from Task/File-IO/PL-I/file-io.pli rename to Task/File-input-output/PL-I/file-input-output.pli diff --git a/Task/File-IO/Perl-6/file-io-1.pl6 b/Task/File-input-output/Perl-6/file-input-output-1.pl6 similarity index 100% rename from Task/File-IO/Perl-6/file-io-1.pl6 rename to Task/File-input-output/Perl-6/file-input-output-1.pl6 diff --git a/Task/File-IO/Perl-6/file-io-2.pl6 b/Task/File-input-output/Perl-6/file-input-output-2.pl6 similarity index 100% rename from Task/File-IO/Perl-6/file-io-2.pl6 rename to Task/File-input-output/Perl-6/file-input-output-2.pl6 diff --git a/Task/File-IO/Perl/file-io.pl b/Task/File-input-output/Perl/file-input-output.pl similarity index 100% rename from Task/File-IO/Perl/file-io.pl rename to Task/File-input-output/Perl/file-input-output.pl diff --git a/Task/File-IO/PicoLisp/file-io-1.l b/Task/File-input-output/PicoLisp/file-input-output-1.l similarity index 100% rename from Task/File-IO/PicoLisp/file-io-1.l rename to Task/File-input-output/PicoLisp/file-input-output-1.l diff --git a/Task/File-IO/PicoLisp/file-io-2.l b/Task/File-input-output/PicoLisp/file-input-output-2.l similarity index 100% rename from Task/File-IO/PicoLisp/file-io-2.l rename to Task/File-input-output/PicoLisp/file-input-output-2.l diff --git a/Task/File-IO/Pop11/file-io-1.pop11 b/Task/File-input-output/Pop11/file-input-output-1.pop11 similarity index 100% rename from Task/File-IO/Pop11/file-io-1.pop11 rename to Task/File-input-output/Pop11/file-input-output-1.pop11 diff --git a/Task/File-IO/Pop11/file-io-2.pop11 b/Task/File-input-output/Pop11/file-input-output-2.pop11 similarity index 100% rename from Task/File-IO/Pop11/file-io-2.pop11 rename to Task/File-input-output/Pop11/file-input-output-2.pop11 diff --git a/Task/File-IO/PowerShell/file-io-1.psh b/Task/File-input-output/PowerShell/file-input-output-1.psh similarity index 100% rename from Task/File-IO/PowerShell/file-io-1.psh rename to Task/File-input-output/PowerShell/file-input-output-1.psh diff --git a/Task/File-IO/PowerShell/file-io-2.psh b/Task/File-input-output/PowerShell/file-input-output-2.psh similarity index 100% rename from Task/File-IO/PowerShell/file-io-2.psh rename to Task/File-input-output/PowerShell/file-input-output-2.psh diff --git a/Task/File-IO/PureBasic/file-io-1.purebasic b/Task/File-input-output/PureBasic/file-input-output-1.purebasic similarity index 100% rename from Task/File-IO/PureBasic/file-io-1.purebasic rename to Task/File-input-output/PureBasic/file-input-output-1.purebasic diff --git a/Task/File-IO/PureBasic/file-io-2.purebasic b/Task/File-input-output/PureBasic/file-input-output-2.purebasic similarity index 100% rename from Task/File-IO/PureBasic/file-io-2.purebasic rename to Task/File-input-output/PureBasic/file-input-output-2.purebasic diff --git a/Task/File-IO/PureBasic/file-io-3.purebasic b/Task/File-input-output/PureBasic/file-input-output-3.purebasic similarity index 100% rename from Task/File-IO/PureBasic/file-io-3.purebasic rename to Task/File-input-output/PureBasic/file-input-output-3.purebasic diff --git a/Task/File-IO/Python/file-io-1.py b/Task/File-input-output/Python/file-input-output-1.py similarity index 100% rename from Task/File-IO/Python/file-io-1.py rename to Task/File-input-output/Python/file-input-output-1.py diff --git a/Task/File-IO/Python/file-io-2.py b/Task/File-input-output/Python/file-input-output-2.py similarity index 100% rename from Task/File-IO/Python/file-io-2.py rename to Task/File-input-output/Python/file-input-output-2.py diff --git a/Task/File-IO/Python/file-io-3.py b/Task/File-input-output/Python/file-input-output-3.py similarity index 100% rename from Task/File-IO/Python/file-io-3.py rename to Task/File-input-output/Python/file-input-output-3.py diff --git a/Task/File-IO/Python/file-io-4.py b/Task/File-input-output/Python/file-input-output-4.py similarity index 100% rename from Task/File-IO/Python/file-io-4.py rename to Task/File-input-output/Python/file-input-output-4.py diff --git a/Task/File-IO/R/file-io-1.r b/Task/File-input-output/R/file-input-output-1.r similarity index 100% rename from Task/File-IO/R/file-io-1.r rename to Task/File-input-output/R/file-input-output-1.r diff --git a/Task/File-IO/R/file-io-2.r b/Task/File-input-output/R/file-input-output-2.r similarity index 100% rename from Task/File-IO/R/file-io-2.r rename to Task/File-input-output/R/file-input-output-2.r diff --git a/Task/File-IO/R/file-io-3.r b/Task/File-input-output/R/file-input-output-3.r similarity index 100% rename from Task/File-IO/R/file-io-3.r rename to Task/File-input-output/R/file-input-output-3.r diff --git a/Task/File-input-output/README b/Task/File-input-output/README new file mode 100644 index 0000000000..8aa1e3b045 --- /dev/null +++ b/Task/File-input-output/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/File_input/output diff --git a/Task/File-IO/REALbasic/file-io.realbasic b/Task/File-input-output/REALbasic/file-input-output.realbasic similarity index 100% rename from Task/File-IO/REALbasic/file-io.realbasic rename to Task/File-input-output/REALbasic/file-input-output.realbasic diff --git a/Task/File-IO/REBOL/file-io.rebol b/Task/File-input-output/REBOL/file-input-output.rebol similarity index 100% rename from Task/File-IO/REBOL/file-io.rebol rename to Task/File-input-output/REBOL/file-input-output.rebol diff --git a/Task/File-input-output/REXX/file-input-output-1.rexx b/Task/File-input-output/REXX/file-input-output-1.rexx new file mode 100644 index 0000000000..dd93e0998c --- /dev/null +++ b/Task/File-input-output/REXX/file-input-output-1.rexx @@ -0,0 +1,10 @@ +/*REXX program to read a file and store the contents into an output file*/ +iFID = 'input.txt' /*name of the input file. */ +oFID = 'output.txt' /*name of the output file. */ +call lineout oFID,,1 /*insure output starts at line 1.*/ + + do while lines(iFID)\==0 /*read records until finished. */ + y = linein(iFID) /*read a record from input. */ + call lineout oFID,y /*write a record to output. */ + end /*while ···*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/File-IO/REXX/file-io-3.rexx b/Task/File-input-output/REXX/file-input-output-2.rexx similarity index 100% rename from Task/File-IO/REXX/file-io-3.rexx rename to Task/File-input-output/REXX/file-input-output-2.rexx diff --git a/Task/File-IO/Racket/file-io.rkt b/Task/File-input-output/Racket/file-input-output.rkt similarity index 100% rename from Task/File-IO/Racket/file-io.rkt rename to Task/File-input-output/Racket/file-input-output.rkt diff --git a/Task/File-IO/RapidQ/file-io-1.rapidq b/Task/File-input-output/RapidQ/file-input-output-1.rapidq similarity index 100% rename from Task/File-IO/RapidQ/file-io-1.rapidq rename to Task/File-input-output/RapidQ/file-input-output-1.rapidq diff --git a/Task/File-IO/RapidQ/file-io-2.rapidq b/Task/File-input-output/RapidQ/file-input-output-2.rapidq similarity index 100% rename from Task/File-IO/RapidQ/file-io-2.rapidq rename to Task/File-input-output/RapidQ/file-input-output-2.rapidq diff --git a/Task/File-IO/Raven/file-io.raven b/Task/File-input-output/Raven/file-input-output.raven similarity index 100% rename from Task/File-IO/Raven/file-io.raven rename to Task/File-input-output/Raven/file-input-output.raven diff --git a/Task/File-IO/Retro/file-io.retro b/Task/File-input-output/Retro/file-input-output.retro similarity index 100% rename from Task/File-IO/Retro/file-io.retro rename to Task/File-input-output/Retro/file-input-output.retro diff --git a/Task/File-IO/Ruby/file-io-1.rb b/Task/File-input-output/Ruby/file-input-output-1.rb similarity index 100% rename from Task/File-IO/Ruby/file-io-1.rb rename to Task/File-input-output/Ruby/file-input-output-1.rb diff --git a/Task/File-IO/Ruby/file-io-2.rb b/Task/File-input-output/Ruby/file-input-output-2.rb similarity index 100% rename from Task/File-IO/Ruby/file-io-2.rb rename to Task/File-input-output/Ruby/file-input-output-2.rb diff --git a/Task/File-IO/Ruby/file-io-3.rb b/Task/File-input-output/Ruby/file-input-output-3.rb similarity index 100% rename from Task/File-IO/Ruby/file-io-3.rb rename to Task/File-input-output/Ruby/file-input-output-3.rb diff --git a/Task/File-IO/Run-BASIC/file-io.run b/Task/File-input-output/Run-BASIC/file-input-output.run similarity index 100% rename from Task/File-IO/Run-BASIC/file-io.run rename to Task/File-input-output/Run-BASIC/file-input-output.run diff --git a/Task/File-IO/Rust/file-io.rust b/Task/File-input-output/Rust/file-input-output.rust similarity index 100% rename from Task/File-IO/Rust/file-io.rust rename to Task/File-input-output/Rust/file-input-output.rust diff --git a/Task/File-IO/SNOBOL4/file-io.sno b/Task/File-input-output/SNOBOL4/file-input-output.sno similarity index 100% rename from Task/File-IO/SNOBOL4/file-io.sno rename to Task/File-input-output/SNOBOL4/file-input-output.sno diff --git a/Task/File-IO/Scala/file-io.scala b/Task/File-input-output/Scala/file-input-output.scala similarity index 68% rename from Task/File-IO/Scala/file-io.scala rename to Task/File-input-output/Scala/file-input-output.scala index ebdccabca9..2278bac201 100644 --- a/Task/File-IO/Scala/file-io.scala +++ b/Task/File-input-output/Scala/file-input-output.scala @@ -2,15 +2,10 @@ import java.io.{ FileNotFoundException, PrintWriter } object FileIO extends App { try { - val MyFileTxtSource = scala.io.Source.fromFile("input.txt") val MyFileTxtTarget = new PrintWriter("output.txt") - val str = MyFileTxtSource.mkString - MyFileTxtTarget.print(str) - + scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println) MyFileTxtTarget.close() - MyFileTxtSource.close() - } } catch { case e: FileNotFoundException => println(e.getLocalizedMessage()) case e: Throwable => { diff --git a/Task/File-IO/Scheme/file-io.ss b/Task/File-input-output/Scheme/file-input-output.ss similarity index 100% rename from Task/File-IO/Scheme/file-io.ss rename to Task/File-input-output/Scheme/file-input-output.ss diff --git a/Task/File-IO/Seed7/file-io.seed7 b/Task/File-input-output/Seed7/file-input-output.seed7 similarity index 100% rename from Task/File-IO/Seed7/file-io.seed7 rename to Task/File-input-output/Seed7/file-input-output.seed7 diff --git a/Task/File-IO/Slate/file-io.slate b/Task/File-input-output/Slate/file-input-output.slate similarity index 100% rename from Task/File-IO/Slate/file-io.slate rename to Task/File-input-output/Slate/file-input-output.slate diff --git a/Task/File-IO/Smalltalk/file-io.st b/Task/File-input-output/Smalltalk/file-input-output.st similarity index 100% rename from Task/File-IO/Smalltalk/file-io.st rename to Task/File-input-output/Smalltalk/file-input-output.st diff --git a/Task/File-IO/Standard-ML/file-io.ml b/Task/File-input-output/Standard-ML/file-input-output.ml similarity index 100% rename from Task/File-IO/Standard-ML/file-io.ml rename to Task/File-input-output/Standard-ML/file-input-output.ml diff --git a/Task/File-IO/Tcl/file-io-1.tcl b/Task/File-input-output/Tcl/file-input-output-1.tcl similarity index 100% rename from Task/File-IO/Tcl/file-io-1.tcl rename to Task/File-input-output/Tcl/file-input-output-1.tcl diff --git a/Task/File-IO/Tcl/file-io-2.tcl b/Task/File-input-output/Tcl/file-input-output-2.tcl similarity index 100% rename from Task/File-IO/Tcl/file-io-2.tcl rename to Task/File-input-output/Tcl/file-input-output-2.tcl diff --git a/Task/File-IO/Tcl/file-io-3.tcl b/Task/File-input-output/Tcl/file-input-output-3.tcl similarity index 100% rename from Task/File-IO/Tcl/file-io-3.tcl rename to Task/File-input-output/Tcl/file-input-output-3.tcl diff --git a/Task/File-IO/Tcl/file-io-4.tcl b/Task/File-input-output/Tcl/file-input-output-4.tcl similarity index 100% rename from Task/File-IO/Tcl/file-io-4.tcl rename to Task/File-input-output/Tcl/file-input-output-4.tcl diff --git a/Task/File-IO/Tcl/file-io-5.tcl b/Task/File-input-output/Tcl/file-input-output-5.tcl similarity index 100% rename from Task/File-IO/Tcl/file-io-5.tcl rename to Task/File-input-output/Tcl/file-input-output-5.tcl diff --git a/Task/File-IO/Toka/file-io-1.toka b/Task/File-input-output/Toka/file-input-output-1.toka similarity index 100% rename from Task/File-IO/Toka/file-io-1.toka rename to Task/File-input-output/Toka/file-input-output-1.toka diff --git a/Task/File-IO/Toka/file-io-2.toka b/Task/File-input-output/Toka/file-input-output-2.toka similarity index 100% rename from Task/File-IO/Toka/file-io-2.toka rename to Task/File-input-output/Toka/file-input-output-2.toka diff --git a/Task/File-IO/Toka/file-io-3.toka b/Task/File-input-output/Toka/file-input-output-3.toka similarity index 100% rename from Task/File-IO/Toka/file-io-3.toka rename to Task/File-input-output/Toka/file-input-output-3.toka diff --git a/Task/File-IO/UNIX-Shell/file-io-1.sh b/Task/File-input-output/UNIX-Shell/file-input-output-1.sh similarity index 100% rename from Task/File-IO/UNIX-Shell/file-io-1.sh rename to Task/File-input-output/UNIX-Shell/file-input-output-1.sh diff --git a/Task/File-IO/UNIX-Shell/file-io-2.sh b/Task/File-input-output/UNIX-Shell/file-input-output-2.sh similarity index 100% rename from Task/File-IO/UNIX-Shell/file-io-2.sh rename to Task/File-input-output/UNIX-Shell/file-input-output-2.sh diff --git a/Task/File-IO/UNIX-Shell/file-io-3.sh b/Task/File-input-output/UNIX-Shell/file-input-output-3.sh similarity index 100% rename from Task/File-IO/UNIX-Shell/file-io-3.sh rename to Task/File-input-output/UNIX-Shell/file-input-output-3.sh diff --git a/Task/File-IO/Ursala/file-io.ursala b/Task/File-input-output/Ursala/file-input-output.ursala similarity index 100% rename from Task/File-IO/Ursala/file-io.ursala rename to Task/File-input-output/Ursala/file-input-output.ursala diff --git a/Task/File-IO/VBScript/file-io.vb b/Task/File-input-output/VBScript/file-input-output.vb similarity index 100% rename from Task/File-IO/VBScript/file-io.vb rename to Task/File-input-output/VBScript/file-input-output.vb diff --git a/Task/File-IO/Vedit-macro-language/file-io.vedit b/Task/File-input-output/Vedit-macro-language/file-input-output.vedit similarity index 100% rename from Task/File-IO/Vedit-macro-language/file-io.vedit rename to Task/File-input-output/Vedit-macro-language/file-input-output.vedit diff --git a/Task/File-IO/Visual-Basic-.NET/file-io.visual b/Task/File-input-output/Visual-Basic-.NET/file-input-output.visual similarity index 100% rename from Task/File-IO/Visual-Basic-.NET/file-io.visual rename to Task/File-input-output/Visual-Basic-.NET/file-input-output.visual diff --git a/Task/File-IO/XPL0/file-io.xpl0 b/Task/File-input-output/XPL0/file-input-output.xpl0 similarity index 100% rename from Task/File-IO/XPL0/file-io.xpl0 rename to Task/File-input-output/XPL0/file-input-output.xpl0 diff --git a/Task/Find-the-last-Sunday-of-each-month/00DESCRIPTION b/Task/Find-the-last-Sunday-of-each-month/00DESCRIPTION new file mode 100644 index 0000000000..056b8f08fa --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/00DESCRIPTION @@ -0,0 +1,25 @@ +Write a program or a script that returns the last Sundays 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: + +
./last_sundays 2013
+2013-01-27
+2013-02-24
+2013-03-31
+2013-04-28
+2013-05-26
+2013-06-30
+2013-07-28
+2013-08-25
+2013-09-29
+2013-10-27
+2013-11-24
+2013-12-29
+ +;Cf.: +* [[Day of the week]] +* [[Five weekends]] +* [[Last Friday of each month]] diff --git a/Task/Find-the-last-Sunday-of-each-month/00META.yaml b/Task/Find-the-last-Sunday-of-each-month/00META.yaml new file mode 100644 index 0000000000..e71737a981 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Date and time diff --git a/Task/Find-the-last-Sunday-of-each-month/AutoHotkey/find-the-last-sunday-of-each-month.ahk b/Task/Find-the-last-Sunday-of-each-month/AutoHotkey/find-the-last-sunday-of-each-month.ahk new file mode 100644 index 0000000000..a467358254 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/AutoHotkey/find-the-last-sunday-of-each-month.ahk @@ -0,0 +1,20 @@ +InputBox, Year, , Enter a year., , 300, 135 +Date := Year . "0101" + +while SubStr(Date, 1, 4) = Year { + FormatTime, WD, % Date, WDay + if (WD = 1) + MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2) + Date += 1, Days +} + +Gui, Font, S10, Courier New +Gui, Add, Text, , % "Last Sundays of " Year ":`n---------------------" + +Loop, 12 { + FormatTime, Month, % Year (A_Index > 9 ? "" : "0") A_Index, MMMM + Gui, Add, Text, y+1, % Month (StrLen(Month) > 7 ? "" : "`t") "`t" Day%A_Index% +} + +Gui, Show +return diff --git a/Task/Find-the-last-Sunday-of-each-month/BBC-BASIC/find-the-last-sunday-of-each-month.bbc b/Task/Find-the-last-Sunday-of-each-month/BBC-BASIC/find-the-last-sunday-of-each-month.bbc new file mode 100644 index 0000000000..8d94868641 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/BBC-BASIC/find-the-last-sunday-of-each-month.bbc @@ -0,0 +1,9 @@ +INSTALL @lib$+"DATELIB" + +INPUT "What year to calculate (YYYY)? " Year% + +PRINT '"Last Sundays in ";Year%;" are on:" +FOR Month%=1 TO 12 + PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%)) +NEXT +END diff --git a/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-1.cpp b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-1.cpp new file mode 100644 index 0000000000..1ecbdb00da --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-1.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class lastSunday +{ +public: + lastSunday() + { + m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; + m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: "; + m[8] = "SEPTEMBER: "; m[9] = "OCTOBER: "; m[10] = "NOVEMBER: "; m[11] = "DECEMBER: "; + } + + void findLastSunday( int y ) + { + year = y; + isleapyear(); + + int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, + d; + for( int i = 0; i < 12; i++ ) + { + d = days[i]; + while( true ) + { + if( !getWeekDay( i, d ) ) break; + d--; + } + lastDay[i] = d; + } + + display(); + } + +private: + void isleapyear() + { + isleap = false; + if( !( year % 4 ) ) + { + if( year % 100 ) isleap = true; + else if( !( year % 400 ) ) isleap = true; + } + } + + void display() + { + system( "cls" ); + cout << " YEAR " << year << endl << "=============" << endl; + for( int x = 0; x < 12; x++ ) + cout << m[x] << lastDay[x] << endl; + + cout << endl << endl; + } + + int getWeekDay( int m, int d ) + { + int y = year; + + int f = y + d + 3 * m - 1; + m++; + if( m < 3 ) y--; + else f -= int( .4 * m + 2.3 ); + + f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); + f %= 7; + + return f; + } + + int lastDay[12], year; + string m[12]; + bool isleap; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + int y; + lastSunday ls; + + while( true ) + { + system( "cls" ); + cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; + cin >> y; + if( !y ) return 0; + + ls.findLastSunday( y ); + + system( "pause" ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-2.cpp b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-2.cpp new file mode 100644 index 0000000000..6e33791ea0 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/C++/find-the-last-sunday-of-each-month-2.cpp @@ -0,0 +1,23 @@ +#include +#include +#include + +int main( int argc , char* argv[ ] ) { + using namespace boost::gregorian ; + + int year = std::atoi( argv[ 1 ] ) ; + for ( int i = 1 ; i < 13 ; i++ ) { + try { + date d( year , i , 1 ) ; + d = d.end_of_month( ) ; + day_iterator d_itr ( d ) ; + while ( d_itr->day_of_week( ) != Sunday ) { + --d_itr ; + } + std::cout << to_simple_string ( *d_itr ) << std::endl ; + } catch ( bad_year by ) { + std::cout << "Terminated because of " << by.what( ) << "\n" ; + } + } + return 0 ; +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Clojure/find-the-last-sunday-of-each-month.clj b/Task/Find-the-last-Sunday-of-each-month/Clojure/find-the-last-sunday-of-each-month.clj new file mode 100644 index 0000000000..050def09b0 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Clojure/find-the-last-sunday-of-each-month.clj @@ -0,0 +1,25 @@ +(ns last-sundays.core + (:require [clj-time.core :as time] + [clj-time.periodic :refer [periodic-seq]] + [clj-time.format :as fmt]) + (:import (org.joda.time DateTime DateTimeConstants)) + (:gen-class)) + +(defn sunday? [t] + (= (.getDayOfWeek t) (DateTimeConstants/SUNDAY))) + +(defn sundays [year] + (take-while #(= (time/year %) year) + (filter sunday? (periodic-seq (time/date-time year 1 1) (time/days 1))))) + +(defn last-sundays-of-months [year] + (->> (sundays year) + (group-by time/month) + (vals) + (map (comp first #(sort-by time/day > %))) + (map #(fmt/unparse (fmt/formatters :year-month-day) %)) + (interpose "\n") + (apply str))) + +(defn -main [& args] + (println (last-sundays-of-months (Integer. (first args))))) diff --git a/Task/Find-the-last-Sunday-of-each-month/D/find-the-last-sunday-of-each-month.d b/Task/Find-the-last-Sunday-of-each-month/D/find-the-last-sunday-of-each-month.d new file mode 100644 index 0000000000..716a84714e --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/D/find-the-last-sunday-of-each-month.d @@ -0,0 +1,14 @@ +void lastSundays(in uint year) { + import std.stdio, std.datetime; + + foreach (immutable month; 1 .. 13) { + auto date = Date(year, month, 1); + date.day(date.daysInMonth); + date.roll!"days"(-(date.dayOfWeek + 7) % 7); + date.writeln; + } +} + +void main() { + lastSundays(2013); +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl b/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl new file mode 100644 index 0000000000..41ebe4dc74 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl @@ -0,0 +1,18 @@ +-module( last_date_each_month ). + +-export( [monday/1, tuesday/1, wednesday/1, thursday/1, friday/1, saturday/1, sunday/1] ). + +monday( Year ) -> last( Year, 1 ). +tuesday( Year ) -> last( Year, 2 ). +wednesday( Year ) -> last( Year, 3 ). +thursday( Year ) -> last( Year, 4 ). +friday( Year ) -> last( Year, 5 ). +saturday( Year ) -> last( Year, 6 ). +sunday( Year ) -> last( Year, 7 ). + + + +last( Year, Week_day ) -> + Months = lists:seq( 1, 12 ), + Months_days = [{X, Y} || X <- Months, Y <- lists:seq(calendar:last_day_of_the_month(Year, X), calendar:last_day_of_the_month(Year, X) - 7, -1), calendar:valid_date(Year, X, Y), calendar:day_of_the_week(Year, X, Y) =:= Week_day], + [{Year, X, proplists:get_value(X, Months_days)} || X <- Months]. diff --git a/Task/Find-the-last-Sunday-of-each-month/FBSL/find-the-last-sunday-of-each-month.fbsl b/Task/Find-the-last-Sunday-of-each-month/FBSL/find-the-last-sunday-of-each-month.fbsl new file mode 100644 index 0000000000..83cdc79c95 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/FBSL/find-the-last-sunday-of-each-month.fbsl @@ -0,0 +1,17 @@ +#APPTYPE CONSOLE + +DIM date AS INTEGER, dayname AS STRING +FOR DIM i = 1 TO 12 + FOR DIM j = 31 DOWNTO 1 + date = 20130000 + (i * 100) + j + IF CHECKDATE(i, j, 2013) THEN + dayname = DATECONV(date, "dddd") + IF dayname = "Sunday" THEN + PRINT 2013, " ", i, " ", j + EXIT FOR + END IF + END IF + NEXT +NEXT + +PAUSE diff --git a/Task/Find-the-last-Sunday-of-each-month/Go/find-the-last-sunday-of-each-month.go b/Task/Find-the-last-Sunday-of-each-month/Go/find-the-last-sunday-of-each-month.go new file mode 100644 index 0000000000..11d87ceaae --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Go/find-the-last-sunday-of-each-month.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + + var year int + var t time.Time + var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } + + for { + fmt.Print("Please select a year: ") + _, err := fmt.Scanf("%d", &year) + if err != nil { + fmt.Println(err) + continue + } else { + break + } + } + + fmt.Println("Last Sundays of each month of", year) + fmt.Println("==================================") + + for i := 1;i < 13; i++ { + j := lastDay[i-1] + if i == 2 { + if time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC).Month() == time.Date(int(year), time.Month(i), j-1, 0, 0, 0, 0, time.UTC).Month() { + j = 29 + } else { + j = 28 + } + } + for { + t = time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC) + if t.Weekday() == 0 { + fmt.Printf("%s: %d\n", time.Month(i), j) + break + } + j = j - 1 + } + } +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-1.groovy b/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-1.groovy new file mode 100644 index 0000000000..331bf8d951 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-1.groovy @@ -0,0 +1,16 @@ +enum Day { + Sun, Mon, Tue, Wed, Thu, Fri, Sat + static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } +} + +def date = Date.&parse.curry('yyyy-MM-dd') +def month = { it.format('MM') } +def days = { year -> (date("${year}-01-01").. days(year).findAll { Day.valueOf(it) == dayOfWeek } } + +def lastWeekDays = { dayOfWeek, year -> + weekDays(dayOfWeek, year).reverse().inject([:]) { months, sunday -> + def monthStr = month(sunday) + !months[monthStr] ? months + [(monthStr):sunday] : months + }.values().sort() +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-2.groovy b/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-2.groovy new file mode 100644 index 0000000000..e1d5f7f38c --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Groovy/find-the-last-sunday-of-each-month-2.groovy @@ -0,0 +1,3 @@ +def ymd = { it.format('yyyy-MM-dd') } +def lastSundays = lastWeekDays.curry(Day.Sun) +lastSundays(args[0] as int).each { println (ymd(it)) } diff --git a/Task/Find-the-last-Sunday-of-each-month/Icon/find-the-last-sunday-of-each-month.icon b/Task/Find-the-last-Sunday-of-each-month/Icon/find-the-last-sunday-of-each-month.icon new file mode 100644 index 0000000000..e9fe18896a --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Icon/find-the-last-sunday-of-each-month.icon @@ -0,0 +1,20 @@ +procedure main(A) +every write(lastsundays(!A)) +end + +procedure lastsundays(year) +every m := 1 to 12 do { + d := case m of { + 2 : if IsLeapYear(year) then 29 else 28 + 4|6|9|11 : 30 + default : 31 + } # last day of month + + z := 0 + j := julian(m,d,year) + 1 # first day of next month + until (j-:=1)%7 = 6 do z -:=1 # backup to last sunday (6) + suspend sprintf("%d-%d-%d",year,m,d+z) + } +end + +link datetime, printf diff --git a/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-1.j b/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-1.j new file mode 100644 index 0000000000..55c69715b4 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-1.j @@ -0,0 +1,2 @@ +require'dates' +last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1 diff --git a/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-2.j b/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-2.j new file mode 100644 index 0000000000..3161785650 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/J/find-the-last-sunday-of-each-month-2.j @@ -0,0 +1,13 @@ + last_sundays 2013 +2013 1 27 +2013 2 24 +2013 3 31 +2013 4 28 +2013 5 26 +2013 6 30 +2013 7 28 +2013 8 25 +2013 9 29 +2013 10 27 +2013 11 24 +2013 12 29 diff --git a/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-1.java b/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-1.java new file mode 100644 index 0000000000..c866582dda --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-1.java @@ -0,0 +1,72 @@ +import java.util.Scanner; + +public class LastSunday +{ + static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; + + public static int[] findLastSunday(int year) + { + boolean isLeap = isLeapYear(year); + + int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31}; + int[] lastDay=new int[12]; + + for(int m=0;i<12;i++) + { + int d; + for(d=days[m]; getWeekDay(year,m,d)!=0; d--) + ; + lastDay[m]=d; + } + + return lastDay; + } + + private static boolean isLeapYear(int year) + { + if(year%4==0) + { + if(year%100!=0) + return true; + else if (year%400==0) + return true; + } + return false; + } + + private static int getWeekDay(int y, int m, int d) + { + int f=y+d+3*m-1; + m++; + + if(m<3) + y--; + else + f-=(int)(0.4*m+2.3); + + f+=(int)(y/4)-(int)((y/100+1)*0.75); + f%=7; + + return f; + } + + private static void display(int year, int[] lastDay) + { + System.out.println("\nYEAR: "+year); + for(int m=0;i<12;i++) + System.out.println(months[m]+": "+lastDay[m]); + } + + public static void main(String[] args) throws Exception + { + System.out.print("Enter year: "); + Scanner s=new Scanner(System.in); + + int y=Integer.parseInt(s.next()); + + int[] lastDay = findLastSunday(y); + display(y, lastDay); + + s.close(); + } +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-2.java b/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-2.java new file mode 100644 index 0000000000..39085d3661 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Java/find-the-last-sunday-of-each-month-2.java @@ -0,0 +1,29 @@ +import java.time.*; +import java.util.stream.*; +import static java.time.temporal.TemporalAdjusters.*; + +public class FindTheLastSundayOfEachMonth { + public static Stream lastSundaysOf(int year) { + return IntStream.rangeClosed(1, 12).mapToObj(month -> + LocalDate.of(year, month, 1).with(lastDayOfMonth()) + .with(previousOrSame(DayOfWeek.SUNDAY)) + ); + } + + public static java.util.List listLastSundaysOf(int year) { + return lastSundaysOf(year).collect(Collectors.toList()); + } + + public static void main(String[] args) throws Exception { + int year = args.length > 0 ? Integer.parseInt(args[0]) : LocalDate.now().getYear(); + + for (LocalDate d : listLastSundaysOf(year)) { + System.out.println(d); + }; + + String result = lastSundaysOf(2013).map(LocalDate::toString).collect(Collectors.joining("\n")); + String test = "2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29"; + if (!test.equals(result)) throw new AssertionError("test failure"); + } + +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Mathematica/find-the-last-sunday-of-each-month.math b/Task/Find-the-last-Sunday-of-each-month/Mathematica/find-the-last-sunday-of-each-month.math new file mode 100644 index 0000000000..025c231953 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Mathematica/find-the-last-sunday-of-each-month.math @@ -0,0 +1,6 @@ +LastSundays[year_] := + Table[Last@ + DayRange[{year, i}, + DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, + 12}] +LastSundays[2013] diff --git a/Task/Find-the-last-Sunday-of-each-month/OCaml/find-the-last-sunday-of-each-month.ocaml b/Task/Find-the-last-Sunday-of-each-month/OCaml/find-the-last-sunday-of-each-month.ocaml new file mode 100644 index 0000000000..7a372f84ae --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/OCaml/find-the-last-sunday-of-each-month.ocaml @@ -0,0 +1,41 @@ +let is_leap_year y = + (* See OCaml solution on Rosetta Code for + determing if it's a leap year *) + if (y mod 100) = 0 + then (y mod 400) = 0 + else (y mod 4) = 0;; + +let get_days y = + if is_leap_year y + then + [31;29;31;30;31;30;31;31;30;31;30;31] + else + [31;28;31;30;31;30;31;31;30;31;30;31];; + +let print_date = Printf.printf "%d/%d/%d\n";; + +let get_day_of_week y m d = + let y = if m > 2 then y else y - 1 in + let c = y / 100 in + let y = y mod 100 in + let m_shifted = float_of_int ( ((m + 9) mod 12) + 1) in + let m_factor = int_of_float (2.6 *. m_shifted -. 0.2) in + let leap_factor = 5 * (y mod 4) + 3 * (y mod 7) + 5 * (c mod 4) in + (d + m_factor + leap_factor) mod 7;; + +let get_shift y m last_day = + get_day_of_week y m last_day;; + +let print_last_sunday y m = + let days = get_days y in + let last_day = List.nth days (m - 1) in + let last_sunday = last_day - (get_shift y m last_day) in + print_date y m last_sunday;; + +let print_last_sundays y = + let months = [1;2;3;4;5;6;7;8;9;10;11;12] in + List.iter (print_last_sunday y) months;; + +match (Array.length Sys.argv ) with + 2 -> print_last_sundays( int_of_string (Sys.argv.(1))); + |_ -> invalid_arg "Please enter a year"; diff --git a/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 new file mode 100644 index 0000000000..77d88811fc --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 @@ -0,0 +1,8 @@ +for (1..12) -> $i { + my $lastDay = Date.days-in-month( @*ARGS[ 0 ].Int , $i ) ; + my $lastDate = Date.new( @*ARGS[ 0 ].Int , $i , $lastDay ) ; + while $lastDate.day-of-week != 7 { + $lastDate -= 1 ; + } + $lastDate.say ; +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Perl/find-the-last-sunday-of-each-month.pl b/Task/Find-the-last-Sunday-of-each-month/Perl/find-the-last-sunday-of-each-month.pl new file mode 100644 index 0000000000..3334d185ad --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Perl/find-the-last-sunday-of-each-month.pl @@ -0,0 +1,14 @@ +#!/usr/bin/perl +use strict ; +use warnings ; +use DateTime ; + +for my $i( 1..12 ) { + my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , + month => $i ) ; + while ( $date->dow != 7 ) { + $date = $date->subtract( days => 1 ) ; + } + my $ymd = $date->ymd ; + print "$ymd\n" ; +} diff --git a/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-1.l b/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-1.l new file mode 100644 index 0000000000..8b9397af92 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-1.l @@ -0,0 +1,7 @@ +(de lastSundays (Y) + (for M 12 + (prinl + (dat$ + (find '((D) (= "Sunday" (day D))) + (mapcar '((D) (date Y M D)) `(range 31 22)) ) + "-" ) ) ) ) diff --git a/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-2.l b/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-2.l new file mode 100644 index 0000000000..3ace323ead --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PicoLisp/find-the-last-sunday-of-each-month-2.l @@ -0,0 +1,13 @@ +: (lastSundays 2013) +2013-01-27 +2013-02-24 +2013-03-31 +2013-04-28 +2013-05-26 +2013-06-30 +2013-07-28 +2013-08-25 +2013-09-29 +2013-10-27 +2013-11-24 +2013-12-29 diff --git a/Task/Find-the-last-Sunday-of-each-month/Python/find-the-last-sunday-of-each-month.py b/Task/Find-the-last-Sunday-of-each-month/Python/find-the-last-sunday-of-each-month.py new file mode 100644 index 0000000000..697b06bfac --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Python/find-the-last-sunday-of-each-month.py @@ -0,0 +1,42 @@ +#!/usr/bin/python3 + +''' + Output: + 2013-Jan-27 + 2013-Feb-24 + 2013-Mar-31 + 2013-Apr-28 + 2013-May-26 + 2013-Jun-30 + 2013-Jul-28 + 2013-Aug-25 + 2013-Sep-29 + 2013-Oct-27 + 2013-Nov-24 + 2013-Dec-29 +''' + +import sys +import calendar + +YEAR = sys.argv[-1] +try: + year = int(YEAR) +except: + year = 2013 + YEAR = str(year) + +c = calendar.Calendar(firstweekday = 0) # Sunday is day 6. + +result = [] +for month in range(0+1,12+1): + MON = calendar.month_abbr[month] + # list of weeks of tuples has too much structure + # Use the overloaded list.__add__ operator to remove the week structure. + flatter = sum(c.monthdays2calendar(year, month), []) + # make a dictionary keyed by number of day of week, + # successively overwriting values. + SUNDAY = {b: a for (a, b) in flatter if a}[6] + result.append('{}-{}-{:2}'.format(YEAR, MON, SUNDAY)) + +print('\n'.join(result)) diff --git a/Task/Find-the-last-Sunday-of-each-month/README b/Task/Find-the-last-Sunday-of-each-month/README new file mode 100644 index 0000000000..a25c162294 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month diff --git a/Task/Find-the-last-Sunday-of-each-month/REBOL/find-the-last-sunday-of-each-month.rebol b/Task/Find-the-last-Sunday-of-each-month/REBOL/find-the-last-sunday-of-each-month.rebol new file mode 100644 index 0000000000..f45c656e7e --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/REBOL/find-the-last-sunday-of-each-month.rebol @@ -0,0 +1,16 @@ +#!/usr/bin/env rebol + +last-sundays-of-year: function [ + "Return series of last sunday (date!) for each month of the year" + year [integer!] "which year?" + ][ + d: to-date reduce [1 1 year] ; start with first day of year + collect [ + repeat month 12 [ + d/month: month + 1 ; move to start of next month + keep d - d/weekday ; calculate last sunday & keep + ] + ] +] + +foreach sunday last-sundays-of-year to-integer system/script/args [print sunday] diff --git a/Task/Find-the-last-Sunday-of-each-month/REXX/find-the-last-sunday-of-each-month.rexx b/Task/Find-the-last-Sunday-of-each-month/REXX/find-the-last-sunday-of-each-month.rexx new file mode 100644 index 0000000000..21a4cc7762 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/REXX/find-the-last-sunday-of-each-month.rexx @@ -0,0 +1,79 @@ +/*REXX program displays dates of last Sundays of each month for any year*/ +parse arg yyyy + do j=1 for 12 + _ = lastDOW('Sunday', j, yyyy) + say right(_,4)'-'right(j,2,0)"-"left(word(_,2),2) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ lastDOW: procedure to return the date of the last day-of-week of │ + │ any particular month of any particular year. │ + │ │ + │ The day-of-week must be specified (it can be in any case, │ + │ (lower-/mixed-/upper-case) as an English name of the spelled day │ + │ of the week, with a minimum length that causes no ambiguity. │ + │ I.E.: W for Wednesday, Sa for Saturday, Su for Sunday ... │ + │ │ + │ The month can be specified as an integer 1 ──► 12 │ + │ 1=January 2=February 3=March ... 12=December │ + │ or the English name of the month, with a minimum length that │ + │ causes no ambiguity. I.E.: Jun for June, D for December. │ + │ If omitted [or an asterisk(*)], the current month is used. │ + │ │ + │ The year is specified as an integer or just the last two digits │ + │ (two digit years are assumed to be in the current century, and │ + │ there is no windowing for a two-digit year). │ + │ If omitted [or an asterisk(*)], the current year is used. │ + │ Years < 100 must be specified with (at least 2) leading zeroes.│ + │ │ + │ Method used: find the "day number" of the 1st of the next month, │ + │ then subtract one (this gives the "day number" of the last day of │ + │ the month, bypassing the leapday mess). The last day-of-week is │ + │ then obtained straightforwardly, or via subtraction. │ + └────────────────────────────────────────────────────────────────────┘*/ +lastdow: procedure; arg dow .,mm .,yy . /*DOW = day of week*/ +parse arg a.1,a.2,a.3 /*orig args, errmsg*/ +if mm=='' | mm=='*' then mm=left(date('U'),2) /*use default month*/ +if yy=='' | yy=='*' then yy=left(date('S'),4) /*use default year */ +if length(yy)==2 then yy=left(date('S'),2)yy /*append century. */ + /*Note mandatory leading blank in strings below.*/ +$=" Monday TUesday Wednesday THursday Friday SAturday SUnday" +!=" JAnuary February MARch APril MAY JUNe JULy AUgust September", + " October November December" +upper $ ! /*uppercase strings*/ +if dow=='' then call .er "wasn't specified",1 +if arg()>3 then call .er 'arguments specified',4 + + do j=1 for 3 /*any plural args ?*/ + if words(arg(j))>1 then call .er 'is illegal:',j + end + +dw=pos(' 'dow,$) /*find day-of-week*/ +if dw==0 then call .er 'is invalid:',1 +if dw\==lastpos(' 'dow,$) then call .er 'is ambigious:',1 + +if datatype(mm,'month') then /*if MM is alpha...*/ + do + m=pos(' 'mm,!) /*maybe its good...*/ + if m==0 then call .er 'is invalid:',1 + if m\==lastpos(' 'mm,!) then call .er 'is ambigious:',2 + mm=wordpos(word(substr(!,m),1),!)-1 /*now, use true Mon*/ + end + +if \datatype(mm,'W') then call .er "isn't an integer:",2 +if \datatype(yy,'W') then call .er "isn't an integer:",3 +if mm<1 | mm>12 then call .er "isn't in range 1──►12:",2 +if yy=0 then call .er "can't be 0 (zero):",3 +if yy<0 then call .er "can't be negative:",3 +if yy>9999 then call .er "can't be > 9999:",3 + +tdow=wordpos(word(substr($,dw),1),$)-1 /*target DOW, 0──►6*/ + /*day# of last dom.*/ +_=date('B',right(yy+(mm=12),4)right(mm//12+1,2,0)"01",'S')-1 +?=_//7 /*calc. DOW, 0──►6*/ +if ?\==tdow then _=_-?-7+tdow+7*(?>tdow) /*not DOW? Adjust.*/ +return date('weekday',_,"B") date(,_,'B') /*return the answer*/ + +.er: arg ,_;say; say '***error!*** (in LASTDOW)';say /*tell error, and */ + say word('day-of-week month year excess',arg(2)) arg(1) a._ + say; exit 13 /*... then exit. */ diff --git a/Task/Find-the-last-Sunday-of-each-month/Racket/find-the-last-sunday-of-each-month.rkt b/Task/Find-the-last-Sunday-of-each-month/Racket/find-the-last-sunday-of-each-month.rkt new file mode 100644 index 0000000000..b181f0efed --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Racket/find-the-last-sunday-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-sundays y) + (for/list ([m (in-range 1 13)]) + (prev-sunday (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-sunday d) + (if (eq? (week-day d) 'sun) + d + (prev-sunday (prev-day d)))) + +(for ([d (last-sundays 2013)]) + (displayln (~a (date->string d "~a ~d ~b ~Y")))) diff --git a/Task/Find-the-last-Sunday-of-each-month/Ruby/find-the-last-sunday-of-each-month.rb b/Task/Find-the-last-Sunday-of-each-month/Ruby/find-the-last-sunday-of-each-month.rb new file mode 100644 index 0000000000..2b172e248d --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Ruby/find-the-last-sunday-of-each-month.rb @@ -0,0 +1,10 @@ +require 'date' + +def last_sundays_of_year(year = Date.today.year) + (1..12).map do |month| + d = Date.new(year, month, -1) # -1 means "last". + d - d.wday + end +end + +puts last_sundays_of_year(2013) diff --git a/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-1.scala b/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-1.scala new file mode 100644 index 0000000000..badb7fb17e --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-1.scala @@ -0,0 +1,15 @@ +object FindTheLastSundayOfEachMonth extends App { + import java.util.Calendar._ + val cal = getInstance + + def lastSundaysOf(year: Int) = + (JANUARY to DECEMBER).map{month => + cal.set(year, month + 1, 1) // first day of next month + (1 to 7).find{_ => cal.add(DAY_OF_MONTH, -1); cal.get(DAY_OF_WEEK) == SUNDAY} + cal.getTime + } + + val year = args.headOption.map(_.toInt).getOrElse(cal.get(YEAR)) + val fmt = new java.text.SimpleDateFormat("yyyy-MM-dd") + println(lastSundaysOf(year).map(fmt.format) mkString "\n") +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-2.scala b/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-2.scala new file mode 100644 index 0000000000..370a390bdd --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Scala/find-the-last-sunday-of-each-month-2.scala @@ -0,0 +1,8 @@ +object FindTheLastSundayOfEachMonth extends App { + def lastSundaysOf(year: Int) = (1 to 12).map{month => + import java.time._; import java.time.temporal.TemporalAdjusters._ + LocalDate.of(year, month, 1).`with`(lastDayOfMonth).`with`(previousOrSame(DayOfWeek.SUNDAY))} + + val year = args.headOption.map(_.toInt).getOrElse(java.time.LocalDate.now.getYear) + println(lastSundaysOf(year) mkString "\n") +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Seed7/find-the-last-sunday-of-each-month.seed7 b/Task/Find-the-last-Sunday-of-each-month/Seed7/find-the-last-sunday-of-each-month.seed7 new file mode 100644 index 0000000000..39574314ca --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Seed7/find-the-last-sunday-of-each-month.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + include "time.s7i"; + include "duration.s7i"; + +const proc: main is func + local + var integer: weekday is 1; # 1 for monday, 2 for tuesday, and so on up to 7 for sunday. + var integer: year is 0; + var integer: month is 1; + var time: aDate is time.value; + var time: selected is time.value; + begin + if length(argv(PROGRAM)) <> 2 then + writeln("usage: lastWeekdayInMonth weekday year"); + writeln(" weekday: 1 for monday, 2 for tuesday, and so on up to 7 for sunday."); + else + weekday := integer parse (argv(PROGRAM)[1]); + year := integer parse (argv(PROGRAM)[2]); + for month range 1 to 12 do + aDate := date(year, month, 1); + while aDate.month = month do + if dayOfWeek(aDate) = weekday then + selected := aDate; + end if; + aDate +:= 1 . DAYS; + end while; + writeln(strDate(selected)); + end for; + end if; + end func; diff --git a/Task/Find-the-last-Sunday-of-each-month/Tcl/find-the-last-sunday-of-each-month.tcl b/Task/Find-the-last-Sunday-of-each-month/Tcl/find-the-last-sunday-of-each-month.tcl new file mode 100644 index 0000000000..dab3969ed6 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Tcl/find-the-last-sunday-of-each-month.tcl @@ -0,0 +1,14 @@ +proc lastSundays {{year ""}} { + if {$year eq ""} { + set year [clock format [clock seconds] -gmt 1 -format "%Y"] + } + foreach month {2 3 4 5 6 7 8 9 10 11 12 13} { + set d [clock add [clock scan "$month/1/$year" -gmt 1] -1 day] + while {[clock format $d -gmt 1 -format "%u"] != 7} { + set d [clock add $d -1 day] + } + lappend result [clock format $d -gmt 1 -format "%Y-%m-%d"] + } + return $result +} +puts [join [lastSundays {*}$argv] "\n"] diff --git a/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vb b/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vb new file mode 100644 index 0000000000..b129959f41 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vb @@ -0,0 +1,6 @@ +strYear = WScript.StdIn.ReadLine + +For i = 1 To 12 + d = DateSerial(strYear, i + 1, 1) - 1 + WScript.Echo d - Weekday(d) + 1 +Next diff --git a/Task/Flipping-bits-game/00DESCRIPTION b/Task/Flipping-bits-game/00DESCRIPTION new file mode 100644 index 0000000000..fb78d36a45 --- /dev/null +++ b/Task/Flipping-bits-game/00DESCRIPTION @@ -0,0 +1,17 @@ +;The game: +Given an N by N square array of zeroes or ones in an initial +configuration, and a target configuration of zeroes and ones +The task is to transform one to the other in as few moves as +possible by inverting whole numbered rows or whole lettered +columns at once, as one move. + +In an inversion any 1 becomes 0, and any 0 becomes 1 for that +whole row or column. + +;The Task: +The task is to create a program to score for the Flipping bits game. +# The game should create an original random target configuration and a starting configuration. +# Ensure that the starting position is ''never'' the target position. +# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position). +# The number of moves taken so far should be shown. +Show an example of a short game here, on this page, for a 3 by 3 array of bits. diff --git a/Task/Flipping-bits-game/00META.yaml b/Task/Flipping-bits-game/00META.yaml new file mode 100644 index 0000000000..e56ba72653 --- /dev/null +++ b/Task/Flipping-bits-game/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Games diff --git a/Task/Flipping-bits-game/Ada/flipping-bits-game.ada b/Task/Flipping-bits-game/Ada/flipping-bits-game.ada new file mode 100644 index 0000000000..bdab992bff --- /dev/null +++ b/Task/Flipping-bits-game/Ada/flipping-bits-game.ada @@ -0,0 +1,104 @@ +with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Discrete_Random; + +procedure Flip_Bits is + + subtype Letter is Character range 'a' .. 'z'; + + Last_Col: constant letter := Ada.Command_Line.Argument(1)(1); + Last_Row: constant Positive := Positive'Value(Ada.Command_Line.Argument(2)); + + package Boolean_Rand is new Ada.Numerics.Discrete_Random(Boolean); + Gen: Boolean_Rand.Generator; + + type Matrix is array + (Letter range 'a' .. Last_Col, Positive range 1 .. Last_Row) of Boolean; + + function Rand_Mat return Matrix is + M: Matrix; + begin + for I in M'Range(1) loop + for J in M'Range(2) loop + M(I,J) := Boolean_Rand.Random(Gen); + end loop; + end loop; + return M; + end Rand_Mat; + + function Rand_Mat(Start: Matrix) return Matrix is + M: Matrix := Start; + begin + for I in M'Range(1) loop + if Boolean_Rand.Random(Gen) then + for J in M'Range(2) loop + M(I,J) := not M(I, J); + end loop; + end if; + end loop; + for I in M'Range(2) loop + if Boolean_Rand.Random(Gen) then + for J in M'Range(1) loop + M(J,I) := not M(J, I); + end loop; + end if; + end loop; + return M; + end Rand_Mat; + + procedure Print(Message: String; Mat: Matrix) is + package NIO is new Ada.Text_IO.Integer_IO(Natural); + begin + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line(Message); + Ada.Text_IO.Put(" "); + for Ch in Matrix'Range(1) loop + Ada.Text_IO.Put(" " & Ch); + end loop; + Ada.Text_IO.New_Line; + for I in Matrix'Range(2) loop + NIO.Put(I, Width => 3); + for Ch in Matrix'Range(1) loop + Ada.Text_IO.Put(if Mat(Ch, I) then " 1" else " 0"); + end loop; + Ada.Text_IO.New_Line; + end loop; + end Print; + + Current, Target: Matrix; + Moves: Natural := 0; + +begin + -- choose random Target and start ("Current") matrices + Boolean_Rand.Reset(Gen); + Target := Rand_Mat; + loop + Current := Rand_Mat(Target); + exit when Current /= Target; + end loop; + Print("Target:", Target); + + -- print and modify Current matrix, until it is identical to Target + while Current /= Target loop + Moves := Moves + 1; + Print("Current move #" & Natural'Image(Moves), Current); + Ada.Text_IO.Put_Line("Flip row 1 .." & Positive'Image(Last_Row) & + " or column 'a' .. '" & Last_Col & "'"); + declare + S: String := Ada.Text_IO.Get_Line; + function Let(S: String) return Character is (S(S'First)); + function Val(Str: String) return Positive is (Positive'Value(Str)); + begin + if Let(S) in 'a' .. Last_Col then + for I in Current'Range(2) loop + Current(Let(S), I) := not Current(Let(S), I); + end loop; + else + for I in Current'Range(1) loop + Current(I, Val(S)) := not Current(I, Val(S)); + end loop; + end if; + end; + end loop; + + -- summarize the outcome + Ada.Text_IO.Put_Line("Done after" & Natural'Image(Moves) & " Moves."); +end Flip_Bits; diff --git a/Task/Flipping-bits-game/AutoHotkey/flipping-bits-game.ahk b/Task/Flipping-bits-game/AutoHotkey/flipping-bits-game.ahk new file mode 100644 index 0000000000..daa08ff47b --- /dev/null +++ b/Task/Flipping-bits-game/AutoHotkey/flipping-bits-game.ahk @@ -0,0 +1,83 @@ +size := 3 ; max 26 +Gui, Add, Button, , O +Loop, %size% +{ + x := chr(A_Index+64) + If x = A + Loop, %size% + Gui, Add, Button, y+4 gFlip, % A_Index + Gui, Add, Button, ym gFlip, % x + Loop, %size% + { + y := A_Index + Random, %x%%y%, 0, 1 + Gui, Add, Edit, v%x%%y% ReadOnly, % %x%%y% + } +} +Gui, Add, Text, ym, Moves:`nTarget: +Loop, %size% +{ + x := chr(A_Index+64) + Loop, %size% + { + y := A_Index + Gui, Add, Edit, % y=1 ? x="A" ? "xp+0 ym+30" : "x+14 ym+30" : "" . "ReadOnly vt" x y, % t%x%%y% := %x%%y% + } +}Gui, Add, Text, xp-18 ym w30 Right vMoves, % Moves:=1 + +; randomize +While (i < size) +{ + Random, z, 1, %size% + Random, x, 0, 1 + z := x ? chr(z+64) : z + Solution .= z ; to cheat + If Flip(z, size) + i := 0 ; ensure we are not at the solution + Else + i++ ; count +} +Gui, Show, NA +Return + +Flip(z, size) { + Loop, %size% + { + If z is alpha + GuiControl, , %z%%A_Index%, % %z%%A_Index% := !%z%%A_Index% + Else + { + AIndex := chr(A_Index+64) + GuiControl, , %AIndex%%z%, % %AIndex%%z% := !%AIndex%%z% + } + } + Loop, %size% + { + x := chr(A_Index+64) + Loop, %size% + { + y := A_Index + If (%x%%y% != t%x%%y%) + Return 0 + } + } + Return 1 +} + +Flip: + GuiControl, , Moves, % Moves++ + If Flip(A_GuiControl, size) + { + Msgbox Success in %Moves% moves! + Reload + } +Return + +ButtonO: + Reload +Return + +GuiEscape: +GuiClose: + ExitApp +Return diff --git a/Task/Flipping-bits-game/C++/flipping-bits-game.cpp b/Task/Flipping-bits-game/C++/flipping-bits-game.cpp new file mode 100644 index 0000000000..4bbc3225b4 --- /dev/null +++ b/Task/Flipping-bits-game/C++/flipping-bits-game.cpp @@ -0,0 +1,92 @@ +#include +#include +#include + +typedef unsigned char byte; +using namespace std; + +class flip +{ +public: + flip() { field = 0; target = 0; } + void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } + +private: + void gameLoop() + { + int moves = 0; + while( !solved() ) + { + display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; + for( string::iterator i = r.begin(); i != r.end(); i++ ) + { + byte ii = ( *i ); + if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } + else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } + } + } + cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; + } + + void display() + { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } + + void output( string t, byte* f ) + { + cout << t << endl; + cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast( x + '1' ); cout << endl; + for( int y = 0; y < hei; y++ ) + { + cout << static_cast( y + 'a' ) << " "; + for( int x = 0; x < wid; x++ ) + cout << static_cast( f[x + y * wid] + 48 ) << " "; + cout << endl; + } + cout << endl << endl; + } + + bool solved() + { + for( int y = 0; y < hei; y++ ) + for( int x = 0; x < wid; x++ ) + if( target[x + y * wid] != field[x + y * wid] ) return false; + return true; + } + + void createTarget() + { + for( int y = 0; y < hei; y++ ) + for( int x = 0; x < wid; x++ ) + if( frnd() < .5f ) target[x + y * wid] = 1; + else target[x + y * wid] = 0; + memcpy( field, target, wid * hei ); + } + + void flipCol( int c ) + { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } + + void flipRow( int r ) + { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } + + void calcStartPos() + { + int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; + for( int x = 0; x < flips; x++ ) + { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } + } + + void createField() + { + if( field ){ delete [] field; delete [] target; } + int t = wid * hei; field = new byte[t]; target = new byte[t]; + memset( field, 0, t ); memset( target, 0, t ); createTarget(); + while( true ) { calcStartPos(); if( !solved() ) break; } + } + + float frnd() { return static_cast( rand() ) / static_cast( RAND_MAX ); } + + byte* field, *target; int wid, hei; +}; + +int main( int argc, char* argv[] ) +{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); } diff --git a/Task/Flipping-bits-game/C/flipping-bits-game.c b/Task/Flipping-bits-game/C/flipping-bits-game.c new file mode 100644 index 0000000000..43195432da --- /dev/null +++ b/Task/Flipping-bits-game/C/flipping-bits-game.c @@ -0,0 +1,115 @@ +#include +#include + +int i, j; + +void fliprow(int **b, int sz, int n) +{ + for(i = 0; i < sz; i++) + b[n+1][i] = !b[n+1][i]; +} + +void flipcol(int **b, int sz, int n) +{ + for(i = 1; i <= sz; i++) + b[i][n] = !b[i][n]; +} + +void initt(int **t, int sz) +{ + for(i = 1; i <= sz; i++) + for(j = 0; j < sz; j++) + t[i][j] = rand()%2; +} + +void initb(int **t, int **b, int sz) +{ + for(i = 1; i <= sz; i++) + for(j = 0; j < sz; j++) + b[i][j] = t[i][j]; + + for(i = 1; i <= sz; i++) + fliprow(b, sz, rand()%sz+1); + for(i = 0; i < sz; i++) + flipcol(b, sz, rand()%sz); +} + +void printb(int **b, int sz) +{ + printf(" "); + for(i = 0; i < sz; i++) + printf(" %d", i); + printf("\n"); + + for(i = 1; i <= sz; i++) + { + printf("%d", i-1); + for(j = 0; j < sz; j++) + printf(" %d", b[i][j]); + printf("\n"); + } + + printf("\n"); +} + +int eq(int **t, int **b, int sz) +{ + for(i = 1; i <= sz; i++) + for(j = 0; j < sz; j++) + if(b[i][j] != t[i][j]) + return 0; + return 1; +} + +void main() +{ + int sz = 3; + int eql = 0; + int mov = 0; + int **t = malloc(sz*(sizeof(int)+1)); + for(i = 1; i <= sz; i++) + t[i] = malloc(sz*sizeof(int)); + + int **b = malloc(sz*(sizeof(int)+1)); + for(i = 1; i <= sz; i++) + b[i] = malloc(sz*sizeof(int)); + char roc; + int n; + initt(t, sz); + initb(t, b, sz); + + while(eq(t, b, sz)) + initb(t, b, sz); + + while(!eql) + { + printf("Target: \n"); + printb(t, sz); + printf("Board: \n"); + printb(b, sz); + printf("What to flip: "); + scanf(" %c", &roc); + scanf(" %d", &n); + + switch(roc) + { + case 'r': + fliprow(b, sz, n); + break; + case 'c': + flipcol(b, sz, n); + break; + default: + perror("Please specify r or c and an number"); + break; + } + + printf("Moves Taken: %d\n", ++mov); + + if(eq(t, b, sz)) + { + printf("You win!\n"); + eql = 1; + } + } +} diff --git a/Task/Flipping-bits-game/D/flipping-bits-game.d b/Task/Flipping-bits-game/D/flipping-bits-game.d new file mode 100644 index 0000000000..f4db439296 --- /dev/null +++ b/Task/Flipping-bits-game/D/flipping-bits-game.d @@ -0,0 +1,70 @@ +import std.stdio, std.random, std.ascii, std.string, std.range, + std.algorithm, std.conv; + +enum N = 3; // Board side. +static assert(N <= lowercase.length); +enum columnIDs = lowercase[0 .. N]; +alias Board = ubyte[N][N]; + +void flipBits(ref Board board, in size_t count=1) { + foreach (immutable _; 0 .. count) + board[uniform(0, $)][uniform(0, $)] ^= 1; +} + +void notRow(ref Board board, in size_t i) pure nothrow { + board[i][] ^= 1; +} + +void notColumn(ref Board board, in size_t i) pure nothrow { + foreach (ref row; board) + row[i] ^= 1; +} + +Board generateGameBoard(in ref Board target) { + // board is generated with many flips, to keep parity unchanged. + Board board = target; + while (board == target) + foreach (immutable _; 0 .. 2 * N) + [¬Row, ¬Column][uniform(0, 2)](board, uniform(0, N)); + return board; +} + +void show(in ref Board board, in string comment) { + comment.writeln; + writefln(" %-(%c %)", columnIDs); + foreach (immutable j, const row; board) + writefln(" %2d %-(%d %)", j + 1, row); +} + +void main() { + "T prints the target, and Q exits.\n".writeln; + // Create target and flip some of its bits randomly. + Board target; + flipBits(target, uniform(0, N) + 1); + show(target, "Target configuration is:"); + + auto board = generateGameBoard(target); + immutable prompt = format(" 1-%d / %s-%s to flip, or T, Q: ", + N, columnIDs[0], columnIDs.back); + uint move = 1; + while (board != target) { + show(board, format("\nMove %d:", move)); + prompt.write; + immutable ans = readln.strip; + + if (ans.length == 1 && columnIDs.canFind(ans)) { + board.notColumn(columnIDs.countUntil(ans)); + move++; + } else if (iota(1, N + 1).map!text.canFind(ans)) { + board.notRow(ans.to!uint - 1); + move++; + } else if (ans == "T") { + show(target, "Target configuration is:"); + } else if (ans == "Q") { + return "Game stopped.".writeln; + } else + writefln(" Wrong input '%s'. Try again.\n", ans.take(9)); + } + + "\nWell done!".writeln; +} diff --git a/Task/Flipping-bits-game/Fortran/flipping-bits-game.f b/Task/Flipping-bits-game/Fortran/flipping-bits-game.f new file mode 100644 index 0000000000..c9cef99fc9 --- /dev/null +++ b/Task/Flipping-bits-game/Fortran/flipping-bits-game.f @@ -0,0 +1,197 @@ +!Implemented by Anant Dixit (October 2014) +program flipping_bits +implicit none +character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)" +integer :: N, i, j, io, seed(8), moves, input +logical, allocatable :: Brd(:,:), Trgt(:,:) +logical :: solved +double precision :: r + +do + write(*,*) 'Enter the number of squares (between 1 and 10) you would like: ' + read(*,*,iostat=io) N + if(N.gt.0 .and. N.le.10 .and. io.eq.0) exit + write(*,*) 'Please, an integer between 1 and 10' +end do + +allocate(Brd(N,N),Trgt(N,N)) +call date_and_time(values=seed) +call srand(1000*seed(7)+seed(8)+60000*seed(6)) +do i = 1,N + do j = 1,N + r = rand() + if(r.gt.0.5D0) then + Brd(i,j) = .TRUE. + Trgt(i,j) = .TRUE. + else + Brd(i,j) = .FALSE. + Trgt(i,j) = .FALSE. + end if + end do +end do +! Random moves taken by the program to `create' a target +moves = N +do i = 1,moves + r = 1+2.0D0*dble(N)*rand() - 1.0D-17 !Only to make sure that the number is between 1 and 2N (less than 2N-1) + if(floor(r).le.N) then + do j = 1,N + Trgt(floor(r),j) = .NOT.Trgt(floor(r),j) + end do + else + r = r-N + do j = 1,N + Trgt(j,floor(r)) = .NOT.Trgt(j,floor(r)) + end do + end if +end do + +!This part checks if the target and the starting configurations are same or not. +do + input = N + call next_move(Brd,Trgt,N,input,solved) + call next_move(Brd,Trgt,N,input,solved) + if(solved) then + r = 1+2.0D0*dble(N)*rand() - 1.0D-17 + if(floor(r).le.N) then + do j = 1,N + Trgt(floor(r),j) = .NOT.Trgt(floor(r),j) + end do + else + r = r-N + do j = 1,N + Trgt(j,floor(r)) = .NOT.Trgt(j,floor(r)) + end do + end if + else + exit + end if +end do + +write(*,*) 'Welcome to the Flipping Bits game!' +write(*,*) 'You have the current position' + +moves = 0 +call display(Brd,Trgt,N) +input = N +do + write(*,*) 'Number of moves so far:', moves + write(*,*) 'Select the column or row you wish to flip: ' + read(*,*,iostat=io) input + if(io.eq.0 .and. input.gt.0 .and. input.le.(2*N)) then + moves = moves+1 + write(*,*) 'Flipping ', input + call next_move(Brd,Trgt,N,input,solved) + call display(Brd,Trgt,N) + if(solved) exit + else + write(*,*) 'Please enter a valid column or row number. To quit, press Ctrl+C!' + end if +end do + +write(*,*) 'Congratulations! You finished the game!' +write(*,ifmt,advance='no') moves +write(*,*) ' moves were taken by you!!' +deallocate(Brd,Trgt) +end program + +subroutine display(Brd,Trgt,N) +implicit none +!arguments +integer :: N +logical :: Brd(N,N), Trgt(N,N) +!local +character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)" +integer :: i, j +write(*,*) 'Current Configuration: ' +do i = 0,N + if(i.eq.0) then + write(*,cfmt,advance='no') 'R/C' + write(*,cfmt,advance='no') ' | ' + else + write(*,ifmt,advance='no') i + end if +end do +write(*,*) +do i = 0,N + if(i.eq.0) then + do j = 0,N+2 + write(*,cfmt,advance='no') '---' + end do + else + write(*,ifmt,advance='no') i+N + write(*,cfmt,advance='no') ' | ' + do j = 1,N + if(Brd(i,j)) then + write(*,ifmt,advance='no') 1 + else + write(*,ifmt,advance='no') 0 + end if + end do + end if + write(*,*) +end do + +write(*,*) +write(*,*) + +write(*,*) 'Target Configuration' +do i = 0,N + if(i.eq.0) then + write(*,cfmt,advance='no') 'R/C' + write(*,cfmt,advance='no') ' | ' + else + write(*,ifmt,advance='no') i + end if +end do +write(*,*) +do i = 0,N + if(i.eq.0) then + do j = 0,N+2 + write(*,cfmt,advance='no') '---' + end do + else + write(*,ifmt,advance='no') i+N + write(*,cfmt,advance='no') ' | ' + do j = 1,N + if(Trgt(i,j)) then + write(*,ifmt,advance='no') 1 + else + write(*,ifmt,advance='no') 0 + end if + end do + end if + write(*,*) +end do +write(*,*) +write(*,*) +end subroutine + +subroutine next_move(Brd,Trgt,N,input,solved) +implicit none +!arguments +integer :: N, input +logical :: Brd(N,N), Trgt(N,N), solved +!others +integer :: i,j + +if(input.gt.N) then + input = input-N + do i = 1,N + Brd(input,i) = .not.Brd(input,i) + end do +else + do i = 1,N + Brd(i,input) = .not.Brd(i,input) + end do +end if +solved = .TRUE. +do i = 1,N + do j = 1,N + if( (.not.Brd(i,j).and.Trgt(i,j)) .or. (Brd(i,j).and..not.Trgt(i,j)) ) then + solved = .FALSE. + exit + end if + end do + if(.not.solved) exit +end do +end subroutine diff --git a/Task/Flipping-bits-game/Go/flipping-bits-game.go b/Task/Flipping-bits-game/Go/flipping-bits-game.go new file mode 100644 index 0000000000..ced2235d10 --- /dev/null +++ b/Task/Flipping-bits-game/Go/flipping-bits-game.go @@ -0,0 +1,122 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + + rand.Seed(time.Now().UnixNano()) + + var n int = 3 // Change to define board size + var moves int = 0 + + a := make([][]int, n) + for i := range a { + a[i] = make([]int, n) + for j := range a { + a[i][j] = rand.Intn(2) + } + } + + b := make([][]int, len(a)) + for i := range a { + b[i] = make([]int, len(a[i])) + copy(b[i], a[i]) + } + + for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { + b = flipCol(b, rand.Intn(n) + 1) + b = flipRow(b, rand.Intn(n) + 1) + } + + fmt.Println("Target:") + drawBoard(a) + fmt.Println("\nBoard:") + drawBoard(b) + + var rc rune + var num int + + for { + for{ + fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) + _, err := fmt.Scanf("%c%d", &rc, &num) + if err != nil { + fmt.Println(err) + continue + } + if num < 1 || num > n { + fmt.Println("Wrong command!") + continue + } + break + } + + switch rc { + case 'c': + fmt.Printf("Column %v will be flipped\n", num) + flipCol(b, num) + case 'r': + fmt.Printf("Row %v will be flipped\n", num) + flipRow(b, num) + default: + fmt.Println("Wrong command!") + continue + } + + moves++ + fmt.Println("\nMoves taken: ", moves) + + fmt.Println("Target:") + drawBoard(a) + fmt.Println("\nBoard:") + drawBoard(b) + + if compareSlices(a, b) { + fmt.Printf("Finished. You win with %d moves!\n", moves) + break + } + } +} + +func drawBoard (m [][]int) { + fmt.Print(" ") + for i := range m { + fmt.Printf("%d ", i+1) + } + for i := range m { + fmt.Println() + fmt.Printf("%d ", i+1) + for _, val := range m[i] { + fmt.Printf(" %d", val) + } + } + fmt.Print("\n") +} + +func flipRow(m [][]int, row int) ([][]int) { + for j := range m { + m[row-1][j] ^= 1 + } + return m +} + +func flipCol(m [][]int, col int) ([][]int) { + for j := range m { + m[j][col-1] ^= 1 + } + return m +} + +func compareSlices(m [][]int, n[][]int) bool { + o := true + for i := range m { + for j := range m { + if m[i][j] != n[i][j] { o = false } + } + } + return o +} diff --git a/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs b/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs new file mode 100644 index 0000000000..382accf1d3 --- /dev/null +++ b/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs @@ -0,0 +1,94 @@ +import Data.Array +import Data.List +import Control.Monad +import System.Random + +type Board = Array (Char, Char) Int + +flp :: Int -> Int +flp 0 = 1 +flp 1 = 0 + +numRows, numCols :: Board -> [Char] +numRows t = let ((a, _), (b, _)) = bounds t in [a .. b] + +numCols t = let ((_, a), (_, b)) = bounds t in [a .. b] + +flipRow, flipCol :: Board -> Char -> Board +flipRow t r = let e = [ (ix, flp (t ! ix)) | ix <- + zip (repeat r) (numCols t) ] + in t // e + +flipCol t c = let e = [ (ix, flp (t ! ix)) | ix <- + zip (numRows t) (repeat c) ] + in t // e + +printBoard :: Board -> IO () +printBoard t = do + let rows = numRows t + cols = numCols t + f 0 = '0' + f 1 = '1' + p r xs = putStrLn $ [r, ' '] ++ intersperse ' ' (map f xs) + putStrLn $ " " ++ intersperse ' ' cols + zipWithM_ p rows [ [ t ! (y, x) | x <- cols ] | y <- rows ] + +-- create a random goal board, and flip rows and columns randomly +-- to get a starting board +setupGame :: Char -> Char -> IO (Board, Board) +setupGame sizey sizex = do + -- random cell value at (row, col) + let mk rc = fmap (\v -> (rc, v)) $ randomRIO (0, 1) + rows = ['a' .. sizey] + cols = ['1' .. sizex] + goal <- fmap (array (('a', '1'), (sizey, sizex))) $ + mapM mk [ (r, c) | r <- rows, c <- cols ] + start <- do + let change :: Board -> Int -> IO Board + -- flip random row + change t 0 = fmap (flipRow t) $ randomRIO ('a', sizey) + -- flip random col + change t 1 = fmap (flipCol t) $ randomRIO ('1', sizex) + numMoves <- randomRIO (3, 15) -- how many flips (3 - 15) + -- determine if rows or cols are flipped + moves <- replicateM numMoves $ randomRIO (0, 1) + -- make changes and get a starting board + foldM change goal moves + if goal /= start -- check if boards are different + then return (goal, start) -- all ok, return both boards + else setupGame sizey sizex -- try again + +main :: IO () +main = do + putStrLn "Select a board size (1 - 9).\nPress any other key to exit." + sizec <- getChar + when (sizec `elem` ['1' .. '9']) $ do + let size = read [sizec] - 1 + (g, s) <- setupGame (['a'..] !! size) (['1'..] !! size) + turns g s 0 + + where + turns goal current moves = do + putStrLn "\nGoal:" + printBoard goal + putStrLn "\nBoard:" + printBoard current + when (moves > 0) $ + putStrLn $ "\nYou've made " ++ show moves ++ " moves so far." + putStrLn $ "\nFlip a row (" ++ numRows current ++ + ") or a column (" ++ numCols current ++ ")" + v <- getChar + if v `elem` numRows current + then check $ flipRow current v + else if v `elem` numCols current + then check $ flipCol current v + else tryAgain + + where check t = if t == goal + then putStrLn $ "\nYou've won in " ++ + show (moves + 1) ++ " moves!" + else turns goal t (moves + 1) + + tryAgain = do + putStrLn ": Invalid row or column." + turns goal current moves diff --git a/Task/Flipping-bits-game/J/flipping-bits-game-1.j b/Task/Flipping-bits-game/J/flipping-bits-game-1.j new file mode 100644 index 0000000000..81cc6d7ef9 --- /dev/null +++ b/Task/Flipping-bits-game/J/flipping-bits-game-1.j @@ -0,0 +1,21 @@ +start=:3 :0 + Moves=:0 + N=:i.y + Board=: ?2$~,~y + 'fr fc'=. (2,y)$}.#:(+?&.<:@<:)2x^2*y + End=: fr~:fc~:"1 Board + Board;End +) + +abc=:'abcdefghij' +move=:3 :0 + fc=. N e.abc i. y ([-.-.)abc + fr=. N e._-.~_ "."0 abc-.~":y + Board=: fr~:fc~:"1 Board + smoutput (":Moves=:Moves++/fr,fc),' moves' + if. Board-:End do. + 'yes' + else. + Board;End + end. +) diff --git a/Task/Flipping-bits-game/J/flipping-bits-game-2.j b/Task/Flipping-bits-game/J/flipping-bits-game-2.j new file mode 100644 index 0000000000..086f47d639 --- /dev/null +++ b/Task/Flipping-bits-game/J/flipping-bits-game-2.j @@ -0,0 +1,16 @@ + start 3 +┌─────┬─────┐ +│1 1 1│1 0 1│ +│1 1 0│0 1 1│ +│1 0 0│0 0 1│ +└─────┴─────┘ + move 'b2' +2 moves +┌─────┬─────┐ +│1 0 1│1 0 1│ +│1 0 0│0 1 1│ +│0 0 1│0 0 1│ +└─────┴─────┘ + move '1' +3 moves +yes diff --git a/Task/Flipping-bits-game/MATLAB/flipping-bits-game.m b/Task/Flipping-bits-game/MATLAB/flipping-bits-game.m new file mode 100644 index 0000000000..23c76a9b22 --- /dev/null +++ b/Task/Flipping-bits-game/MATLAB/flipping-bits-game.m @@ -0,0 +1,87 @@ +function FlippingBitsGame(n) +% Play the flipping bits game on an n x n array + + % Generate random target array + fprintf('Welcome to the Flipping Bits Game!\n') + if nargin < 1 + n = input('What dimension array should we use? '); + end + Tar = logical(randi([0 1], n)); + + % Generate starting array by randomly flipping rows or columns + Cur = Tar; + while all(Cur(:) == Tar(:)) + nFlips = randi([3*n max(10*n, 100)]); + randDim = randi([0 1], nFlips, 1); + randIdx = randi([1 n], nFlips, 1); + for k = 1:nFlips + if randDim(k) + Cur(randIdx(k), :) = ~Cur(randIdx(k), :); + else + Cur(:, randIdx(k)) = ~Cur(:, randIdx(k)); + end + end + end + + % Print rules + fprintf('Given a %d x %d logical array,\n', n, n) + fprintf('and a target array configuration,\n') + fprintf('attempt to transform the array to the target\n') + fprintf('by inverting the bits in a whole row or column\n') + fprintf('at once in as few moves as possible.\n') + fprintf('Enter the corresponding letter to invert a column,\n') + fprintf('or the corresponding number to invert a row.\n') + fprintf('0 will reprint the target array, and no entry quits.\n\n') + fprintf('Target:\n') + PrintArray(Tar) + + % Play until player wins or quits + move = true; + nMoves = 0; + while ~isempty(move) && any(Cur(:) ~= Tar(:)) + fprintf('Move %d:\n', nMoves) + PrintArray(Cur) + move = lower(input('Enter move: ', 's')); + if length(move) > 1 + fprintf('Invalid move, try again\n') + elseif move + r = str2double(move); + if isnan(r) + c = move-96; + if c > n || c < 1 + fprintf('Invalid move, try again\n') + else + Cur(:, c) = ~Cur(:, c); + nMoves = nMoves+1; + end + else + if r > n || r < 0 + fprintf('Invalid move, try again\n') + elseif r == 0 + fprintf('Target:\n') + PrintArray(Tar) + else + Cur(r, :) = ~Cur(r, :); + nMoves = nMoves+1; + end + end + end + end + + if all(Cur(:) == Tar(:)) + fprintf('You win in %d moves! Try not to flip out!\n', nMoves) + else + fprintf('Quitting? The challenge a bit much for you?\n') + end +end + +function PrintArray(A) + [nRows, nCols] = size(A); + fprintf(' ') + fprintf(' %c', (1:nCols)+96) + fprintf('\n') + for r = 1:nRows + fprintf('%8d%s\n', r, sprintf(' %d', A(r, :))) + end + fprintf('\n') +end diff --git a/Task/Flipping-bits-game/PL-I/flipping-bits-game.pli b/Task/Flipping-bits-game/PL-I/flipping-bits-game.pli new file mode 100644 index 0000000000..82838bf9bf --- /dev/null +++ b/Task/Flipping-bits-game/PL-I/flipping-bits-game.pli @@ -0,0 +1,49 @@ +(subscriptrange, stringrange, stringsize): +flip: procedure options (main); + declare n fixed binary; + + put skip list ('This is the bit-flipping game. What size of board do you want?'); + get list (n); + put skip list + ('Your task is to change your board so as match the board on the right (the objective)'); + + begin; + declare initial(n,n) bit (1), objective(n,n) bit (1); + declare (i, j, k, move) fixed binary; + declare ch character(1); + declare alphabet character (26) initial ('abcdefghijklmnopqrstuvwxyz'); + + on subrg + begin; put skip list ('Your row or column ' || trim(ch) || ' is out of range'); stop; end; + + initial, objective = iand(random()*99, 1) = 1; + + /* Set up the objective array: */ + do i = 1 to n-1; + j = random()*n+1; objective(j,*) = ^objective(j,*); + j = random()*n+1; objective(*,j) = ^objective(*,j); + end; + + do move = 0 by 1; + put skip edit ( center('You', n*3), center('The objective', 3*n+4) ) (x(3), a); + put skip edit ( (substr(alphabet, i, 1) do i = 1 to n) ) (x(5), (n) a(3)); + put edit ( (substr(alphabet, i, 1) do i = 1 to n) ) (x(3), (n) a(3)); + do i = 1 to n; + put skip edit (i, initial(i,*), objective(i,*)) ((n+1) f(3), x(3), (n) F(3)); + end; + + if all(initial = objective) then leave; + + put skip(2) list + ('Please type a row number or column letter whose bits you want to flip: '); + get edit (ch) (L); put edit (ch) (a); + k = index(alphabet, ch); + if k > 0 then + initial(*, k) = ^initial(*,k); /* Flip column k */ + else + initial(ch,*) = ^initial(ch,*); /* Flip row ch */ + end; + put skip(2) list ('Congratulations. You solved it in ' || trim(move) || ' moves.'); + end; + +end flip; diff --git a/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 b/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 new file mode 100644 index 0000000000..25463da7f6 --- /dev/null +++ b/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 @@ -0,0 +1,54 @@ +sub MAIN ($square = 4) { + say "{$square}? Seriously?" and exit if $square < 1 or $square > 26; + my %bits = map { $_ => %( map { $_ => 0 }, ('A' .. *)[^ $square] ) }, + (1 .. *)[^ $square]; + scramble %bits; + my $target = build %bits; + scramble %bits until build(%bits) ne $target; + display($target, %bits); + my $turns = 0; + while my $flip = prompt "Turn {++$turns}: Flip which row / column? " { + flip $flip.match(/\w/).uc, %bits; + if display($target, %bits) { + say "Hurray! You solved it in $turns turns."; + last; + } + } +} + +sub display($goal, %hash) { + shell('clear'); + say "Goal\n$goal\nYou"; + my $this = build %hash; + say $this; + return ($goal eq $this); +} + +sub flip ($a, %hash) { + given $a { + when any(keys %hash) { + %hash{$a}{$_} = %hash{$a}{$_} +^ 1 for %hash{$a}.keys + }; + when any(keys %hash{'1'}) { + %hash{$_}{$a} = %hash{$_}{$a} +^ 1 for %hash.keys + }; + } +} + +sub build (%hash) { + my $string = ' '; + $string ~= sprintf "%2s ", $_ for sort keys %hash{'1'}; + $string ~= "\n"; + for sort keys %hash -> $key { + $string ~= sprintf "%2s ", $key; + $string ~= sprintf "%2s ", %hash{$key}{$_} for sort keys %hash{$key}; + $string ~= "\n"; + }; + $string +} + +sub scramble(%hash) { + my @keys = keys %hash; + @keys ,= keys %hash{'1'}; + flip $_, %hash for @keys.pick( @keys/2 ); +} diff --git a/Task/Flipping-bits-game/Perl/flipping-bits-game.pl b/Task/Flipping-bits-game/Perl/flipping-bits-game.pl new file mode 100644 index 0000000000..926c516197 --- /dev/null +++ b/Task/Flipping-bits-game/Perl/flipping-bits-game.pl @@ -0,0 +1,76 @@ +#!perl +use strict; +use warnings qw(FATAL all); + +my $n = shift(@ARGV) || 4; +if( $n < 2 or $n > 26 ) { + die "You can't play a size $n game\n"; +} + +my $n2 = $n*$n; + +my (@rows, @cols); +for my $i ( 0 .. $n-1 ) { + my $row = my $col = "\x00" x $n2; + vec($row, $i * $n + $_, 8) ^= 1 for 0 .. $n-1; + vec($col, $i + $_ * $n, 8) ^= 1 for 0 .. $n-1; + push @rows, $row; + push @cols, $col; +} + +my $goal = "0" x $n2; +int(rand(2)) or (vec($goal, $_, 8) ^= 1) for 0 .. $n2-1; +my $start = $goal; +{ + for(@rows, @cols) { + $start ^= $_ if int rand 2; + } + redo if $start eq $goal; +} + +my @letters = ('a'..'z')[0..$n-1]; +sub to_strings { + my $board = shift; + my @result = join(" ", " ", @letters); + for( 0 .. $n-1 ) { + my $res = sprintf("%2d ",$_+1); + $res .= join " ", split //, substr $board, $_*$n, $n; + push @result, $res; + } + \@result; +} + +my $fmt; +my ($stext, $etext) = ("Starting board", "Ending board"); +my $re = join "|", reverse 1 .. $n, @letters; +my $moves_so_far = 0; +while( 1 ) { + my ($from, $to) = (to_strings($start), to_strings($goal)); + unless( $fmt ) { + my $len = length $from->[0]; + $len = length($stext) if $len < length $stext; + $fmt = join($len, "%", "s%", "s\n"); + } + printf $fmt, $stext, $etext; + printf $fmt, $from->[$_], $to->[$_] for 0 .. $n; + last if $start eq $goal; + INPUT_LOOP: { + printf "Move #%s: Type one or more row numbers and/or column letters: ", + $moves_so_far+1; + my $input = <>; + die unless defined $input; + my $did_one; + for( $input =~ /($re)/gi ) { + $did_one = 1; + if( /\d/ ) { + $start ^= $rows[$_-1]; + } else { + $_ = ord(lc) - ord('a'); + $start ^= $cols[$_]; + } + ++$moves_so_far; + } + redo INPUT_LOOP unless $did_one; + } +} +print "You won after $moves_so_far moves.\n"; diff --git a/Task/Flipping-bits-game/Python/flipping-bits-game.py b/Task/Flipping-bits-game/Python/flipping-bits-game.py new file mode 100644 index 0000000000..8c0a9ac9c4 --- /dev/null +++ b/Task/Flipping-bits-game/Python/flipping-bits-game.py @@ -0,0 +1,85 @@ +""" +Given a %i by %i sqare array of zeroes or ones in an initial +configuration, and a target configuration of zeroes and ones +The task is to transform one to the other in as few moves as +possible by inverting whole numbered rows or whole lettered +columns at once. +In an inversion any 1 becomes 0 and any 0 becomes 1 for that +whole row or column. + +""" + +from random import randrange +from copy import deepcopy +from string import ascii_lowercase + + +try: # 2to3 fix + input = raw_input +except: + pass + +N = 3 # N x N Square arrray + +board = [[0]* N for i in range(N)] + +def setbits(board, count=1): + for i in range(count): + board[randrange(N)][randrange(N)] ^= 1 + +def shuffle(board, count=1): + for i in range(count): + if randrange(0, 2): + fliprow(randrange(N)) + else: + flipcol(randrange(N)) + + +def pr(board, comment=''): + print(str(comment)) + print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) + print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) + for j, line in enumerate(board, 1))) + +def init(board): + setbits(board, count=randrange(N)+1) + target = deepcopy(board) + while board == target: + shuffle(board, count=2 * N) + prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], + ascii_lowercase[N-1]) + return target, prompt + +def fliprow(i): + board[i-1][:] = [x ^ 1 for x in board[i-1] ] + +def flipcol(i): + for row in board: + row[i] ^= 1 + +if __name__ == '__main__': + print(__doc__ % (N, N)) + target, prompt = init(board) + pr(target, 'Target configuration is:') + print('') + turns = 0 + while board != target: + turns += 1 + pr(board, '%i:' % turns) + ans = input(prompt).strip() + if (len(ans) == 1 + and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): + flipcol(ascii_lowercase.index(ans)) + elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: + fliprow(int(ans)) + elif ans == 'T': + pr(target, 'Target configuration is:') + turns -= 1 + elif ans == 'X': + break + else: + print(" I don't understand %r... Try again. " + "(X to exit or T to show target)\n" % ans[:9]) + turns -= 1 + else: + print('\nWell done!\nBye.') diff --git a/Task/Flipping-bits-game/README b/Task/Flipping-bits-game/README new file mode 100644 index 0000000000..36d3622512 --- /dev/null +++ b/Task/Flipping-bits-game/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Flipping_bits_game diff --git a/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx new file mode 100644 index 0000000000..2859ae6731 --- /dev/null +++ b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx @@ -0,0 +1,86 @@ +/*REXX program presents a "flipping bit" puzzle, user can solve via C.L.*/ +parse arg N u on off . /*get optional arguments. */ +if N=='' | N==',' then N=3 /*Size given? Then use default.*/ +if u=='' | u==',' then u=N /*number of bits initialized ON.*/ +if on =='' then on =1 /*character used for "on". */ +if off=='' then off=0 /*character used for "off". */ +col@='a b c d e f g h i j k l m n o p q r s t u v w x y z' /*for col id.*/ +cols=space(col@,0); upper cols /*letters to be used for columns.*/ +@.=off; !.=off /*set both arrays to "off" chars.*/ +tries=0 /*# of player's attempts used. */ + do while show(0) < u /* [↓] turn "on" U bits.*/ + r=random(1,N); c=random(1,N) /*get a random row and column.*/ + @.r.c=on ; !.r.c=on /*set (both) row & column to ON*/ + end /*while*/ /* [↑] keep going 'til U bits set*/ +oz=z /*keep the original array string.*/ +call show 1, ' ◄───target' /*show target for user to attain.*/ + + do random(1,2); call flip 'R',random(1,N) /*flip a row of bits*/ + call flip 'C',random(1,N) /* " " col " " */ + end /*random···*/ /* [↑] 1 or 2 times*/ + +if z==oz then call flip 'R',random(1,N) /*ensure it's not the target.*/ + + do until z==oz /*prompt until they get it right.*/ + call prompt /*get a row or column # from C.L.*/ + call flip left(?,1),substr(?,2) /*flip a user selected row or col*/ + call show 0 /*get image (Z) of updated array.*/ + end /*until···*/ + +call show 1, ' ◄───your array' /*display the array to the screen*/ +say '─────────Congrats! You did it in' tries "tries." +exit tries /*stick a fork in it, we're done.*/ +/*──────────────────────────────────FLIP subroutine────────────────────────*/ +flip: parse arg x,# /*X is R or C, # is which one.*/ + do c=1 for N while x=='R'; if @.#.c==on then @.#.c=off; else @.#.c=on; end + do r=1 for N while x=='C'; if @.r.#==on then @.r.#=off; else @.r.#=on; end +return /* [↑] the bits can be ON or OFF*/ +/*──────────────────────────────────PROMPTER subroutine─────────────────*/ +prompt: if tries\==0 then say '─────────bit array after play: ' tries +signal on halt /*another way for player to quit.*/ +!='─────────Please enter a row number or column letter, or Quit:' +call show 1, ' ◄───your array' /*display the array to the screen*/ + + do forever; ok=1; say; say !; pull ? _ . 1 all /*prompt & get ans*/ + if abbrev('QUIT',?,1) then do; say 'quitting···'; exit 0; end + if ?=='' then do; call show 1,' ◄───target',.; ok=0 + call show 1,' ◄───your array' + end /* [↑] reshow targ*/ + if _\=='' then call terr 'too many args entered:' all + if \isInt(?) & \isLet(?) then call terr 'row/column: ' ? + if isLet(?) then a=pos(?,cols) + if isLet(?) & (a<1 | a>N) then call terr 'column: ' ? + if isLet(?) & length(?)>1 then call terr 'column: ' ? + if isLet(?) then ?='C'pos(?,cols) + if isInt(?) & (?<1 | ?>N) then call terr 'row: ' ? + if isInt(?) then ?=?/1 /*normalize number*/ + if isInt(?) then ?='R'? + if ok then leave /*No errors? Leave*/ + end /*forever*/ /*endeth da checks*/ + +tries=tries+1 /*bump da counter.*/ +return ? /*return response.*/ +/*──────────────────────────────────SHOW subroutine─────────────────────*/ +show: $=0; _=; z=; parse arg tell,tx,o /*$: # of ON bits.*/ +if tell then do /*are we telling? */ + say /*show blank line.*/ + say ' ' subword(col@,1,N) " column letter" + say 'row ╔'copies('═',N+N+1) /*prepend col hdrs*/ + end /* [↑] grid hdrs.*/ + + do r=1 for N /*show grid rows.*/ + do c=1 for N /*build grid cols.*/ + if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$+(!.r.c==on); end + else do; z=z || @.r.c; _=_ @.r.c; $=$+(@.r.c==on); end + end /*c*/ /*··· and sum ONs.*/ + if tx\=='' then tar.r=_ tx /*build da target?*/ + if tell then say right(r,2) ' ║'_ tx; _= /*show the grid? */ + end /*r*/ /*show a grid row.*/ + +if tell then say /*show blank line.*/ +return $ /*$: # of ON bits.*/ +/*──────────────────────────────────one-liner subroutines───────────────*/ +halt: say 'program was halted!'; exit /*the REXX program was halted.*/ +isInt: return datatype(arg(1),'W') /*returns 1 if arg is an int. */ +isLet: return datatype(arg(1),'M') /*returns 1 if arg is a letter*/ +terr: if ok then say '***error!***: illegal' arg(1); ok=0; return diff --git a/Task/Flipping-bits-game/Racket/flipping-bits-game.rkt b/Task/Flipping-bits-game/Racket/flipping-bits-game.rkt new file mode 100644 index 0000000000..43641fb572 --- /dev/null +++ b/Task/Flipping-bits-game/Racket/flipping-bits-game.rkt @@ -0,0 +1,71 @@ +#lang racket +(define (flip-row! pzzl r) + (define N (integer-sqrt (bytes-length pzzl))) + (for* ((c (in-range N))) + (define idx (+ c (* N r))) + (bytes-set! pzzl idx (- 1 (bytes-ref pzzl idx))))) + +(define (flip-col! pzzl c) + (define N (integer-sqrt (bytes-length pzzl))) + (for* ((r (in-range N))) + (define idx (+ c (* N r))) + (bytes-set! pzzl idx (- 1 (bytes-ref pzzl idx))))) + +(define (new-game N (flips 10)) + (define N2 (sqr N)) + (define targ (list->bytes (for/list ((_ N2)) (random 2)))) + (define strt (bytes-copy targ)) + (for ((_ flips)) + (case (random 2) + ((0) (flip-col! strt (random N))) + ((1) (flip-row! strt (random N))))) + (if (equal? strt targ) (new-game N) (values targ strt))) + +(define (show-games #:sep (pzl-sep " | ") . pzzls) + (define N (integer-sqrt (bytes-length (first pzzls)))) + (define caption (string-join (for/list ((c (in-range N))) (~a (add1 c))) "")) + (define ruler (string-join (for/list ((c (in-range N))) "-") "")) + + (define ((pzzle-row r) p) + (string-join (for/list ((c (in-range N))) (~a (bytes-ref p (+ c (* N r))))) "")) + + (displayln + (string-join + (list* + (format " ~a" (string-join (for/list ((_ pzzls)) caption) pzl-sep)) + (format " ~a" (string-join (for/list ((_ pzzls)) ruler) pzl-sep)) + (for/list ((r (in-range N)) (R (in-naturals (char->integer #\a)))) + (format "~a ~a" (integer->char R) (string-join (map (pzzle-row r) pzzls) pzl-sep)))) + "\n"))) + +(define (play N) + (define-values (end start) (new-game N)) + (define (turn n (show? #t)) + (cond + [(equal? end start) (printf "you won on turn #~a~%" n)] + [else + (when show? ;; don't show after whitespace + (printf "turn #~a~%" n) + (show-games start end)) + (match (read-char) + [(? eof-object?) (printf "sad to see you go :-(~%")] + [(? char-whitespace?) (turn n #f)] + [(? char-numeric? c) + (define cnum (- (char->integer c) (char->integer #\1))) + (cond [(< -1 cnum N) + (printf "flipping col ~a~%" (add1 cnum)) + (flip-col! start cnum) + (turn (add1 n))] + [else (printf "column number out of range ~a > ~a~%" (add1 cnum) N) + (turn n)])] + [(? char-lower-case? c) + (define rnum (- (char->integer c) (char->integer #\a))) + (cond [(< -1 rnum N) + (printf "flipping row ~a~%" (add1 rnum)) + (flip-row! start rnum) + (turn (add1 n))] + [else (printf "row number out of range ~a > ~a~%" (add1 rnum) (sub1 N)) + (turn n)])] + [else (printf "unrecognised character in input: ~s~%" else) + (turn n)])])) + (turn 0)) diff --git a/Task/Flipping-bits-game/Ruby/flipping-bits-game.rb b/Task/Flipping-bits-game/Ruby/flipping-bits-game.rb new file mode 100644 index 0000000000..f316f50ee8 --- /dev/null +++ b/Task/Flipping-bits-game/Ruby/flipping-bits-game.rb @@ -0,0 +1,104 @@ +class FlipBoard + def initialize(size) + raise ArgumentError.new("Invalid board size: #{size}") if size < 2 + + @size = size + @board = Array.new(size**2, 0) + + randomize_board + loop do + @target = generate_target + break unless solved? + end + + # these are used for validating user input + @columns = [*'a'...('a'.ord+@size).chr] + @rows = (1..@size).map(&:to_s) + end + + ############################################################ + + def play + moves = 0 + puts "your target:", target + + until solved? + puts "", "move #{moves}:", self + print "Row/column to flip: " + ans = $stdin.gets.strip + + if @columns.include? ans + flip_column @columns.index(ans) + moves += 1 + elsif @rows.include? ans + flip_row @rows.index(ans) + moves += 1 + else + puts "invalid input: " + ans + end + end + + puts "", "you solved the game in #{moves} moves", self + end + + # the target formation as a string + def target + format_array @target + end + + # the current formation as a string + def to_s + format_array @board + end + + ############################################################ + private + + def solved? + @board == @target + end + + # flip a random number of bits on the board + def randomize_board + (@size + rand(@size)).times do + flip_bit rand(@size), rand(@size) + end + end + + # generate a random number of flip_row/flip_column calls + def generate_target + orig_board = @board.clone + (@size + rand(@size)).times do + rand(2).zero? ? flip_row( rand(@size) ) : flip_column( rand(@size) ) + end + target, @board = @board, orig_board + target + end + + def flip_row(row) + @size.times {|col| flip_bit(row, col)} + end + + def flip_column(col) + @size.times {|row| flip_bit(row, col)} + end + + def flip_bit(row, col) + @board[@size * row + col] ^= 1 + end + + def format_array(ary) + str = " " + @columns.join(" ") + "\n" + @size.times do |row| + str << "%2s " % @rows[row] + ary[@size*row, @size].join(" ") + "\n" + end + str + end +end + +###################################################################### +begin + FlipBoard.new(ARGV.shift.to_i).play +rescue => e + puts e.message +end diff --git a/Task/Flipping-bits-game/Tcl/flipping-bits-game.tcl b/Task/Flipping-bits-game/Tcl/flipping-bits-game.tcl new file mode 100644 index 0000000000..2a9f8de701 --- /dev/null +++ b/Task/Flipping-bits-game/Tcl/flipping-bits-game.tcl @@ -0,0 +1,92 @@ +package require Tcl 8.6 + +oo::class create Flip { + variable board target s + constructor {size} { + set s $size + set target [my RandomConfiguration] + set board $target + while {$board eq $target} { + for {set i 0} {$i < $s} {incr i} { + if {rand()<.5} { + my SwapRow $i + } + if {rand()<.5} { + my SwapColumn $i + } + } + } + } + + method RandomConfiguration {{p 0.5}} { + for {set row 0} {$row < $s} {incr row} { + set r {} + for {set col 0} {$col < $s} {incr col} { + lappend r [expr {rand() < $p}] + } + lappend result $r + } + return $result + } + + method SwapRow {rowId} { + for {set i 0} {$i < $s} {incr i} { + lset board $rowId $i [expr {![lindex $board $rowId $i]}] + } + } + method SwapColumn {columnId} { + for {set i 0} {$i < $s} {incr i} { + lset board $i $columnId [expr {![lindex $board $i $columnId]}] + } + } + + method Render {configuration {prefixes {}}} { + join [lmap r $configuration p $prefixes { + format %s%s $p [join [lmap c $r {string index ".X" $c}] ""] + }] "\n" + } + method GetInput {prompt} { + puts -nonewline "${prompt}: " + flush stdout + gets stdin + } + + method play {} { + set p0 {} + set p {} + set top [format "%*s " [string length $s] ""] + for {set i 1;set j 97} {$i<=$s} {incr i;incr j} { + append top [format %c $j] + lappend p [format "%*d " [string length $s] $i] + lappend p0 [format "%*s " [string length $s] ""] + } + + set moves 0 + puts "You are trying to get to:\n[my Render $target $p0]\n" + while true { + puts "Current configuration (#$moves):\n$top\n[my Render $board $p]" + + # Test for if we've won + if {$board eq $target} break + + # Ask the user for a move + set i [my GetInput "Pick a column (letter) or row (number) to flip"] + + # Parse the move and apply it + if {[string is lower -strict $i] && [set c [expr {[scan $i "%c"] - 97}]]<$s} { + my SwapColumn $c + incr moves + } elseif {[string is integer -strict $i] && $i>0 && $i<=$s} { + my SwapRow [expr {$i - 1}] + incr moves + } else { + puts "Error: bad selection" + } + puts "" + } + puts "\nYou win! (You took $moves moves.)" + } +} + +Flip create flip 3 +flip play diff --git a/Task/Fractran/00DESCRIPTION b/Task/Fractran/00DESCRIPTION new file mode 100644 index 0000000000..c12430617c --- /dev/null +++ b/Task/Fractran/00DESCRIPTION @@ -0,0 +1,37 @@ + '''[[wp:FRACTRAN|FRACTRAN]]''' is a Turing-complete esoteric programming language invented by the mathematician [[wp:John Horton Conway|John Horton Conway]]. + +A FRACTRAN program is an ordered list of positive fractions P = (f_1, f_2, \ldots, f_m), together with an initial positive integer input n. + +The program is run by updating the integer n as follows: + +* for the first fraction, f_i, in the list for which nf_i is an integer, replace n with nf_i ; +* repeat this rule until no fraction in the list produces an integer when multiplied by n, then halt. + +Conway gave a program for primes in FRACTRAN: + +: 17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1 + +Starting with n=2, this FRACTRAN program will change n to 15=2\times (15/2), then 825=15\times (55/1), generating the following sequence of integers: + +: 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, \ldots + +After 2, this sequence contains the following powers of 2: + +:2^2=4, 2^3=8, 2^5=32, 2^7=128, 2^{11}=2048, 2^{13}=8192, 2^{17}=131072, 2^{19}=524288, \ldots + +which are the prime powers of 2. + +'''Your task''' is to +write a program that reads a list of fractions in a ''natural'' format from the keyboard or from a string, +to parse it into a sequence of fractions (''i.e.'' two integers), +and runs the FRACTRAN starting from a provided integer, writing the result at each step. +It is also required that the number of step is limited (by a parameter easy to find). + +'''Extra credit:''' Use this program to derive the first 20 or so prime numbers. + +For more on how to program FRACTRAN as a universal programming language, see: +* J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. + +* J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. + +* [http://scienceblogs.com/goodmath/2006/10/27/prime-number-pathology-fractra/Prime Number Pathology: Fractran] by Mark C. Chu-Carroll; October 27, 2006. diff --git a/Task/Fractran/Ada/fractran.ada b/Task/Fractran/Ada/fractran.ada new file mode 100644 index 0000000000..90f1a8e4db --- /dev/null +++ b/Task/Fractran/Ada/fractran.ada @@ -0,0 +1,43 @@ +with Ada.Text_IO; + +procedure Fractan is + + type Fraction is record Nom: Natural; Denom: Positive; end record; + type Frac_Arr is array(Positive range <>) of Fraction; + + function "/" (N: Natural; D: Positive) return Fraction is + Frac: Fraction := (Nom => N, Denom => D); + begin + return Frac; + end "/"; + + procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is + N: Positive := Start; + J: Positive; + begin + Ada.Text_IO.Put(" 0:" & Integer'Image(N) & " "); + for I in 1 .. Max_Steps loop + J := List'First; + loop + if N mod List(J).Denom = 0 then + N := (N/List(J).Denom) * List(J).Nom; + exit; -- found fraction + elsif J >= List'Last then + return; -- did try out all fractions + else + J := J + 1; -- try the next fraction + end if; + end loop; + Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & " "); + end loop; + end F; + +begin + -- F((2/3, 7/2, 1/5, 1/7, 1/9, 1/4, 1/8), 2, 100); + -- output would be "0: 2 1: 7 2: 1" and then terminate + + F((17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, + 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1), + 2, 15); + -- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116" +end Fractan; diff --git a/Task/Fractran/AutoHotkey/fractran.ahk b/Task/Fractran/AutoHotkey/fractran.ahk new file mode 100644 index 0000000000..c1f3dae451 --- /dev/null +++ b/Task/Fractran/AutoHotkey/fractran.ahk @@ -0,0 +1,24 @@ +n := 2, steplimit := 15, numerator := [], denominator := [] +s := "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" + +Loop, Parse, s, % A_Space + if (!RegExMatch(A_LoopField, "^(\d+)/(\d+)$", m)) + MsgBox, % "Invalid input string (" A_LoopField ")." + else + numerator[A_Index] := m1, denominator[A_Index] := m2 + +SetFormat, FloatFast, 0.0 +Gui, Add, ListView, R10 W100 -Hdr, | +SysGet, VSBW, 2 +LV_ModifyCol(1, 95 - VSBW), LV_Add( , 0 ": " n) +Gui, Show + +Loop, % steplimit { + i := A_Index + Loop, % numerator.MaxIndex() + if (!Mod(nn := n * numerator[A_Index] / denominator[A_Index], 1)) { + LV_Modify(LV_Add( , i ": " (n := nn)), "Vis") + continue, 2 + } + break +} diff --git a/Task/Fractran/Bracmat/fractran.bracmat b/Task/Fractran/Bracmat/fractran.bracmat new file mode 100644 index 0000000000..72bd1682bb --- /dev/null +++ b/Task/Fractran/Bracmat/fractran.bracmat @@ -0,0 +1,36 @@ +(fractran= + np n fs A Z fi P p N L M +. !arg:(?N,?n,?fs) {Number of iterations, start n, fractions} + & :?P:?L {Initialise accumulators.} + & whl + ' ( -1+!N:>0:?N {Stop when counted down to zero.} + & !n !L:?L {Prepend all numbers to result list.} + & (2\L!n:#?p&!P !p:?P|) {If log2(n) is rational, append it to list of primes.} + & !fs:? (/?fi&!n*!fi:~/:?n) ? {This line does the following (See task description): + "for the first fraction, fi, in the list for which + nfi is an integer, replace n by nfi ;"} + ) + & :?M + & whl'(!L:%?n ?L&!n !M:?M) {Invert list of numbers. (append to long list is + very expensive. Better to prepend and finally invert.} + & (!M,!P) {Return the two lists} +); + + + +( clk$:?t0 +& fractran$(430000, 2, 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1) + : (?numbers,?primes) +& lst$(numbers,"numbers.lst",NEW) +& put$(" +FRACTRAN found these primes:" + !primes + "\nThe list of numbers is saved in numbers.txt +The biggest number in the list is" + ( 0:?max + & !numbers:? (>%@!max:?max&~) ? + | !max + ) +str$("\ntime: " flt$(clk$+-1*!t0,4) " sec\n") +, "FRACTRAN.OUT",NEW) +); diff --git a/Task/Fractran/C++/fractran.cpp b/Task/Fractran/C++/fractran.cpp new file mode 100644 index 0000000000..a7be3afd55 --- /dev/null +++ b/Task/Fractran/C++/fractran.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#include + +using namespace std; + +class fractran +{ +public: + void run( std::string p, int s, int l ) + { + start = s; limit = l; + istringstream iss( p ); vector tmp; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( tmp ) ); + + string item; vector< pair > v; + pair a; + for( vector::iterator i = tmp.begin(); i != tmp.end(); i++ ) + { + string::size_type pos = ( *i ).find( '/', 0 ); + if( pos != std::string::npos ) + { + a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); + v.push_back( a ); + } + } + + exec( &v ); + } + +private: + void exec( vector< pair >* v ) + { + int cnt = 0; bool found; float r; + while( cnt < limit ) + { + cout << cnt << " : " << start << "\n"; + cnt++; + vector< pair >::iterator it = v->begin(); + found = false; + while( it != v->end() ) + { + r = start * ( ( *it ).first / ( *it ).second ); + if( r == floor( r ) ) + { + found = true; + break; + } + ++it; + } + + if( found ) start = ( int )r; + else break; + } + } + int start, limit; +}; +int main( int argc, char* argv[] ) +{ + fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); + return system( "pause" ); +} diff --git a/Task/Fractran/C/fractran.c b/Task/Fractran/C/fractran.c new file mode 100644 index 0000000000..6931d47852 --- /dev/null +++ b/Task/Fractran/C/fractran.c @@ -0,0 +1,65 @@ +#include +#include +#include + +typedef struct frac_s *frac; +struct frac_s { + int n, d; + frac next; +}; + +frac parse(char *s) +{ + int offset = 0; + struct frac_s h = {0}, *p = &h; + + while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { + s += offset; + p = p->next = malloc(sizeof *p); + *p = h; + p->next = 0; + } + + return h.next; +} + +int run(int v, char *s) +{ + frac n, p = parse(s); + mpz_t val; + mpz_init_set_ui(val, v); + +loop: n = p; + if (mpz_popcount(val) == 1) + gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); + else + gmp_printf(" %Zd", val); + + for (n = p; n; n = n->next) { + // assuming the fractions are not reducible + if (!mpz_divisible_ui_p(val, n->d)) continue; + + mpz_divexact_ui(val, val, n->d); + mpz_mul_ui(val, val, n->n); + goto loop; + } + + gmp_printf("\nhalt: %Zd has no divisors\n", val); + + mpz_clear(val); + while (p) { + n = p->next; + free(p); + p = n; + } + + return 0; +} + +int main(void) +{ + run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " + "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); + + return 0; +} diff --git a/Task/Fractran/Common-Lisp/fractran.lisp b/Task/Fractran/Common-Lisp/fractran.lisp new file mode 100644 index 0000000000..5c44f72791 --- /dev/null +++ b/Task/Fractran/Common-Lisp/fractran.lisp @@ -0,0 +1,21 @@ +(defun fractran (n frac-list) + (lambda () + (prog1 + n + (when n + (let ((f (find-if (lambda (frac) + (integerp (* n frac))) + frac-list))) + (when f (setf n (* f n)))))))) + + +;; test + +(defvar *primes-ft* '(17/91 78/85 19/51 23/38 29/33 77/29 95/23 + 77/19 1/17 11/13 13/11 15/14 15/2 55/1)) + +(loop with fractran-instance = (fractran 2 *primes-ft*) + repeat 20 + for next = (funcall fractran-instance) + until (null next) + do (print next)) diff --git a/Task/Fractran/D/fractran-1.d b/Task/Fractran/D/fractran-1.d new file mode 100644 index 0000000000..ecb689edeb --- /dev/null +++ b/Task/Fractran/D/fractran-1.d @@ -0,0 +1,18 @@ +import std.stdio, std.algorithm, std.conv, std.array; + +void fractran(in string prog, int val, in uint limit) { + const fracts = prog.split.map!(p => p.split("/").to!(int[])).array; + + foreach (immutable n; 0 .. limit) { + writeln(n, ": ", val); + const found = fracts.find!(p => val % p[1] == 0); + if (found.empty) + break; + val = found.front[0] * val / found.front[1]; + } +} + +void main() { + fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 + 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15); +} diff --git a/Task/Fractran/D/fractran-2.d b/Task/Fractran/D/fractran-2.d new file mode 100644 index 0000000000..30fac153fe --- /dev/null +++ b/Task/Fractran/D/fractran-2.d @@ -0,0 +1,26 @@ +import std.stdio, std.algorithm, std.conv, std.array, std.range; + +struct Fractran { + int front; + bool empty = false; + const int[][] fracts; + + this(in string prog, in int val) { + this.front = val; + fracts = prog.split.map!(p => p.split("/").to!(int[])).array; + } + + void popFront() { + const found = fracts.find!(p => front % p[1] == 0); + if (found.empty) + empty = true; + else + front = found.front[0] * front / found.front[1]; + } +} + +void main() { + Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 + 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2) + .take(15).writeln; +} diff --git a/Task/Fractran/Go/fractran-1.go b/Task/Fractran/Go/fractran-1.go new file mode 100644 index 0000000000..647ffbbd3c --- /dev/null +++ b/Task/Fractran/Go/fractran-1.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "log" + "math/big" + "os" + "strconv" + "strings" +) + +func compile(src string) ([]big.Rat, bool) { + s := strings.Fields(src) + r := make([]big.Rat, len(s)) + for i, s1 := range s { + if _, ok := r[i].SetString(s1); !ok { + return nil, false + } + } + return r, true +} + +func exec(p []big.Rat, n *big.Int, limit int) { + var q, r big.Int +rule: + for i := 0; i < limit; i++ { + fmt.Printf("%d ", n) + for j := range p { + q.QuoRem(n, p[j].Denom(), &r) + if r.BitLen() == 0 { + n.Mul(&q, p[j].Num()) + continue rule + } + } + break + } + fmt.Println() +} + +func usage() { + log.Fatal("usage: ft ") +} + +func main() { + if len(os.Args) != 4 { + usage() + } + limit, err := strconv.Atoi(os.Args[1]) + if err != nil { + usage() + } + var n big.Int + _, ok := n.SetString(os.Args[2], 10) + if !ok { + usage() + } + p, ok := compile(os.Args[3]) + if !ok { + usage() + } + exec(p, &n, limit) +} diff --git a/Task/Fractran/Go/fractran-2.go b/Task/Fractran/Go/fractran-2.go new file mode 100644 index 0000000000..80aec53863 --- /dev/null +++ b/Task/Fractran/Go/fractran-2.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "log" + "math/big" + "os" + "os/exec" +) + +func main() { + c := exec.Command("ft", "1000000", "2", `17/91 78/85 19/51 23/38 + 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1`) + c.Stderr = os.Stderr + r, err := c.StdoutPipe() + if err != nil { + log.Fatal(err) + } + if err = c.Start(); err != nil { + log.Fatal(err) + } + var n big.Int + for primes := 0; primes < 20; { + if _, err = fmt.Fscan(r, &n); err != nil { + log.Fatal(err) + } + l := n.BitLen() - 1 + n.SetBit(&n, l, 0) + if n.BitLen() == 0 && l > 1 { + fmt.Printf("%d ", l) + primes++ + } + } + fmt.Println() +} diff --git a/Task/Fractran/Haskell/fractran.hs b/Task/Fractran/Haskell/fractran.hs new file mode 100644 index 0000000000..e80a1ec778 --- /dev/null +++ b/Task/Fractran/Haskell/fractran.hs @@ -0,0 +1,12 @@ +import Data.List (find) +import Data.Ratio (Ratio, (%), denominator) + +fractran :: (Integral a) => [Ratio a] -> a -> [a] +fractran fracts n = n : + case find (\f -> n `mod` denominator f == 0) fracts of + Nothing -> [] + Just f -> fractran fracts $ truncate (fromIntegral n * f) + +main :: IO () +main = print $ take 15 $ fractran [17%91, 78%85, 19%51, 23%38, 29%33, 77%29, + 95%23, 77%19, 1%17, 11%13, 13%11, 15%14, 15%2, 55%1] 2 diff --git a/Task/Fractran/Icon/fractran.icon b/Task/Fractran/Icon/fractran.icon new file mode 100644 index 0000000000..0b56769361 --- /dev/null +++ b/Task/Fractran/Icon/fractran.icon @@ -0,0 +1,27 @@ +record fract(n,d) + +procedure main(A) + fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2) +end + +procedure fractran(s, n, limit) + execute(parse(s),n, limit) +end + +procedure parse(s) + f := [] + s ? while not pos(0) do { + tab(upto(' ')|0) ? put(f,fract(tab(upto('/')), (move(1),tab(0)))) + move(1) + } + return f +end + +procedure execute(f,d,limit) + /limit := 15 + every !limit do { + if d := (d%f[i := !*f].d == 0, (writes(" ",d)/f[i].d)*f[i].n) then {} + else break write() + } + write() +end diff --git a/Task/Fractran/J/fractran-1.j b/Task/Fractran/J/fractran-1.j new file mode 100644 index 0000000000..1474193a3c --- /dev/null +++ b/Task/Fractran/J/fractran-1.j @@ -0,0 +1,2 @@ +toFrac=: '/r' 0&".@charsub ] NB. read fractions from string +fractran15=: ({~ (= <.) i. 1:)@(toFrac@[ * ]) ^:(<15) NB. return first 15 Fractran results diff --git a/Task/Fractran/J/fractran-2.j b/Task/Fractran/J/fractran-2.j new file mode 100644 index 0000000000..7e7867e7ff --- /dev/null +++ b/Task/Fractran/J/fractran-2.j @@ -0,0 +1,3 @@ + taskstr=: '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' + taskstr fractran15 2 +2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 diff --git a/Task/Fractran/Java/fractran.java b/Task/Fractran/Java/fractran.java new file mode 100644 index 0000000000..59a3e6cbf8 --- /dev/null +++ b/Task/Fractran/Java/fractran.java @@ -0,0 +1,54 @@ +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Fractran{ + + public static void main(String []args){ + + new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); + } + final int limit = 15; + + + Vector num = new Vector<>(); + Vector den = new Vector<>(); + public Fractran(String prog, Integer val){ + compile(prog); + dump(); + exec(2); + } + + + void compile(String prog){ + Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); + Matcher matcher = regexp.matcher(prog); + while(matcher.find()){ + num.add(Integer.parseInt(matcher.group(1))); + den.add(Integer.parseInt(matcher.group(2))); + matcher = regexp.matcher(matcher.group(3)); + } + } + + void exec(Integer val){ + int n = 0; + while(val != null && n"; + val = step(val); + i ++; + } +} + +// Main +compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"); +dump(); +var limit = 15; +exec(2); diff --git a/Task/Fractran/Mathematica/fractran.math b/Task/Fractran/Mathematica/fractran.math new file mode 100644 index 0000000000..e3decc34bf --- /dev/null +++ b/Task/Fractran/Mathematica/fractran.math @@ -0,0 +1,15 @@ +fractionlist = {17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1}; +n = 2; +steplimit = 20; +j = 0; +break = False; +While[break == False && j <= steplimit, + newlist = n fractionlist; + isintegerlist = IntegerQ[#] & /@ newlist; + truepositions = Position[isintegerlist, True]; + If[Length[truepositions] == 0, + break = True, + Print[ToString[j] <> ": " <> ToString[n]]; + n = newlist[[truepositions[[1, 1]]]]; j++; + ] + ] diff --git a/Task/Fractran/Perl-6/fractran-1.pl6 b/Task/Fractran/Perl-6/fractran-1.pl6 new file mode 100644 index 0000000000..1882f33ce0 --- /dev/null +++ b/Task/Fractran/Perl-6/fractran-1.pl6 @@ -0,0 +1,6 @@ +sub ft (\n) { + first Int, map (* * n).narrow, + <17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1>, 0 +} +constant FT = 2, &ft ... 0; +say FT[^100]; diff --git a/Task/Fractran/Perl-6/fractran-2.pl6 b/Task/Fractran/Perl-6/fractran-2.pl6 new file mode 100644 index 0000000000..1ea8f08465 --- /dev/null +++ b/Task/Fractran/Perl-6/fractran-2.pl6 @@ -0,0 +1,6 @@ +constant FT2 = FT.grep: { not $_ +& ($_ - 1) } +for 1..* -> $i { + given FT2[$i] { + say $i, "\t", .msb, "\t", $_; + } +} diff --git a/Task/Fractran/Perl/fractran.pl b/Task/Fractran/Perl/fractran.pl new file mode 100644 index 0000000000..abf777dd2c --- /dev/null +++ b/Task/Fractran/Perl/fractran.pl @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Math::BigRat; + +my ($n, @P) = map Math::BigRat->new($_), qw{ +2 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1 +}; + +$|=1; +MAIN: for( 1 .. 5000 ) { + print " " if $_ > 1; + my ($pow, $rest) = (0, $n->copy); + until( $rest->is_odd ) { + ++$pow; + $rest->bdiv(2); + } + if( $rest->is_one ) { + print "2**$pow"; + } else { + #print $n; + } + for my $f_i (@P) { + my $nf_i = $n * $f_i; + next unless $nf_i->is_int; + $n = $nf_i; + next MAIN; + } + last; +} + +print "\n"; diff --git a/Task/Fractran/Python/fractran-1.py b/Task/Fractran/Python/fractran-1.py new file mode 100644 index 0000000000..aa3eeaf7aa --- /dev/null +++ b/Task/Fractran/Python/fractran-1.py @@ -0,0 +1,21 @@ +from fractions import Fraction + +def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' + '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' + '13 / 11, 15 / 14, 15 / 2, 55 / 1'): + flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] + + n = Fraction(n) + while True: + yield n.numerator + for f in flist: + if (n * f).denominator == 1: + break + else: + break + n *= f + +if __name__ == '__main__': + n, m = 2, 15 + print('First %i members of fractran(%i):\n ' % (m, n) + + ', '.join(str(f) for f,i in zip(fractran(n), range(m)))) diff --git a/Task/Fractran/Python/fractran-2.py b/Task/Fractran/Python/fractran-2.py new file mode 100644 index 0000000000..a88b18c217 --- /dev/null +++ b/Task/Fractran/Python/fractran-2.py @@ -0,0 +1,13 @@ +from fractran import fractran + +def fractran_primes(): + for i, fr in enumerate(fractran(2), 1): + binstr = bin(fr)[2:] + if binstr.count('1') == 1: + prime = binstr.count('0') + if prime > 1: # Skip 2**0 and 2**1 + yield prime, i + +if __name__ == '__main__': + for (prime, i), j in zip(fractran_primes(), range(15)): + print("Generated prime %2i from the %6i'th member of the fractran series" % (prime, i)) diff --git a/Task/Fractran/README b/Task/Fractran/README new file mode 100644 index 0000000000..2d8a1de06f --- /dev/null +++ b/Task/Fractran/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Fractran diff --git a/Task/Fractran/REXX/fractran-1.rexx b/Task/Fractran/REXX/fractran-1.rexx new file mode 100644 index 0000000000..404b69824c --- /dev/null +++ b/Task/Fractran/REXX/fractran-1.rexx @@ -0,0 +1,23 @@ +/*REXX pgm runs FRACTRAN for a given set of fractions and from a given N*/ +numeric digits 999 /*be able to handle larger nums. */ +parse arg N terms fracs /*get optional arguments from CL.*/ +if N=='' | N==',' then N=2 /*N specified? No, use default.*/ +if terms==''|terms==',' then terms=100 /*TERMS specified? Use default.*/ +if fracs='' then fracs= , /*any fractions specified? No···*/ +'17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1' +f=space(fracs,0) /* [↑] use default for fractions.*/ + do i=1 while f\==''; parse var f n.i '/' d.i ',' f + end /*i*/ /* [↑] parse all the fractions.*/ +#=i-1 /*the number of fractions found. */ +say # 'fractions:' fracs /*display # and actual fractions.*/ +say 'N is starting at ' N /*display the starting number N.*/ +say terms ' terms are being shown:' /*display a kind of header/title.*/ + + do j=1 for terms /*perform loop once for each term*/ + do k=1 for #; if N//d.k\==0 then iterate /*not an integer?*/ + say right('term' j,35) '──► ' N /*display the Nth term with N. */ + N = N % d.k * n.k /*calculate the next term (use %)*/ + leave /*go start calculating next term.*/ + end /*k*/ /* [↑] if integer, found a new N*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Fractran/REXX/fractran-2.rexx b/Task/Fractran/REXX/fractran-2.rexx new file mode 100644 index 0000000000..abc6dbcf67 --- /dev/null +++ b/Task/Fractran/REXX/fractran-2.rexx @@ -0,0 +1,35 @@ +/*REXX pgm runs FRACTRAN for a given set of fractions and from a given N*/ +numeric digits 999; w=length(digits()) /*be able to handle larger nums. */ +parse arg N terms fracs /*get optional arguments from CL.*/ +if N=='' | N==',' then N=2 /*N specified? No, use default.*/ +if terms==''|terms==',' then terms=100 /*TERMS specified? Use default.*/ +if fracs='' then fracs= , /*any fractions specified? No···*/ +'17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1' +f=space(fracs,0) /* [↑] use default for fractions.*/ +L=length(N) /*length in decimal digits of N.*/ +tell= terms>0 /*flag: show # or a power of 2.*/ + do i=1 while f\==''; parse var f n.i '/' d.i ',' f + end /*i*/ /* [↑] parse all the fractions.*/ +!.=0 /*default value for powers of 2.*/ +if \tell then do p=0 until length(_)>digits(); _=2**p; !._=1 + if p<2 then @._=left('',w+9) '2**'left(p,w) " " + else @._='(prime' right(p,w)") 2**"left(p,w) ' ' + end /*p*/ /* [↑] build powers of 2 tables.*/ +#=i-1 /*the number of fractions found. */ +say # 'fractions:' fracs /*display # and actual fractions.*/ +say 'N is starting at ' N /*display the starting number N.*/ +if tell then say terms ' terms are being shown:' /*display hdr.*/ + else say 'only powers of two are being shown:' /* " " */ +q='(max digits used: ' /*a literal used in the SAY below*/ + + do j=1 for abs(terms) /*perform loop once for each term*/ + do k=1 for #; if N//d.k\==0 then iterate /*not an integer?*/ + if tell then say right('term' j,35) '──► ' N /*display Nth term&N*/ + else if !.N then say right('term' j,15) '──►' @.N q, + right(L,w)") " N /*2ⁿ.*/ + N = N % d.k * n.k /*calculate the next term (use %)*/ + L=max(L, length(N)) /*maximum number of decimal digs.*/ + leave /*go start calculating next term.*/ + end /*k*/ /* [↑] if integer, found a new N*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Fractran/Racket/fractran.rkt b/Task/Fractran/Racket/fractran.rkt new file mode 100644 index 0000000000..c415b51bab --- /dev/null +++ b/Task/Fractran/Racket/fractran.rkt @@ -0,0 +1,31 @@ +#lang racket + +(define (displaysp x) + (display x) + (display " ")) + +(define (read-string-list str) + (map string->number + (string-split (string-replace str " " "") ","))) + +(define (eval-fractran n list) + (for/or ([e (in-list list)]) + (let ([en (* e n)]) + (and (integer? en) en)))) + +(define (show-fractran fr n s) + (printf "First ~a members of fractran(~a):\n" s n) + (displaysp n) + (for/fold ([n n]) ([i (in-range (- s 1))]) + (let ([new-n (eval-fractran n fr)]) + (displaysp new-n) + new-n)) + (void)) + +(define fractran + (read-string-list + (string-append "17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33," + "77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13," + "13 / 11, 15 / 14, 15 / 2, 55 / 1"))) + +(show-fractran fractran 2 15) diff --git a/Task/Fractran/Ruby/fractran.rb b/Task/Fractran/Ruby/fractran.rb new file mode 100644 index 0000000000..9839dfdb3f --- /dev/null +++ b/Task/Fractran/Ruby/fractran.rb @@ -0,0 +1,18 @@ +str ="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1" +FractalProgram = str.split(',').map(&:to_r) #=> array of rationals + +Runner = Enumerator.new do |y| + num = 2 + loop{ y << num *= FractalProgram.detect{|f| (num*f).denominator == 1} } +end + +prime_generator = Enumerator.new do |y| + Runner.each do |num| + l = Math.log2(num) + y << l.to_i if l.floor == l + end +end + +# demo +p Runner.take(20) +p prime_generator.take(20) diff --git a/Task/Fractran/Seed7/fractran-1.seed7 b/Task/Fractran/Seed7/fractran-1.seed7 new file mode 100644 index 0000000000..2a3db7790d --- /dev/null +++ b/Task/Fractran/Seed7/fractran-1.seed7 @@ -0,0 +1,36 @@ +$ include "seed7_05.s7i"; + include "rational.s7i"; + +const func array integer: fractran (in integer: limit, in var integer: number, in array rational: program) is func + result + var array integer: output is 0 times 0; + local + var integer: index is 1; + var rational: newNumber is 0/1; + begin + output := [] (number); + while index <= length(program) and length(output) <= limit do + newNumber := rat(number) * program[index]; + if newNumber = rat(trunc(newNumber)) then + number := trunc(newNumber); + output &:= number; + index := 1; + else + incr(index); + end if; + end while; + end func; + +const proc: main is func + local + const array rational: program is [] + (17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1); + var array integer: output is 0 times 0; + var integer: number is 0; + begin + output := fractran(15, 2, program); + for number range output do + write(number <& " "); + end for; + writeln; + end func; diff --git a/Task/Fractran/Seed7/fractran-2.seed7 b/Task/Fractran/Seed7/fractran-2.seed7 new file mode 100644 index 0000000000..8e49eaa328 --- /dev/null +++ b/Task/Fractran/Seed7/fractran-2.seed7 @@ -0,0 +1,29 @@ +$ include "seed7_05.s7i"; + include "bigrat.s7i"; + +const proc: fractran (in var bigInteger: number, in array bigRational: program) is func + local + var integer: index is 1; + var bigRational: newNumber is 0_/1_; + begin + while index <= length(program) do + newNumber := rat(number) * program[index]; + if newNumber = rat(trunc(newNumber)) then + number := trunc(newNumber); + if 2_ ** ord(log2(number)) = number then + writeln(log2(number)); + end if; + index := 1; + else + incr(index); + end if; + end while; + end func; + +const proc: main is func + local + const array bigRational: program is [] + (17_/91_, 78_/85_, 19_/51_, 23_/38_, 29_/33_, 77_/29_, 95_/23_, 77_/19_, 1_/17_, 11_/13_, 13_/11_, 15_/14_, 15_/2_, 55_/1_); + begin + fractran(2_, program); + end func; diff --git a/Task/Fractran/Tcl/fractran-1.tcl b/Task/Fractran/Tcl/fractran-1.tcl new file mode 100644 index 0000000000..50932aaba5 --- /dev/null +++ b/Task/Fractran/Tcl/fractran-1.tcl @@ -0,0 +1,49 @@ +package require Tcl 8.6 + +oo::class create Fractran { + variable fracs nco + constructor {fractions} { + set fracs {} + foreach frac $fractions { + if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { + lappend fracs $num $denom + } else { + return -code error "$frac is not a supported fraction" + } + } + if {![llength $fracs]} { + return -code error "need at least one fraction" + } + } + + method execute {n {steps 15}} { + set co [coroutine [incr nco] my Generate $n] + for {set i 0} {$i < $steps} {incr i} { + lappend result [$co] + } + catch {rename $co ""} + return $result + } + + method Step {n} { + foreach {num den} $fracs { + if {$n % $den} continue + return [expr {$n * $num / $den}] + } + return -code break + } + method Generate {n} { + yield [info coroutine] + while 1 { + yield $n + set n [my Step $n] + } + return -code break + } +} + +set ft [Fractran new { + 17/91 78/85 19/51 23/38 29/33 77/29 95/23 + 77/19 1/17 11/13 13/11 15/14 15/2 55/1 +}] +puts [$ft execute 2] diff --git a/Task/Fractran/Tcl/fractran-2.tcl b/Task/Fractran/Tcl/fractran-2.tcl new file mode 100644 index 0000000000..a61af1865b --- /dev/null +++ b/Task/Fractran/Tcl/fractran-2.tcl @@ -0,0 +1,12 @@ +oo::objdefine $ft method pow2 {n} { + set co [coroutine [incr nco] my Generate 2] + set pows {} + while {[llength $pows] < $n} { + set item [$co] + if {($item & ($item-1)) == 0} { + lappend pows $item + } + } + return $pows +} +puts [$ft pow2 10] diff --git a/Task/Gaussian-elimination/00DESCRIPTION b/Task/Gaussian-elimination/00DESCRIPTION new file mode 100644 index 0000000000..09cd5dfd4d --- /dev/null +++ b/Task/Gaussian-elimination/00DESCRIPTION @@ -0,0 +1 @@ +Problem: Solve Ax=b using Gaussian elimination then backwards substitution. A being an n by n matrix. Also, x and b are n by 1 vectors. To improve accuracy, please use partial pivoting and scaling. diff --git a/Task/Gaussian-elimination/00META.yaml b/Task/Gaussian-elimination/00META.yaml new file mode 100644 index 0000000000..106b0ac419 --- /dev/null +++ b/Task/Gaussian-elimination/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Matrices diff --git a/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-1.alg b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-1.alg new file mode 100644 index 0000000000..6f92084e03 --- /dev/null +++ b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-1.alg @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- # +COMMENT PROVIDES + MODE FIXED; INT fixed exception, unfixed exception; + PROC (STRING message) FIXED raise, raise value error +END COMMENT + +# Note: ℵ indicates attribute is "private", and + should not be used outside of this prelude # + +MODE FIXED = BOOL; # if an exception is detected, can it be fixed "on-site"? # +FIXED fixed exception = TRUE, unfixed exception = FALSE; + +MODE #ℵ#SIMPLEOUTV = [0]UNION(CHAR, STRING, INT, REAL, BOOL, BITS); +MODE #ℵ#SIMPLEOUTM = [0]#ℵ#SIMPLEOUTV; +MODE #ℵ#SIMPLEOUTT = [0]#ℵ#SIMPLEOUTM; +MODE SIMPLEOUT = [0]#ℵ#SIMPLEOUTT; + +PROC raise = (#ℵ#SIMPLEOUT message)FIXED: ( + putf(stand error, ($"Exception:"$, $xg$, message, $l$)); + stop +); + +PROC raise value error = (#ℵ#SIMPLEOUT message)FIXED: + IF raise(message) NE fixed exception THEN exception value error; FALSE FI; + +SKIP diff --git a/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-2.alg b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-2.alg new file mode 100644 index 0000000000..dd44e276d7 --- /dev/null +++ b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-2.alg @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- # +COMMENT PRELUDE REQUIRES + MODE SCAL = REAL; + FORMAT scal repr = real repr + # and various SCAL OPerators # +END COMMENT + +COMMENT PRELUDE PROIVIDES + MODE VEC, MAT; + OP :=:, -:=, +:=, *:=, /:=; + FORMAT sub, sep, bus; + FORMAT vec repr, mat repr +END COMMENT + +# Note: ℵ indicates attribute is "private", and + should not be used outside of this prelude # + +INT #ℵ#lwb vec := 1, #ℵ#upb vec := 0; +INT #ℵ#lwb mat := 1, #ℵ#upb mat := 0; +MODE VEC = [lwb vec:upb vec]SCAL, + MAT = [lwb mat:upb mat,lwb vec:upb vec]SCAL; + +FORMAT sub := $"( "$, sep := $", "$, bus := $")"$, nl:=$lxx$; +FORMAT vec repr := $f(sub)n(upb vec - lwb vec)(f(scal repr)f(sep))f(scal repr)f(bus)$; +FORMAT mat repr := $f(sub)n(upb mat - lwb mat)(f( vec repr)f(nl))f( vec repr)f(bus)$; + +# OPerators to swap the contents of two VECtors # +PRIO =:= = 1; +OP =:= = (REF VEC u, v)VOID: + FOR i TO UPB u DO SCAL scal=u[i]; u[i]:=v[i]; v[i]:=scal OD; + +OP +:= = (REF VEC lhs, VEC rhs)REF VEC: ( + FOR i TO UPB lhs DO lhs[i] +:= rhs[i] OD; + lhs +); + +OP -:= = (REF VEC lhs, VEC rhs)REF VEC: ( + FOR i TO UPB lhs DO lhs[i] -:= rhs[i] OD; + lhs +); + +OP *:= = (REF VEC lhs, SCAL rhs)REF VEC: ( + FOR i TO UPB lhs DO lhs[i] *:= rhs OD; + lhs +); + +OP /:= = (REF VEC lhs, SCAL rhs)REF VEC: ( + SCAL inv = 1 / rhs; # multiplication is faster # + FOR i TO UPB lhs DO lhs[i] *:= inv OD; + lhs +); + +SKIP diff --git a/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-3.alg b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-3.alg new file mode 100644 index 0000000000..9957c30000 --- /dev/null +++ b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-3.alg @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- # +COMMENT PRELUDE REQUIRES + MODE SCAL = REAL, + REAL near min scal = min real ** 0.99, + MODE VEC = []REAL, + MODE MAT = [,]REAL, + FORMAT scal repr = real repr, + and various OPerators of MAT and VEC +END COMMENT + +COMMENT PRELUDE PROVIDES + PROC(MAT a, b)MAT gaussian elimination; + PROC(REF MAT a, b)REF MAT in situ gaussian elimination +END COMMENT + +#################################################### +# using Gaussian elimination, find x where A*x = b # +#################################################### +PROC in situ gaussian elimination = (REF MAT a, b)REF MAT: ( +# Note: a and b are modified "in situ", and b is returned as x # + + FOR diag TO UPB a-1 DO + INT pivot row := diag; SCAL pivot factor := ABS a[diag,diag]; + FOR row FROM diag + 1 TO UPB a DO # Full pivoting # + SCAL abs a diag = ABS a[row,diag]; + IF abs a diag>=pivot factor THEN + pivot row := row; pivot factor := abs a diag FI + OD; + # now we have the "best" diag to full pivot, do the actual pivot # + IF diag NE pivot row THEN + # a[pivot row,] =:= a[diag,]; XXX: unoptimised # #DB# + a[pivot row,diag:] =:= a[diag,diag:]; # XXX: optimised # + b[pivot row,] =:= b[diag,] # swap/pivot the diags of a & b # + FI; + + IF ABS a[diag,diag] <= near min scal THEN + raise value error("singular matrix") FI; + SCAL a diag reciprocal := 1 / a[diag, diag]; + + FOR row FROM diag+1 TO UPB a DO + SCAL factor = a[row,diag] * a diag reciprocal; + # a[row,] -:= factor * a[diag,] XXX: "unoptimised" # #DB# + a[row,diag+1:] -:= factor * a[diag,diag+1:];# XXX: "optimised" # + b[row,] -:= factor * b[diag,] + OD + OD; + +# We have a triangular matrix, at this point we can traverse backwards + up the diagonal calculating b\A Converting it initial to a diagonal + matrix, then to the identity. # + + FOR diag FROM UPB a BY -1 TO 1+LWB a DO + + IF ABS a[diag,diag] <= near min scal THEN + raise value error("Zero pivot encountered?") FI; + SCAL a diag reciprocal = 1 / a[diag,diag]; + + FOR row TO diag-1 DO + SCAL factor = a[row,diag] * a diag reciprocal; + # a[row,diag] -:= factor * a[diag,diag]; XXX: "unoptimised" so remove # #DB# + b[row,] -:= factor * b[diag,] + OD; +# Now we have only diagonal elements we can simply divide b + by the values along the diagonal of A. # + b[diag,] *:= a diag reciprocal + OD; + + b # EXIT # +); + +PROC gaussian elimination = (MAT in a, in b)MAT: ( +# Note: a and b are cloned and not modified "in situ" # + [UPB in a, 2 UPB in a]SCAL a := in a; + [UPB in b, 2 UPB in b]SCAL b := in b; + in situ gaussian elimination(a,b) +); + +SKIP diff --git a/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-4.alg b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-4.alg new file mode 100644 index 0000000000..b8ceef80ee --- /dev/null +++ b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-4.alg @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- # +COMMENT POSTLUDE PROIVIDES + PROC VOID exception too many iterations, exception value error; +END COMMENT + +SKIP EXIT +exception too many iterations: +exception value error: + stop diff --git a/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-5.alg b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-5.alg new file mode 100644 index 0000000000..4c27544a4e --- /dev/null +++ b/Task/Gaussian-elimination/ALGOL-68/gaussian-elimination-5.alg @@ -0,0 +1,29 @@ +#!/usr/bin/algol68g-full --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude_exception.a68" PR; + +# define the attributes of the scalar field being used # +MODE SCAL = REAL; +FORMAT scal repr = $g(-0,real width)$; +# create "near min scal" as is scales better then small real # +SCAL near min scal = min real ** 0.99; + +PR READ "prelude_mat_lib.a68" PR; +PR READ "prelude_gaussian_elimination.a68" PR; + +MAT a =(( 1.00, 0.00, 0.00, 0.00, 0.00, 0.00), + ( 1.00, 0.63, 0.39, 0.25, 0.16, 0.10), + ( 1.00, 1.26, 1.58, 1.98, 2.49, 3.13), + ( 1.00, 1.88, 3.55, 6.70, 12.62, 23.80), + ( 1.00, 2.51, 6.32, 15.88, 39.90, 100.28), + ( 1.00, 3.14, 9.87, 31.01, 97.41, 306.02)); +VEC b = (-0.01, 0.61, 0.91, 0.99, 0.60, 0.02); + +[UPB b,1]SCAL col b; col b[,1]:= b; + +upb vec := 2 UPB a; + +printf((vec repr, gaussian elimination(a,col b))); + +PR READ "postlude_exception.a68" PR diff --git a/Task/Gaussian-elimination/C/gaussian-elimination.c b/Task/Gaussian-elimination/C/gaussian-elimination.c new file mode 100644 index 0000000000..0c588ba730 --- /dev/null +++ b/Task/Gaussian-elimination/C/gaussian-elimination.c @@ -0,0 +1,73 @@ +#include +#include +#include + +#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x))) + +void swap_row(double *a, double *b, int r1, int r2, int n) +{ + double tmp, *p1, *p2; + int i; + + if (r1 == r2) return; + for (i = 0; i < n; i++) { + p1 = mat_elem(a, r1, i, n); + p2 = mat_elem(a, r2, i, n); + tmp = *p1, *p1 = *p2, *p2 = tmp; + } + tmp = b[r1], b[r1] = b[r2], b[r2] = tmp; +} + +void gauss_eliminate(double *a, double *b, double *x, int n) +{ +#define A(y, x) (*mat_elem(a, y, x, n)) + int i, j, col, row, max_row,dia; + double max, tmp; + + for (dia = 0; dia < n; dia++) { + max_row = dia, max = A(dia, dia); + + for (row = dia + 1; row < n; row++) + if ((tmp = fabs(A(row, dia))) > max) + max_row = row, max = tmp; + + swap_row(a, b, dia, max_row, n); + + for (row = dia + 1; row < n; row++) { + tmp = A(row, dia) / A(dia, dia); + for (col = dia+1; col < n; col++) + A(row, col) -= tmp * A(dia, col); + A(row, dia) = 0; + b[row] -= tmp * b[dia]; + } + } + for (row = n - 1; row >= 0; row--) { + tmp = b[row]; + for (j = n - 1; j > row; j--) + tmp -= x[j] * A(row, j); + x[row] = tmp / A(row, row); + } +#undef A +} + +int main(void) +{ + double a[] = { + 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, + 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, + 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, + 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, + 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, + 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 + }; + double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 }; + double x[6]; + int i; + + gauss_eliminate(a, b, x, 6); + + for (i = 0; i < 6; i++) + printf("%g\n", x[i]); + + return 0; +} diff --git a/Task/Gaussian-elimination/D/gaussian-elimination.d b/Task/Gaussian-elimination/D/gaussian-elimination.d new file mode 100644 index 0000000000..f85f439d1e --- /dev/null +++ b/Task/Gaussian-elimination/D/gaussian-elimination.d @@ -0,0 +1,69 @@ +import std.stdio, std.math, std.algorithm, std.range, std.numeric, + std.typecons; + +Tuple!(double[],"x", string,"err") +gaussPartial(in double[][] a0, in double[] b0) pure /*nothrow*/ +in { + assert(a0.length == a0[0].length); + assert(a0.length == b0.length); + assert(a0.all!(row => row.length == a0[0].length)); +} body { + enum eps = 1e-6; + immutable m = b0.length; + + // Make augmented matrix. + //auto a = a0.zip(b0).map!(c => c[0] ~ c[1]).array; // Not mutable. + auto a = a0.zip(b0).map!(c => [] ~ c[0] ~ c[1]).array; + + // Wikipedia algorithm from Gaussian elimination page, + // produces row-eschelon form. + foreach (immutable k; 0 .. a.length) { + // Find pivot for column k and swap. + a[k .. m].minPos!((x, y) => x[k] > y[k]).front.swap(a[k]); + if (a[k][k].abs < eps) + return typeof(return)(null, "singular"); + + // Do for all rows below pivot. + foreach (immutable i; k + 1 .. m) { + // Do for all remaining elements in current row. + a[i][k+1 .. m+1] -= a[k][k+1 .. m+1] * (a[i][k] / a[k][k]); + + a[i][k] = 0; // Fill lower triangular matrix with zeros. + } + } + + // End of WP algorithm. Now back substitute to get result. + auto x = new double[m]; + foreach_reverse (immutable i; 0 .. m) + x[i] = (a[i][m] - a[i][i+1 .. m].dotProduct(x[i+1 .. m])) / a[i][i]; + + return typeof(return)(x, null); +} + +void main() { + // The test case result is correct to this tolerance. + enum eps = 1e-13; + + // Common RC example. Result computed with rational arithmetic + // then converted to double, and so should be about as close to + // correct as double represention allows. + immutable a = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00], + [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], + [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], + [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], + [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], + [1.00, 3.14, 9.87, 31.01, 97.41, 306.02]]; + immutable b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]; + + immutable r = gaussPartial(a, b); + if (!r.err.empty) + return writeln("Error: ", r.err); + r.x.writeln; + + immutable result = [-0.01, 1.602790394502114, + -1.6132030599055613, 1.2454941213714368, + -0.4909897195846576, 0.065760696175232]; + foreach (immutable i, immutable xi; result) + if (abs(r.x[i] - xi) > eps) + return writeln("Out of tolerance: ", r.x[i], " ", xi); +} diff --git a/Task/Gaussian-elimination/Fortran/gaussian-elimination.f b/Task/Gaussian-elimination/Fortran/gaussian-elimination.f new file mode 100644 index 0000000000..128c48516b --- /dev/null +++ b/Task/Gaussian-elimination/Fortran/gaussian-elimination.f @@ -0,0 +1,43 @@ + program ge + + real, allocatable :: a(:,:),b(:) + a = reshape( & + [1.0, 1.00, 1.00, 1.00, 1.00, 1.00, & + 0.0, 0.63, 1.26, 1.88, 2.51, 3.14, & + 0.0, 0.39, 1.58, 3.55, 6.32, 9.87, & + 0.0, 0.25, 1.98, 6.70, 15.88, 31.01, & + 0.0, 0.16, 2.49, 12.62, 39.90, 97.41, & + 0.0, 0.10, 3.13, 23.80, 100.28, 306.02], [6,6] ) + b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02] + print'(f15.7)',solve_wbs(ge_wpp(a,b)) + + contains + + function solve_wbs(u) result(x) ! solve with backward substitution + real :: u(:,:) + integer :: i,n + real , allocatable :: x(:) + n = size(u,1) + allocate(x(n)) + forall (i=n:1:-1) x(i) = ( u(i,n+1) - sum(u(i,i+1:n)*x(i+1:n)) ) / u(i,i) + end function + + function ge_wpp(a,b) result(u) ! gaussian eliminate with partial pivoting + real :: a(:,:),b(:),upi + integer :: i,j,n,p + real , allocatable :: u(:,:) + n = size(a,1) + u = reshape( [a,b], [n,n+1] ) + do j=1,n + p = maxloc(abs(u(j:n,j)),1) + j-1 ! maxloc returns indices between (1,n-j+1) + if (p /= j) u([p,j],j) = u([j,p],j) + u(j+1:,j) = u(j+1:,j)/u(j,j) + do i=j+1,n+1 + upi = u(p,i) + if (p /= j) u([p,j],i) = u([j,p],i) + u(j+1:n,i) = u(j+1:n,i) - upi*u(j+1:n,j) + end do + end do + end function + + end program diff --git a/Task/Gaussian-elimination/Go/gaussian-elimination.go b/Task/Gaussian-elimination/Go/gaussian-elimination.go new file mode 100644 index 0000000000..5e5bb5b53f --- /dev/null +++ b/Task/Gaussian-elimination/Go/gaussian-elimination.go @@ -0,0 +1,97 @@ +package main + +import ( + "errors" + "fmt" + "log" + "math" +) + +type testCase struct { + a [][]float64 + b []float64 + x []float64 +} + +var tc = testCase{ + // common RC example. Result x computed with rational arithmetic then + // converted to float64, and so should be about as close to correct as + // float64 represention allows. + a: [][]float64{ + {1.00, 0.00, 0.00, 0.00, 0.00, 0.00}, + {1.00, 0.63, 0.39, 0.25, 0.16, 0.10}, + {1.00, 1.26, 1.58, 1.98, 2.49, 3.13}, + {1.00, 1.88, 3.55, 6.70, 12.62, 23.80}, + {1.00, 2.51, 6.32, 15.88, 39.90, 100.28}, + {1.00, 3.14, 9.87, 31.01, 97.41, 306.02}}, + b: []float64{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02}, + x: []float64{-0.01, 1.602790394502114, -1.6132030599055613, + 1.2454941213714368, -0.4909897195846576, 0.065760696175232}, +} + +// result from above test case turns out to be correct to this tolerance. +const ε = 1e-13 + +func main() { + x, err := GaussPartial(tc.a, tc.b) + if err != nil { + log.Fatal(err) + } + fmt.Println(x) + for i, xi := range x { + if math.Abs(tc.x[i]-xi) > ε { + log.Println("out of tolerance") + log.Fatal("expected", tc.x) + } + } +} + +func GaussPartial(a0 [][]float64, b0 []float64) ([]float64, error) { + // make augmented matrix + m := len(b0) + a := make([][]float64, m) + for i, ai := range a0 { + row := make([]float64, m+1) + copy(row, ai) + row[m] = b0[i] + a[i] = row + } + // WP algorithm from Gaussian elimination page + // produces row-eschelon form + for k := range a { + // Find pivot for column k: + iMax := k + max := math.Abs(a[k][k]) + for i := k + 1; i < m; i++ { + if abs := math.Abs(a[i][k]); abs > max { + iMax = i + max = abs + } + } + if a[iMax][k] == 0 { + return nil, errors.New("singular") + } + // swap rows(k, i_max) + a[k], a[iMax] = a[iMax], a[k] + // Do for all rows below pivot: + for i := k + 1; i < m; i++ { + // Do for all remaining elements in current row: + for j := k + 1; j <= m; j++ { + a[i][j] -= a[k][j] * (a[i][k] / a[k][k]) + } + // Fill lower triangular matrix with zeros: + a[i][k] = 0 + } + } + // end of WP algorithm. + // now back substitute to get result. + x := make([]float64, m) + for i := m - 1; i >= 0; i-- { + x[i] = a[i][m] + for j := i + 1; j < m; j++ { + x[i] -= a[i][j] * x[j] + } + x[i] /= a[i][i] + } + return x, nil +} diff --git a/Task/Gaussian-elimination/J/gaussian-elimination.j b/Task/Gaussian-elimination/J/gaussian-elimination.j new file mode 100644 index 0000000000..c8f78fb60b --- /dev/null +++ b/Task/Gaussian-elimination/J/gaussian-elimination.j @@ -0,0 +1,57 @@ + f=: 6j2&": NB. formatting verb + + sin=: 1&o. NB. verb to evaluate circle function 1, the sine + + add_noise=: ] + (* (_0.5 + 0 ?@:#~ #)) NB. AMPLITUDE add_noise SIGNAL + + f RADIANS=: o.@:(%~ i.@:>:)5 NB. monadic circle function is pi times + 0.00 0.63 1.26 1.88 2.51 3.14 + + f SINES=: sin RADIANS + 0.00 0.59 0.95 0.95 0.59 0.00 + + f NOISY_SINES=: 0.1 add_noise SINES + _0.01 0.61 0.91 0.99 0.60 0.02 + + A=: (^/ i.@:#) RADIANS NB. A is the quintic coefficient matrix + + NB. display the equation to solve + (f A) ; 'x' ; '=' ; f@:,. NOISY_SINES +┌────────────────────────────────────┬─┬─┬──────┐ +│ 1.00 0.00 0.00 0.00 0.00 0.00│x│=│ _0.01│ +│ 1.00 0.63 0.39 0.25 0.16 0.10│ │ │ 0.61│ +│ 1.00 1.26 1.58 1.98 2.49 3.13│ │ │ 0.91│ +│ 1.00 1.88 3.55 6.70 12.62 23.80│ │ │ 0.99│ +│ 1.00 2.51 6.32 15.88 39.90100.28│ │ │ 0.60│ +│ 1.00 3.14 9.87 31.01 97.41306.02│ │ │ 0.02│ +└────────────────────────────────────┴─┴─┴──────┘ + + f QUINTIC_COEFFICIENTS=: NOISY_SINES %. A NB. %. solves the linear system + _0.01 1.71 _1.88 1.48 _0.58 0.08 + + quintic=: QUINTIC_COEFFICIENTS&p. NB. verb to evaluate the polynomial + + NB. %. also solves the least squares fit for overdetermined system + quadratic=: (NOISY_SINES %. (^/ i.@:3:) RADIANS)&p. NB. verb to evaluate quadratic. + quadratic +_0.0200630695393961729 1.26066877804926536 _0.398275112136019516&p. + + NB. The quintic is agrees with the noisy data, as it should + f@:(NOISY_SINES ,. sin ,. quadratic ,. quintic) RADIANS + _0.01 0.00 _0.02 _0.01 + 0.61 0.59 0.61 0.61 + 0.91 0.95 0.94 0.91 + 0.99 0.95 0.94 0.99 + 0.60 0.59 0.63 0.60 + 0.02 0.00 0.01 0.02 + + f MID_POINTS=: (+ -:@:(-/@:(2&{.)))RADIANS + _0.31 0.31 0.94 1.57 2.20 2.83 + + f@:(sin ,. quadratic ,. quintic) MID_POINTS + _0.31 _0.46 _0.79 + 0.31 0.34 0.38 + 0.81 0.81 0.77 + 1.00 0.98 1.00 + 0.81 0.83 0.86 + 0.31 0.36 0.27 diff --git a/Task/Gaussian-elimination/Julia/gaussian-elimination.julia b/Task/Gaussian-elimination/Julia/gaussian-elimination.julia new file mode 100644 index 0000000000..65a9d2a328 --- /dev/null +++ b/Task/Gaussian-elimination/Julia/gaussian-elimination.julia @@ -0,0 +1 @@ +x = A \ b diff --git a/Task/Gaussian-elimination/MATLAB/gaussian-elimination.m b/Task/Gaussian-elimination/MATLAB/gaussian-elimination.m new file mode 100644 index 0000000000..897383e10d --- /dev/null +++ b/Task/Gaussian-elimination/MATLAB/gaussian-elimination.m @@ -0,0 +1,70 @@ +function [ x ] = GaussElim( A, b) + +% Ensures A is n by n +sz = size(A); +if sz(1)~=sz(2) + fprintf('A is not n by n\n'); + clear x; + return; +end + +n = sz(1); + +% Ensures b is n x 1. +if n~=sz(1) + fprintf('b is not 1 by n.\n'); + return +end + +x = zeros(n,1); +aug = [A b]; +tempmatrix = aug; + +for i=2:sz(1) + + + % Find maximum of row and divide by the maximum + tempmatrix(1,:) = tempmatrix(1,:)/max(tempmatrix(1,:)); + + % Finds the maximum in column + temp = find(abs(tempmatrix) - max(abs(tempmatrix(:,1)))); + if length(temp)>2 + for j=1:length(temp)-1 + if j~=temp(j) + maxi = j; %maxi = column number of maximum + break; + end + end + else % length(temp)==2 + maxi=1; + end + + % Row swap if maxi is not 1 + if maxi~=1 + temp = tempmatrix(maxi,:); + tempmatrix(maxi,:) = tempmatrix(1,:); + tempmatrix(1,:) = temp; + end + + % Row reducing + for j=2:length(tempmatrix)-1 + tempmatrix(j,:) = tempmatrix(j,:)-tempmatrix(j,1)/tempmatrix(1,1)*tempmatrix(1,:); + if tempmatrix(j,j)==0 || isnan(tempmatrix(j,j)) || abs(tempmatrix(j,j))==Inf + fprintf('Error: Matrix is singular.\n'); + clear x; + return + end + end + aug(i-1:end,i-1:end) = tempmatrix; + + % Decrease matrix size + tempmatrix = tempmatrix(2:end,2:end); +end + +% Backwards Substitution +x(end) = aug(end,end)/aug(end,end-1); +for i=n-1:-1:1 + x(i) = (aug(i,end)-dot(aug(i,1:end-1),x))/aug(i,i); +end + +end diff --git a/Task/Gaussian-elimination/Mathematica/gaussian-elimination.math b/Task/Gaussian-elimination/Mathematica/gaussian-elimination.math new file mode 100644 index 0000000000..dd2a4c0cf3 --- /dev/null +++ b/Task/Gaussian-elimination/Mathematica/gaussian-elimination.math @@ -0,0 +1 @@ +GaussianElimination[A_?MatrixQ, b_?VectorQ] := Last /@ RowReduce[Flatten /@ Transpose[{A, b}]] diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml new file mode 100644 index 0000000000..7785cf88e2 --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml @@ -0,0 +1,28 @@ +module Array = struct + include Array + (* Computes: f a.(0) + f a.(1) + ... where + is 'g'. *) + let foldmap g f a = + let n = Array.length a in + let rec aux acc i = + if i >= n then acc else aux (g acc (f a.(i))) (succ i) + in aux (f a.(0)) 1 + + (* like the stdlib fold_left, but also provides index to f *) + let foldi_left f x a = + let r = ref x in + for i = 0 to length a - 1 do + r := f i !r (unsafe_get a i) + done; + !r +end + +let foldmap_range g f (a,b) = + let rec aux acc n = + let n = succ n in + if n > b then acc else aux (g acc (f n)) n + in aux (f a) a + +let fold_range f init (a,b) = + let rec aux acc n = + if n > b then acc else aux (f acc n) (succ n) + in aux init a diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml new file mode 100644 index 0000000000..d3da69e497 --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml @@ -0,0 +1,38 @@ +(* Some less-general support functions for 'solve'. *) +let swap_elem m i j = let x = m.(i) in m.(i) <- m.(j); m.(j) <- x +let maxtup a b = if (snd a) > (snd b) then a else b +let augmented_matrix m b = + Array.(init (length m) ( fun i -> append m.(i) [|b.(i)|] )) + +(* Solve Ax=b for x, using gaussian elimination with scaled partial pivot, + * and then back-substitution of the resulting row-echelon matrix. *) +let solve m b = + let n = Array.length m in + let n' = pred n in (* last index = n-1 *) + let s = Array.(map (foldmap max abs_float) m) in (* scaling vector *) + let a = augmented_matrix m b in + + for k = 0 to pred n' do + (* Scaled partial pivot, to preserve precision *) + let pair i = (i, abs_float a.(i).(k) /. s.(i)) in + let i_max,v = foldmap_range maxtup pair (k,n') in + if v < epsilon_float then failwith "Matrix is singular."; + swap_elem a k i_max; + swap_elem s k i_max; + + (* Eliminate one column *) + for i = succ k to n' do + let tmp = a.(i).(k) /. a.(k).(k) in + for j = succ k to n do + a.(i).(j) <- a.(i).(j) -. tmp *. a.(k).(j); + done + done + done; + + (* Backward substitution; 'b' is in the 'nth' column of 'a' *) + let x = Array.copy b in (* just a fresh array of the right size and type *) + for i = n' downto 0 do + let minus_dprod t j = t -. x.(j) *. a.(i).(j) in + x.(i) <- fold_range minus_dprod a.(i).(n) (i+1,n') /. a.(i).(i); + done; + x diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml new file mode 100644 index 0000000000..975a6eba55 --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml @@ -0,0 +1,8 @@ +let a = + [| [| 1.00; 0.00; 0.00; 0.00; 0.00; 0.00 |]; + [| 1.00; 0.63; 0.39; 0.25; 0.16; 0.10 |]; + [| 1.00; 1.26; 1.58; 1.98; 2.49; 3.13 |]; + [| 1.00; 1.88; 3.55; 6.70; 12.62; 23.80 |]; + [| 1.00; 2.51; 6.32; 15.88; 39.90; 100.28 |]; + [| 1.00; 3.14; 9.87; 31.01; 97.41; 306.02 |] |] +let b = [| -0.01; 0.61; 0.91; 0.99; 0.60; 0.02 |] diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml new file mode 100644 index 0000000000..1aa74fbc3c --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml @@ -0,0 +1,4 @@ +# let x = solve a b;; +val x : float array = +[|-0.0100000000000000991; 1.60279039450210536; -1.61320305990553226; + 1.24549412137140547; -0.490989719584644546; 0.0657606961752301433|] diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml new file mode 100644 index 0000000000..d0b4f4a341 --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml @@ -0,0 +1,8 @@ +let mul m v = + Array.mapi (fun i u -> + Array.foldi_left (fun j sum uj -> + sum +. uj *. v.(j) + ) 0. u + ) m + +let sub u v = Array.mapi (fun i e -> e -. v.(i)) u diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml new file mode 100644 index 0000000000..d8c6f7e7bb --- /dev/null +++ b/Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml @@ -0,0 +1,4 @@ +# let residual = sub b (mul a x);; +val residual : float array = + [|9.8879238130678e-17; 1.11022302462515654e-16; 2.22044604925031308e-16; + 8.88178419700125232e-16; -5.5511151231257827e-16; 4.26741975090294545e-16|] diff --git a/Task/Gaussian-elimination/PARI-GP/gaussian-elimination.pari b/Task/Gaussian-elimination/PARI-GP/gaussian-elimination.pari new file mode 100644 index 0000000000..186b0b3a4f --- /dev/null +++ b/Task/Gaussian-elimination/PARI-GP/gaussian-elimination.pari @@ -0,0 +1 @@ +matsolve(A,B) diff --git a/Task/Gaussian-elimination/PHP/gaussian-elimination.php b/Task/Gaussian-elimination/PHP/gaussian-elimination.php new file mode 100644 index 0000000000..ae5b91467b --- /dev/null +++ b/Task/Gaussian-elimination/PHP/gaussian-elimination.php @@ -0,0 +1,75 @@ +function swap_rows(&$a, &$b, $r1, $r2) +{ + if ($r1 == $r2) return; + + $tmp = $a[$r1]; + $a[$r1] = $a[$r2]; + $a[$r2] = $tmp; + + $tmp = $b[$r1]; + $b[$r1] = $b[$r2]; + $b[$r2] = $tmp; +} + +function gauss_eliminate($A, $b, $N) +{ + for ($col = 0; $col < $N; $col++) + { + $j = $col; + $max = $A[$j][$j]; + + for ($i = $col + 1; $i < $N; $i++) + { + $tmp = abs($A[$i][$col]); + if ($tmp > $max) + { + $j = $i; + $max = $tmp; + } + } + + swap_rows($A, $b, $col, $j); + + for ($i = $col + 1; $i < $N; $i++) + { + $tmp = $A[$i][$col] / $A[$col][$col]; + for ($j = $col + 1; $j < $N; $j++) + { + $A[$i][$j] -= $tmp * $A[$col][$j]; + } + $A[$i][$col] = 0; + $b[$i] -= $tmp * $b[$col]; + } + } + $x = array(); + for ($col = $N - 1; $col >= 0; $col--) + { + $tmp = $b[$col]; + for ($j = $N - 1; $j > $col; $j--) + { + $tmp -= $x[$j] * $A[$col][$j]; + } + $x[$col] = $tmp / $A[$col][$col]; + } + return $x; +} + +function test_gauss() +{ + $a = array( + array(1.00, 0.00, 0.00, 0.00, 0.00, 0.00), + array(1.00, 0.63, 0.39, 0.25, 0.16, 0.10), + array(1.00, 1.26, 1.58, 1.98, 2.49, 3.13), + array(1.00, 1.88, 3.55, 6.70, 12.62, 23.80), + array(1.00, 2.51, 6.32, 15.88, 39.90, 100.28), + array(1.00, 3.14, 9.87, 31.01, 97.41, 306.02) + ); + $b = array( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ); + + $x = gauss_eliminate($a, $b, 6); + + ksort($x); + print_r($x); +} + +test_gauss(); diff --git a/Task/Gaussian-elimination/PL-I/gaussian-elimination.pli b/Task/Gaussian-elimination/PL-I/gaussian-elimination.pli new file mode 100644 index 0000000000..ad36a157f6 --- /dev/null +++ b/Task/Gaussian-elimination/PL-I/gaussian-elimination.pli @@ -0,0 +1,71 @@ +Solve: procedure options (main); /* 11 January 2014 */ + + declare n fixed binary; + put ('Program to solve n simultaneous equations of the form Ax = b. Please type n:' ); + get (n); + +begin; + declare (A(n, n), b(n), x(n)) float(18); + declare (SA(n,n), Sb(n)) float (18); + declare i fixed binary; + + put skip list ('Please type A:'); + get (a); + put skip list ('Please type the right-hand sides, b:'); + get (b); + + SA = A; Sb = b; + + put skip list ('The equations are:'); + do i = 1 to n; + put skip edit (A(i,*), b(i)) (f(5), x(1)); + end; + + call Gauss_elimination (A, b); + + call Backward_substitution (A, b, x); + + put skip list ('Solutions:'); put skip data (x); + + /* Check solutions: */ + put skip list ('Residuals:'); + do i = 1 to n; + put skip list (sum(SA(i,*) * x(*)) - Sb(i)); + end; +end; + +Gauss_elimination: procedure (A, b) options (reorder); /* Triangularise */ + declare (A(*,*), b(*)) float(18); + declare n fixed binary initial (hbound(A, 1)); + declare (i, j, k) fixed binary; + declare t float(18); + + do j = 1 to n; + do i = j+1 to n; /* For each of the rows beneath the current (pivot) row. */ + t = A(j,j) / A(i,j); + do k = j+1 to n; /* Subtract a multiple of row i from row j. */ + A(i,k) = A(j,k) - t*A(i,k); + end; + b(i) = b(j) - t*b(i); /* ... and the right-hand side. */ + end; + end; +end Gauss_elimination; + +Backward_substitution: procedure (A, b, x) options (reorder); + declare (A(*,*), b(*), x(*)) float(18); + declare t float(18); + declare n fixed binary initial (hbound(A, 1)); + declare (i, j) fixed binary; + + x(n) = b(n) / a(n,n); + + do j = n-1 to 1 by -1; + t = 0; + do i = j+1 to n; + t = t + a(j,i)*x(i); + end; + x(j) = (b(j) - t) / a(j,j); + end; +end Backward_substitution; + +end Solve; diff --git a/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 b/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 new file mode 100644 index 0000000000..f3bc86d02d --- /dev/null +++ b/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 @@ -0,0 +1,54 @@ +sub mat_elem(@a, $y, $x, $n) is rw { @a[ $y * $n + $x ] } +sub swap_row(@a, @b, $r1, $r2, $n) { + return if $r1 == $r2; + for ^$n -> $i { + ( + mat_elem(@a, $r1, $i, $n), + mat_elem(@a, $r2, $i, $n) + ).=reverse; + } + @b[$r1, $r2].=reverse; +} + +sub gauss_eliminate(@a, @b, $n) { + sub A($y, $x) is rw { mat_elem(@a, $y, $x, $n) } + my ($i, $j, $col, $row, $max_row, $dia); + my ($max, $tmp); + for ^$n -> $dia { + for $dia ^..^ $n -> $row { + swap_row @a, @b, $dia, + max(:by({ abs(A($_, $dia)) }), $dia ^..^ $n), + $n; + $tmp = A($row, $dia) / A($dia, $dia); + for $dia ^..^ $n -> $col { + A($row, $col) -= $tmp * A($dia, $col); + } + A($row, $dia) = 0; + @b[$row] -= $tmp * @b[$dia]; + } + } + my @x; + for $n - 1, $n - 2 ... 0 -> $row { + $tmp = @b[$row]; + for $n - 1, $n - 2 ...^ $row -> $j { + $tmp -= @x[$j] * A($row, $j); + } + @x[$row] = $tmp / A($row, $row); + } + return @x; +} + +sub MAIN { + my @a = < + 1.00 0.00 0.00 0.00 0.00 0.00 + 1.00 0.63 0.39 0.25 0.16 0.10 + 1.00 1.26 1.58 1.98 2.49 3.13 + 1.00 1.88 3.55 6.70 12.62 23.80 + 1.00 2.51 6.32 15.88 39.90 100.28 + 1.00 3.14 9.87 31.01 97.41 306.02 + >; + my @b = < + -0.01 0.61 0.91 0.99 0.60 0.02 + >; + .say for gauss_eliminate(@a, @b, 6); +} diff --git a/Task/Gaussian-elimination/Perl/gaussian-elimination.pl b/Task/Gaussian-elimination/Perl/gaussian-elimination.pl new file mode 100644 index 0000000000..b042315dc1 --- /dev/null +++ b/Task/Gaussian-elimination/Perl/gaussian-elimination.pl @@ -0,0 +1,9 @@ +use Math::Matrix; +my $a = Math::Matrix->new([0,1,0], + [0,0,1], + [2,0,1]); +my $b = Math::Matrix->new([1], + [2], + [4]); +my $x = $a->concat($b)->solve; +print $x; diff --git a/Task/Gaussian-elimination/Python/gaussian-elimination.py b/Task/Gaussian-elimination/Python/gaussian-elimination.py new file mode 100644 index 0000000000..1673cd0c20 --- /dev/null +++ b/Task/Gaussian-elimination/Python/gaussian-elimination.py @@ -0,0 +1,96 @@ +# The 'gauss' function takes two matrices, 'a' and 'b', with 'a' square, and it return the determinant of 'a' and a matrix 'x' such that a*x = b. +# If 'b' is the identity, then 'x' is the inverse of 'a'. + +import copy +from fractions import Fraction + +def gauss(a, b): + a = copy.deepcopy(a) + b = copy.deepcopy(b) + n = len(a) + p = len(b[0]) + det = 1 + for i in range(n - 1): + k = i + for j in range(i + 1, n): + if abs(a[j][i]) > abs(a[k][i]): + k = j + if k != i: + a[i], a[k] = a[k], a[i] + b[i], b[k] = b[k], b[i] + det = -det + + for j in range(i + 1, n): + t = a[j][i]/a[i][i] + for k in range(i + 1, n): + a[j][k] -= t*a[i][k] + for k in range(p): + b[j][k] -= t*b[i][k] + + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + t = a[i][j] + for k in range(p): + b[i][k] -= t*b[j][k] + t = 1/a[i][i] + det *= a[i][i] + for j in range(p): + b[i][j] *= t + return det, b + +def zeromat(p, q): + return [[0]*q for i in range(p)] + +def matmul(a, b): + n, p = len(a), len(a[0]) + p1, q = len(b), len(b[0]) + if p != p1: + raise ValueError("Incompatible dimensions") + c = zeromat(n, q) + for i in range(n): + for j in range(q): + c[i][j] = sum(a[i][k]*b[k][j] for k in range(p)) + return c + + +def mapmat(f, a): + return [list(map(f, v)) for v in a] + +def ratmat(a): + return mapmat(Fraction, a) + +# As an example, compute the determinant and inverse of 3x3 magic square + +a = [[2, 9, 4], [7, 5, 3], [6, 1, 8]] +b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] +det, c = gauss(a, b) + +det +-360.0 + +c +[[-0.10277777777777776, 0.18888888888888888, -0.019444444444444438], +[0.10555555555555554, 0.02222222222222223, -0.061111111111111116], +[0.0638888888888889, -0.14444444444444446, 0.14722222222222223]] + +# Check product +matmul(a, c) +[[1.0, 0.0, 0.0], [5.551115123125783e-17, 1.0, 0.0], +[1.1102230246251565e-16, -2.220446049250313e-16, 1.0]] + +# Same with fractions, so the result is exact + +det, c = gauss(ratmat(a), ratmat(b)) + +det +Fraction(-360, 1) + +c +[[Fraction(-37, 360), Fraction(17, 90), Fraction(-7, 360)], +[Fraction(19, 180), Fraction(1, 45), Fraction(-11, 180)], +[Fraction(23, 360), Fraction(-13, 90), Fraction(53, 360)]] + +matmul(a, c) +[[Fraction(1, 1), Fraction(0, 1), Fraction(0, 1)], +[Fraction(0, 1), Fraction(1, 1), Fraction(0, 1)], +[Fraction(0, 1), Fraction(0, 1), Fraction(1, 1)]] diff --git a/Task/Gaussian-elimination/README b/Task/Gaussian-elimination/README new file mode 100644 index 0000000000..76fbc5d283 --- /dev/null +++ b/Task/Gaussian-elimination/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Gaussian_elimination diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-1.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-1.rexx new file mode 100644 index 0000000000..440caf5bb0 --- /dev/null +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-1.rexx @@ -0,0 +1,79 @@ +/* REXX --------------------------------------------------------------- +* 07.08.2014 Walter Pachl translated from PL/I) +*--------------------------------------------------------------------*/ + Numeric Digits 20 + Parse Arg t + n=3 + Parse Value '1 2 3 14' With a.1.1 a.1.2 a.1.3 b.1 + Parse Value '2 1 3 13' With a.2.1 a.2.2 a.2.3 b.2 + Parse Value '3 -2 -1 -4' With a.3.1 a.3.2 a.3.3 b.3 + If t=6 Then Do + n=6 + Parse Value '1.00 0.00 0.00 0.00 0.00 0.00 ' With a.1.1 a.1.2 a.1.3 a.1.4 a.1.5 a.1.6 . + Parse Value '1.00 0.63 0.39 0.25 0.16 0.10 ' With a.2.1 a.2.2 a.2.3 a.2.4 a.2.5 a.2.6 . + Parse Value '1.00 1.26 1.58 1.98 2.49 3.13 ' With a.3.1 a.3.2 a.3.3 a.3.4 a.3.5 a.3.6 . + Parse Value '1.00 1.88 3.55 6.70 12.62 23.80 ' With a.4.1 a.4.2 a.4.3 a.4.4 a.4.5 a.4.6 . + Parse Value '1.00 2.51 6.32 15.88 39.90 100.28' With a.5.1 a.5.2 a.5.3 a.5.4 a.5.5 a.5.6 . + Parse Value '1.00 3.14 9.87 31.01 97.41 306.02' With a.6.1 a.6.2 a.6.3 a.6.4 a.6.5 a.6.6 . + Parse Value '-0.01 0.61 0.91 0.99 0.60 0.02' With b.1 b.2 b.3 b.4 b.5 b.6 . + End + Do i=1 To n + Do j=1 To n + sa.i.j=a.i.j + End + sb.i=b.i + End + Say 'The equations are:' + do i = 1 to n; + ol='' + Do j=1 To n + ol=ol format(a.i.j,4,4) + End + ol=ol' 'format(b.i,4,4) + Say ol + end + + call Gauss_elimination + + call Backward_substitution + + Say 'Solutions:' + Do i=1 To n + Say 'x('i')='||x.i + End + + /* Check solutions: */ + Say 'Residuals:' + do i = 1 to n + res=0 + Do j=1 To n + res=res+(sa.i.j*x.j) + End + res=res-sb.i + Say 'res('i')='res + End + +Exit + +Gauss_elimination: + do j = 1 to n + do i = j+1 to n /* For each of the rows beneath the current (pivot) row. */ + t = a.j.j / a.i.j + do k = j+1 to n /* Subtract a multiple of row i from row j. */ + a.i.k = a.j.k - t*a.i.k + end + b.i = b.j - t*b.i /* ... and the right-hand side. */ + end + end + Return + +Backward_substitution: + x.n = b.n / a.n.n + do j = n-1 to 1 by -1 + t = 0 + do i = j+1 to n + t = t + a.j.i*x.i + end + x.j = (b.j - t) / a.j.j + end + Return diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx new file mode 100644 index 0000000000..ba111c7c8a --- /dev/null +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx @@ -0,0 +1,35 @@ +/*REXX pgm solves Ax=b with Gaussian elimination &backwards substitution*/ +parse arg iFID .; if iFID=='' then iFID='GAUSS_E.DAT' + + do files=1 while lines(iFID)\==0; #=0 /*read equation sets*/ + numeric digits 200 /*reduces rounding. */ + do $=1 while lines(iFID)\==0 /*process equation. */ + z=linein(iFID); if z='' then leave /*Blank line? e─o─d.*/ + if $==1 then do; say; say center(' equations ',75,'▒'); say; end + say z /*show an equation. */ + if left(space(z),1)=='*' then iterate /*ignore comments. */ + #=#+1; n=words(z)-1 /*assign equation #s*/ + do e=1 for n; a.#.e=word(z,e); end /*e*/ /*process the A #s.*/ + b.#=word(z,n+1) /* " " B #.*/ + end /*$*/ + if #==0 then iterate /*extra blank line? */ + call Gauss_elimination /*invoke Gauss elim.*/ + say; say center('solution',75,'═'); say /* [↓] show solution*/ + numeric digits 8; pad=left('',30) /*only show 8 digits*/ + do s=1 for n; say pad 'x['s"] = " left('', x.s>=0) x.s/1; end + end /*files*/ + +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GAUSS_ELIMINATION subroutine────────*/ +Gauss_elimination: do j=1 for n; jp=j+1 + do i=jp to n; _=a.j.j/a.i.j + do k=jp to n; a.i.k=a.j.k-_*a.i.k; end /*k*/ + b.i=b.j-_*b.i + end /*i*/ + end /*j*/ +x.n=b.n/a.n.n + do j=n-1 to 1 by -1; _=0 + do i=j+1 to n; _=_+a.j.i*x.i; end /*i*/ + x.j=(b.j-_)/a.j.j + end /*j*/ /* [↑] backwards substitution.*/ +return diff --git a/Task/Gaussian-elimination/Racket/gaussian-elimination-1.rkt b/Task/Gaussian-elimination/Racket/gaussian-elimination-1.rkt new file mode 100644 index 0000000000..d599bb7152 --- /dev/null +++ b/Task/Gaussian-elimination/Racket/gaussian-elimination-1.rkt @@ -0,0 +1,13 @@ +#lang racket +(require math/matrix) +(define A + (matrix [[1.00 0.00 0.00 0.00 0.00 0.00] + [1.00 0.63 0.39 0.25 0.16 0.10] + [1.00 1.26 1.58 1.98 2.49 3.13] + [1.00 1.88 3.55 6.70 12.62 23.80] + [1.00 2.51 6.32 15.88 39.90 100.28] + [1.00 3.14 9.87 31.01 97.41 306.02]])) + +(define b (col-matrix [-0.01 0.61 0.91 0.99 0.60 0.02])) + +(matrix-solve A b) diff --git a/Task/Gaussian-elimination/Racket/gaussian-elimination-2.rkt b/Task/Gaussian-elimination/Racket/gaussian-elimination-2.rkt new file mode 100644 index 0000000000..4fd38dda44 --- /dev/null +++ b/Task/Gaussian-elimination/Racket/gaussian-elimination-2.rkt @@ -0,0 +1,8 @@ +# diff --git a/Task/Gaussian-elimination/Ruby/gaussian-elimination.rb b/Task/Gaussian-elimination/Ruby/gaussian-elimination.rb new file mode 100644 index 0000000000..2473aca1fb --- /dev/null +++ b/Task/Gaussian-elimination/Ruby/gaussian-elimination.rb @@ -0,0 +1,18 @@ +require 'bigdecimal/ludcmp' +include LUSolve + +BigDecimal::limit(30) + +a = [1.00, 0.00, 0.00, 0.00, 0.00, 0.00, + 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, + 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, + 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, + 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, + 1.00, 3.14, 9.87, 31.01, 97.41, 306.02].map{|i|BigDecimal(i,16)} +b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02].map{|i|BigDecimal(i,16)} + +n = 6 +zero = BigDecimal("0.0") +one = BigDecimal("1.0") + +lusolve(a, b, ludecomp(a, n, zero,one), zero).each{|v| puts v.to_s('F')[0..20]} diff --git a/Task/Gaussian-elimination/Tcl/gaussian-elimination.tcl b/Task/Gaussian-elimination/Tcl/gaussian-elimination.tcl new file mode 100644 index 0000000000..96eb07d02f --- /dev/null +++ b/Task/Gaussian-elimination/Tcl/gaussian-elimination.tcl @@ -0,0 +1,12 @@ +package require math::linearalgebra + +set A { + {1.00 0.00 0.00 0.00 0.00 0.00} + {1.00 0.63 0.39 0.25 0.16 0.10} + {1.00 1.26 1.58 1.98 2.49 3.13} + {1.00 1.88 3.55 6.70 12.62 23.80} + {1.00 2.51 6.32 15.88 39.90 100.28} + {1.00 3.14 9.87 31.01 97.41 306.02} +} +set b {-0.01 0.61 0.91 0.99 0.60 0.02} +puts -nonewline [math::linearalgebra::show [math::linearalgebra::solveGauss $A $b] "%.2f"] diff --git a/Task/Generate-Chess960-starting-position/00DESCRIPTION b/Task/Generate-Chess960-starting-position/00DESCRIPTION new file mode 100644 index 0000000000..67e0a4a615 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/00DESCRIPTION @@ -0,0 +1,12 @@ +'''[[wp:Chess960|Chess960]]''' is a variant of chess created by world champion [[wp:Bobby Fisher|Bobby Fisher]]. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: + +* as in the standard chess game, all eight white pawns must be placed on the second rank. +* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: +** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) +** the King must be between two rooks (with any number of other pieces between them all) +* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) + +With those constraints there are 960 possible starting positions, thus the name of the variant. + +;Task: +The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with [[wp:Chess symbols in Unicode|Chess symbols in Unicode: ♔♕♖♗♘]] or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight. diff --git a/Task/Generate-Chess960-starting-position/AutoHotkey/generate-chess960-starting-position.ahk b/Task/Generate-Chess960-starting-position/AutoHotkey/generate-chess960-starting-position.ahk new file mode 100644 index 0000000000..0a67b9df06 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/AutoHotkey/generate-chess960-starting-position.ahk @@ -0,0 +1,33 @@ +Loop, 5 + Out .= Chess960() "`n" +MsgBox, % RTrim(Out, "`n") + +Chess960() { + P := {} + P[K := Rand(2, 7)] := Chr(0x2654) ; King + P[Rand(1, K - 1)] := Chr(0x2656) ; Rook 1 + P[Rand(K + 1, 8)] := Chr(0x2656) ; Rook 2 + Loop, 8 + Remaining .= P[A_Index] ? "" : A_Index "`n" + Sort, Remaining, Random N + P[Bishop1 := SubStr(Remaining, 1, 1)] := Chr(0x2657) ; Bishop 1 + Remaining := SubStr(Remaining, 3) + Loop, Parse, Remaining, `n + if (Mod(Bishop1 - A_LoopField, 2)) + Odd .= A_LoopField "`n" + else + Even .= A_LoopField "`n" + X := StrSplit(Odd Even, "`n") + P[X.1] := Chr(0x2657) ; Bishop 2 + P[X.2] := Chr(0x2655) ; Queen + P[X.3] := Chr(0x2658) ; Knight 1 + P[X.4] := Chr(0x2658) ; Knight 2 + for Key, Val in P + Out .= Val + return Out +} + +Rand(Min, Max) { + Random, n, Min, Max + return n +} diff --git a/Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp b/Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp new file mode 100644 index 0000000000..33fcdfa69f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +using namespace std; +class chess960 +{ +public: + void generate( int c ) + { + for( int x = 0; x < c; x++ ) + cout << startPos() << "\n"; + } + +private: + string startPos() + { + char p[8]; memset( p, 0, 8 ); + int b1, b2; bool q; + + // bishops + while( 1 ) + { + b1 = rand() % 8; b2 = rand() % 8; + if( !( b1 & 1 ) && b2 & 1 ) break; + } + p[b1] = 'B'; p[b2] = 'B'; + + // queen, knight, knight + q = false; + for( int x = 0; x < 3; x++ ) + { + do + { b1 = rand() % 8; } + while( p[b1] ); + if( !q ) + { p[b1] = 'Q'; q = true; } + else p[b1] = 'N'; + } + + // rook king rook + q = false; + for( int x = 0; x < 3; x++ ) + { + int a = 0; + for( ; a < 8; a++ ) + if( !p[a] ) break; + + if( !q ) + { p[a] = 'R'; q = true; } + else + { p[a] = 'K'; q = false; } + } + + string s; + for( int x = 0; x < 8; x++ ) + s.append( 1, p[x] ); + + return s; + } +}; + +int main( int argc, char* argv[] ) +{ + srand( time( NULL ) ); + chess960 c; + c.generate( 10 ); + cout << "\n\n"; + return system( "pause" ); +} diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d new file mode 100644 index 0000000000..a0e9db973f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d @@ -0,0 +1,13 @@ +void main() { + import std.stdio, std.range, std.algorithm, std.string, permutations2; + + const pieces = "KQRrBbNN"; + alias I = indexOf; + auto starts = pieces.dup.permutations.filter!(p => + I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop constraint. + // King constraint. + ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) || + (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r')))) + .map!toUpper.array.sort().uniq; + writeln(starts.walkLength, "\n", starts.front); +} diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d new file mode 100644 index 0000000000..420a99b0c8 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d @@ -0,0 +1,11 @@ +void main() { + import std.stdio, std.regex, std.range, std.algorithm, permutations2; + + immutable pieces = "KQRRBBNN"; + immutable bish = r"B(|..|....|......)B"; + immutable king = r"R.*K.*R"; + auto starts3 = permutations(pieces.dup) + .filter!(p => p.match(bish) && p.match(king)) + .array.sort().uniq; + writeln(starts3.walkLength, "\n", starts3.front); +} diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d new file mode 100644 index 0000000000..5885e3bb3d --- /dev/null +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d @@ -0,0 +1,13 @@ +void main() { + import std.stdio, std.random, std.array, std.range; + + // Subsequent order unchanged by insertions. + auto start = "RKR".dup; + foreach (immutable piece; "QNN") + start.insertInPlace(uniform(0, start.length), piece); + + immutable bishpos = uniform(0, start.length); + start.insertInPlace(bishpos, 'B'); + start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B'); + start.writeln; +} diff --git a/Task/Generate-Chess960-starting-position/Go/generate-chess960-starting-position.go b/Task/Generate-Chess960-starting-position/Go/generate-chess960-starting-position.go new file mode 100644 index 0000000000..1bab9eb0d0 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Go/generate-chess960-starting-position.go @@ -0,0 +1,63 @@ +package main + +import ( + "fmt" + "math/rand" +) + +type symbols struct{ k, q, r, b, n rune } + +var A = symbols{'K', 'Q', 'R', 'B', 'N'} +var W = symbols{'♔', '♕', '♖', '♗', '♘'} +var B = symbols{'♚', '♛', '♜', '♝', '♞'} + +var krn = []string{ + "nnrkr", "nrnkr", "nrknr", "nrkrn", + "rnnkr", "rnknr", "rnkrn", + "rknnr", "rknrn", + "rkrnn"} + +func (sym symbols) chess960(id int) string { + var pos [8]rune + q, r := id/4, id%4 + pos[r*2+1] = sym.b + q, r = q/4, q%4 + pos[r*2] = sym.b + q, r = q/6, q%6 + for i := 0; ; i++ { + if pos[i] != 0 { + continue + } + if r == 0 { + pos[i] = sym.q + break + } + r-- + } + i := 0 + for _, f := range krn[q] { + for pos[i] != 0 { + i++ + } + switch f { + case 'k': + pos[i] = sym.k + case 'r': + pos[i] = sym.r + case 'n': + pos[i] = sym.n + } + } + return string(pos[:]) +} + +func main() { + fmt.Println(" ID Start position") + for _, id := range []int{0, 518, 959} { + fmt.Printf("%3d %s\n", id, A.chess960(id)) + } + fmt.Println("\nRandom") + for i := 0; i < 5; i++ { + fmt.Println(W.chess960(rand.Intn(960))) + } +} diff --git a/Task/Generate-Chess960-starting-position/Haskell/generate-chess960-starting-position.hs b/Task/Generate-Chess960-starting-position/Haskell/generate-chess960-starting-position.hs new file mode 100644 index 0000000000..bbd57d6e72 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Haskell/generate-chess960-starting-position.hs @@ -0,0 +1,15 @@ +import Data.List +import qualified Data.Set as Set + +data Piece = K | Q | R | B | N deriving (Eq, Ord, Show) + +isChess960 :: [Piece] -> Bool +isChess960 rank = + (odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB + where + Just king = findIndex (== K) rank + [rookA, rookB] = findIndices (== R) rank + +main :: IO () +main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList + . filter isChess960 $ permutations [R,N,B,Q,K,B,N,R] diff --git a/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-1.j b/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-1.j new file mode 100644 index 0000000000..b87fa67647 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-1.j @@ -0,0 +1,11 @@ +row0=: u: 9812+2}.5|i.10 +king=: u:9812 +rook=: u:9814 +bish=: u:9815 +pos=: I.@e. +bishok=: 1=2+/ .| pos&bish +rookok=: pos&rook -: (<./,>./)@pos&(rook,king) +ok=: bishok*rookok +perm=: A.&i.~ ! +valid=: (#~ ok"1) ~.row0{"1~perm 8 +gen=: valid {~ ? bind 960 diff --git a/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-2.j b/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-2.j new file mode 100644 index 0000000000..2a93b11b02 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/J/generate-chess960-starting-position-2.j @@ -0,0 +1,8 @@ + gen'' +♘♗♖♔♗♕♖♘ + gen'' +♗♘♘♗♖♔♖♕ + gen'' +♖♗♔♘♘♕♗♖ + gen'' +♖♔♕♗♗♘♖♘ diff --git a/Task/Generate-Chess960-starting-position/Java/generate-chess960-starting-position.java b/Task/Generate-Chess960-starting-position/Java/generate-chess960-starting-position.java new file mode 100644 index 0000000000..aa25c68da5 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Java/generate-chess960-starting-position.java @@ -0,0 +1,27 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Chess960{ + private static List pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); + + public static List generateFirstRank(){ + do{ + Collections.shuffle(pieces); + }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); //List.toString adds some human stuff, remove that + + return pieces; + } + + private static boolean check(String rank){ + if(!rank.matches(".*R.*K.*R.*")) return false; //king between rooks + if(!rank.matches(".*B(..|....|......|)B.*")) return false; //all possible ways bishops can be placed + return true; + } + + public static void main(String[] args){ + for(int i = 0; i < 10; i++){ + System.out.println(generateFirstRank()); + } + } +} diff --git a/Task/Generate-Chess960-starting-position/Objeck/generate-chess960-starting-position.objeck b/Task/Generate-Chess960-starting-position/Objeck/generate-chess960-starting-position.objeck new file mode 100644 index 0000000000..b29f24b755 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Objeck/generate-chess960-starting-position.objeck @@ -0,0 +1,70 @@ +class Chess960 { + function : Main(args : String[]) ~ Nil { + Generate(10); + } + + function : Generate(c : Int) ~ Nil { + for(x := 0; x < c; x += 1;) { + StartPos()->PrintLine(); + }; + } + + function : StartPos() ~ String { + p := Char->New[8]; + + # bishops + b1 : Int; b2 : Int; + while(true) { + b1 := GetPosition(); b2 := GetPosition(); + + b1c := b1 and 1; b2c := b2 and 1; + c := b1c = 0 & b2c <> 0; + if(c) { + break; + }; + }; + p[b1] := 0x2657; p[b2] := 0x2657; + + # queen, knight, knight + q := false; + for(x := 0; x < 3; x += 1;) { + do { + b1 := GetPosition(); + } while( p[b1] <> '\0'); + + if(<>q) { + p[b1] := 0x2655; q := true; + } + else { + p[b1] := 0x2658; + }; + }; + + # rook king rook + q := false; + for(x := 0; x < 3; x += 1;) { + a := 0; + while(a < 8) { + if(p[a] = '\0') { + break; + }; + a += 1; + }; + + if(<>q) { + p[a] := 0x2656; q := true; + } + else { + p[a] := 0x2654; q := false; + }; + }; + + s := ""; + for(x := 0; x < 8; x += 1;) { s->Append(p[x]); }; + return s; + } + + function : GetPosition() ~ Int { + return (Float->Random() * 1000)->As(Int) % 8; + } +} diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-1.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-1.pl6 new file mode 100644 index 0000000000..811ea8a2a5 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-1.pl6 @@ -0,0 +1,3 @@ +repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join } +s:2nd['♖'] = '♔'; +say .comb; diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-2.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-2.pl6 new file mode 100644 index 0000000000..3c4d7b2357 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-2.pl6 @@ -0,0 +1,6 @@ +constant chess960 = + map *.subst(:nth(2), /'♜'/, '♚'), + grep rx/ '♝' [..]* '♝' /, + < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.pick(*).join xx *; + +.say for chess960[^10]; diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 new file mode 100644 index 0000000000..a4fa7a4b9e --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 @@ -0,0 +1,6 @@ +constant chess960 = eager + .subst(:nth(2), /'♜'/, '♚') + if / '♝' [..]* '♝' / + for < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.uniq; + +.say for chess960; diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 new file mode 100644 index 0000000000..ff2a3d4145 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 @@ -0,0 +1,22 @@ +sub insert(@a,$p,$e) { @a[^$p], $e, @a[$p..*] } + +constant chess960 = eager gather for 0..3 -> $q { + my @q = insert <♜ ♚ ♜>, $q, '♛'; + for 0 .. @q -> $n1 { + my @n1 = insert @q, $n1, '♞'; + for $n1 ^.. @n1 -> $n2 { + my @n2 = insert @n1, $n2, '♞'; + for 0 .. @n2 -> $b1 { + my @b1 = insert @n2, $b1, '♝'; + for $b1+1, $b1+3 ...^ * > @b1 -> $b2 { + my @b2 = insert @b1, $b2, '♝'; + take @b2.join; + } + } + } + } +} + +CHECK { note "done compiling" } +note +chess960; +say chess960.pick; diff --git a/Task/Generate-Chess960-starting-position/Perl/generate-chess960-starting-position.pl b/Task/Generate-Chess960-starting-position/Perl/generate-chess960-starting-position.pl new file mode 100644 index 0000000000..b1adcd5b78 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Perl/generate-chess960-starting-position.pl @@ -0,0 +1,17 @@ +sub rnd($) { int(rand(shift)) } + +sub empties { grep !$_[0][$_], 0 .. 7 } + +sub chess960 { + my @s = (undef) x 8; + @s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/; + + for (qw/Q N N/) { + my @idx = empties \@s; + $s[$idx[rnd(@idx)]] = $_; + } + + @s[empties \@s] = qw/R K R/; + @s +} +print "@{[chess960]}\n" for 0 .. 10; diff --git a/Task/Generate-Chess960-starting-position/PicoLisp/generate-chess960-starting-position.l b/Task/Generate-Chess960-starting-position/PicoLisp/generate-chess960-starting-position.l new file mode 100644 index 0000000000..f5cacc393f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/PicoLisp/generate-chess960-starting-position.l @@ -0,0 +1,16 @@ +(load "@lib/simul.l") + +(seed (in "/dev/urandom" (rd 8))) + +(loop + (match + '(@A B @B B @C) + (shuffle '(Q B B N N 0 0 0)) ) + (NIL (bit? 1 (length @B))) ) + +(let Rkr '(R K R) + (for I (append @A '(B) @B '(B) @C) + (prin (if (=0 I) (pop 'Rkr) I)) ) + (prinl) ) + +(bye) diff --git a/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-1.py b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-1.py new file mode 100644 index 0000000000..b6702d5b04 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-1.py @@ -0,0 +1,11 @@ +>>> from itertools import permutations +>>> pieces = 'KQRrBbNN' +>>> starts = {''.join(p).upper() for p in permutations(pieces) + if p.index('B') % 2 != p.index('b') % 2 # Bishop constraint + and ( p.index('r') < p.index('K') < p.index('R') # King constraint + or p.index('R') < p.index('K') < p.index('r') ) } +>>> len(starts) +960 +>>> starts.pop() +'QNBRNKRB' +>>> diff --git a/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-2.py b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-2.py new file mode 100644 index 0000000000..0a82c50f6b --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-2.py @@ -0,0 +1,11 @@ +>>> import re +>>> pieces = 'KQRRBBNN' +>>> bish = re.compile(r'B(|..|....|......)B').search +>>> king = re.compile(r'R.*K.*R').search +>>> starts3 = {p for p in (''.join(q) for q in permutations(pieces)) + if bish(p) and king(p)} +>>> len(starts3) +960 +>>> starts3.pop() +'QRNKBNRB' +>>> diff --git a/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-3.py b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-3.py new file mode 100644 index 0000000000..110a30de79 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-3.py @@ -0,0 +1,15 @@ +from random import choice + +def random960(): + start = ['R', 'K', 'R'] # Subsequent order unchanged by insertions. + # + for piece in ['Q', 'N', 'N']: + start.insert(choice(range(len(start)+1)), piece) + # + bishpos = choice(range(len(start)+1)) + start.insert(bishpos, 'B') + start.insert(choice(range(bishpos + 1, len(start) + 1, 2)), 'B') + return start + return ''.join(start).upper() + +print(random960()) diff --git a/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-4.py b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-4.py new file mode 100644 index 0000000000..30acb104a0 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Python/generate-chess960-starting-position-4.py @@ -0,0 +1,31 @@ +from random import choice + +def generate960(): + start = ('R', 'K', 'R') # Subsequent order unchanged by insertions. + + # Insert QNN in all combinations of places + starts = {start} + for piece in ['Q', 'N', 'N']: + starts2 = set() + for s in starts: + for pos in range(len(s)+1): + s2 = list(s) + s2.insert(pos, piece) + starts2.add(tuple(s2)) + starts = starts2 + + # For each of the previous starting positions insert the bishops in their 16 positions + starts2 = set() + for s in starts: + for bishpos in range(len(s)+1): + s2 = list(s) + s2.insert(bishpos, 'B') + for bishpos2 in range(bishpos+1, len(s)+2, 2): + s3 = s2[::] + s3.insert(bishpos2, 'B') + starts2.add(tuple(s3)) + + return list(starts2) + +gen = generate960() +print(''.join(choice(gen))) diff --git a/Task/Generate-Chess960-starting-position/README b/Task/Generate-Chess960-starting-position/README new file mode 100644 index 0000000000..19ddd8f69e --- /dev/null +++ b/Task/Generate-Chess960-starting-position/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Generate_Chess960_starting_position diff --git a/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-1.rexx b/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-1.rexx new file mode 100644 index 0000000000..4d3b72d527 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-1.rexx @@ -0,0 +1,26 @@ +/*REXX pgm generates a random starting position for the Chess960 game.*/ +parse arg seed . /*allow for (RAND) repeatability.*/ +if seed\=='' then call random ,,seed /*if SEED specified, use the seed*/ +@.=. /*define the (empty) first rank. */ +r1=random(1,8) /*generate the first rook, rank 1*/ +@.r1='R' /*place the first rook on rank1.*/ + do until r2\==r1 & r2\==r1-1 & r2\==r1+1 + r2=random(1,8) /*find placement for the 2nd rook*/ + end /*forever*/ +@.r2='r' /*place the second rook on rank 1*/ +_=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random possition of king*/ +@._='K' /*place king between the 2 rooks.*/ + do _=0 ; b1=random(1,8); if @.b1\==. then iterate; c=b1//2 + do forever; b2=random(1,8) /* c=color of bishop ►──────┘ */ + if @.b2\==. | b2==b1 | b2//2==c then iterate /*bad position*/ + leave _ /*found position for the 2 clergy*/ + end /*forever*/ /* [↑] find a place: 1st bishop.*/ + end /* _ */ /* [↑] " " " 2nd " */ +@.b1='B' /*place the 1st bishop on rank1*/ +@.b2='b' /* " " 2nd " " " */ + /*place the two knights on rank 1*/ + do until @._='N'; _=random(1,8); if @._\==. then iterate; @._='N'; end + do until @.!='n'; !=random(1,8); if @.!\==. then iterate; @.!='n'; end +_= /*only the queen is left to place*/ + do i=1 for 8; _=_ || @.i; end /*construct output: first rank. */ +say translate(translate(_, 'q', .)) /*stick a fork in it, we're done.*/ diff --git a/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-2.rexx b/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-2.rexx new file mode 100644 index 0000000000..2353387a8f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/REXX/generate-chess960-starting-position-2.rexx @@ -0,0 +1,38 @@ +/*REXX pgm generates all random starting positions for the Chess960 game*/ +parse arg seed . /*allow for (RAND) repeatability.*/ +if seed\=='' then call random ,,seed /*if SEED specified, use the seed*/ +x.=0; #=0 + +do t=1 /*═══════════════════════════════════════════════════════════════*/ +if t//1000==0 then say right(t,9) 'random generations: ' # " unique starting positions." +@.=. /*define the (empty) first rank. */ +r1=random(1,8) /*generate the first rook, rank 1*/ +@.r1='R' /*place the first rook on rank1.*/ + do until r2\==r1 & r2\==r1-1 & r2\==r1+1 + r2=random(1,8) /*find placement for the 2nd rook*/ + end /*forever*/ +@.r2='r' /*place the second rook on rank 1*/ +_=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random possition of king*/ +@._='K' /*place king between the 2 rooks.*/ + do _=0 ; b1=random(1,8); if @.b1\==. then iterate; c=b1//2 + do forever; b2=random(1,8) /* c=color of bishop ►──────┘ */ + if @.b2\==. | b2==b1 | b2//2==c then iterate /*bad position*/ + leave _ /*found position for the 2 clergy*/ + end /*forever*/ /* [↑] find a place: 1st bishop.*/ + end /* _ */ /* [↑] " " " 2nd " */ +@.b1='B' /*place the 1st bishop on rank1*/ +@.b2='b' /* " " 2nd " " " */ + /*place the two knights on rank 1*/ + do until @._='N'; _=random(1,8); if @._\==. then iterate; @._='N'; end + do until @.!='n'; !=random(1,8); if @.!\==. then iterate; @.!='n'; end +_= /*only the queen is left to place*/ + do i=1 for 8; _=_ || @.i; end /*construct output: first rank. */ +upper _ /*uppercase all the chess pieces.*/ +if x._ then iterate /*was this position found before?*/ +x._=1 /*define this position as found. */ +#=#+1 /*bump the unique positions found*/ +if #==960 then leave +end /*t ══════════════════════════════════════════════════════════════*/ + +say # 'unique starting positions found after ' t "generations." + /*stick a fork in it, we're done.*/ diff --git a/Task/Generate-Chess960-starting-position/Racket/generate-chess960-starting-position.rkt b/Task/Generate-Chess960-starting-position/Racket/generate-chess960-starting-position.rkt new file mode 100644 index 0000000000..592b16850f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Racket/generate-chess960-starting-position.rkt @@ -0,0 +1,32 @@ +#lang racket +(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔])) +(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚])) + +(define (piece->unicode piece colour) + (match colour ('w white) ('b black)) piece) + +(define (find/set!-random-slot vec val k (f values)) + (define r (f (random k))) + (cond + [(vector-ref vec r) + (find/set!-random-slot vec val k f)] + [else + (vector-set! vec r val) + r])) + +(define (chess960-start-position) + (define v (make-vector 8 #f)) + ;; Kings and Rooks + (let ((k (find/set!-random-slot v (white 'K) 6 add1))) + (find/set!-random-slot v (white 'R) k) + (find/set!-random-slot v (white 'R) (- 7 k) (curry + k 1))) + ;; Bishops -- so far only three squares allocated, so there is at least one of each colour left + (find/set!-random-slot v (white 'B) 4 (curry * 2)) + (find/set!-random-slot v (white 'B) 4 (compose add1 (curry * 2))) + ;; Everyone else + (find/set!-random-slot v (white 'Q) 8) + (find/set!-random-slot v (white 'N) 8) + (find/set!-random-slot v (white 'N) 8) + (list->string (vector->list v))) + +(chess960-start-position) diff --git a/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-1.rb b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-1.rb new file mode 100644 index 0000000000..82b5d0b71f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-1.rb @@ -0,0 +1,4 @@ +pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) +regexes = [/♗(..)*♗/, /♖.*♔.*♖/] +row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} +puts row diff --git a/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-2.rb b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-2.rb new file mode 100644 index 0000000000..e9845ab443 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-2.rb @@ -0,0 +1,5 @@ +row = [:♖, :♔, :♖] +[:♕, :♘, :♘].each{|piece| row.insert(rand(row.size+1), piece)} +[[0, 2, 4, 6].sample, [1, 3, 5, 7].sample].sort.each{|pos| row.insert(pos, :♗)} + +puts row diff --git a/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-3.rb b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-3.rb new file mode 100644 index 0000000000..782ecdf4b7 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Ruby/generate-chess960-starting-position-3.rb @@ -0,0 +1,22 @@ +KRN = %w(NNRKR NRNKR NRKNR NRKRN RNNKR RNKNR RNKRN RKNNR RKNRN RKRNN) + +def chess960(id=rand(960)) + pos = Array.new(8) + q, r = id.divmod(4) + pos[r * 2 + 1] = "B" + q, r = q.divmod(4) + pos[r * 2] = "B" + q, r = q.divmod(6) + pos[pos.each_index.reject{|i| pos[i]}[r]] = "Q" + krn = KRN[q].each_char + pos.each_index {|i| pos[i] ||= krn.next} + pos.join +end + +puts "Generate Start Position from id number" +[0,518,959].each do |id| + puts "%3d : %s" % [id, chess960(id)] +end + +puts "\nGenerate random Start Position" +5.times {puts chess960} diff --git a/Task/Generate-Chess960-starting-position/Seed7/generate-chess960-starting-position.seed7 b/Task/Generate-Chess960-starting-position/Seed7/generate-chess960-starting-position.seed7 new file mode 100644 index 0000000000..24d963cf49 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Seed7/generate-chess960-starting-position.seed7 @@ -0,0 +1,18 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: start is "RKR"; + var char: piece is ' '; + var integer: pos is 0; + begin + for piece range "QNN" do + pos := rand(1, succ(length(start))); + start := start[.. pred(pos)] & str(piece) & start[pos ..]; + end for; + pos := rand(1, succ(length(start))); + start := start[.. pred(pos)] & "B" & start[pos ..]; + pos := succ(pos) + 2 * rand(0, (length(start) - pos) div 2); + start := start[.. pred(pos)] & "B" & start[pos ..]; + writeln(start); + end func; diff --git a/Task/Generate-Chess960-starting-position/Tcl/generate-chess960-starting-position.tcl b/Task/Generate-Chess960-starting-position/Tcl/generate-chess960-starting-position.tcl new file mode 100644 index 0000000000..0bbe18145c --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Tcl/generate-chess960-starting-position.tcl @@ -0,0 +1,18 @@ +package require struct::list + +proc chess960 {} { + while true { + set pos [join [struct::list shuffle {N N B B R R Q K}] ""] + if {[regexp {R.*K.*R} $pos] && [regexp {B(..)*B} $pos]} { + return $pos + } + } +} + +# A simple renderer +proc chessRender {position} { + string map {P ♙ N ♘ B ♗ R ♖ Q ♕ K ♔} $position +} + +# Output multiple times just to show scope of positions +foreach - {1 2 3 4 5} {puts [chessRender [chess960]]} diff --git a/Task/Generate-lower-case-ASCII-alphabet/00DESCRIPTION b/Task/Generate-lower-case-ASCII-alphabet/00DESCRIPTION new file mode 100644 index 0000000000..64226e20b6 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/00DESCRIPTION @@ -0,0 +1,11 @@ +Generate an array, list, lazy sequence, or even an indexable string +of all the lower case ASCII characters, from 'a' to 'z'. + +If the standard library contains such sequence, show how to access it, +but don't fail to show how to generate a similar sequence. +For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. + +It's bug prone to enumerate all the lowercase chars manually in the code. +During code review it's not immediate to spot the bug in a Tcl line like this contained in a page of code: + +set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} diff --git a/Task/Generate-lower-case-ASCII-alphabet/00META.yaml b/Task/Generate-lower-case-ASCII-alphabet/00META.yaml new file mode 100644 index 0000000000..ccf0fbbda3 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/00META.yaml @@ -0,0 +1,2 @@ +--- +note: String_manipulation diff --git a/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-1.alg b/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-1.alg new file mode 100644 index 0000000000..cda5f92032 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-1.alg @@ -0,0 +1,5 @@ + # in ALGOL 68, a STRING is an array of characters with flexible bounds # + # so we can declare an array of 26 characters and assign a string # + # containing the lower-case letters to it # + + [ 26 ]CHAR lc := "abcdefghijklmnopqrstuvwxyz" diff --git a/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-2.alg b/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-2.alg new file mode 100644 index 0000000000..4eb804fbbc --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ALGOL-68/generate-lower-case-ascii-alphabet-2.alg @@ -0,0 +1,9 @@ + # fills lc with the 26 lower-case letters, assuming that # + # they are consecutive in the character set, as they are in ASCII # + + [ 26 ]CHAR lc; + + FOR i FROM LWB lc TO UPB lc + DO + lc[ i ] := REPR ( ABS "a" + ( i - 1 ) ) + OD diff --git a/Task/Generate-lower-case-ASCII-alphabet/ATS/generate-lower-case-ascii-alphabet.ats b/Task/Generate-lower-case-ASCII-alphabet/ATS/generate-lower-case-ascii-alphabet.ats new file mode 100644 index 0000000000..20b4b307e1 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ATS/generate-lower-case-ascii-alphabet.ats @@ -0,0 +1,26 @@ +(* ****** ****** *) +// +// How to compile: +// +// patscc -DATS_MEMALLOC_LIBC -o lowercase lowercase.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +implement +main0 () = +{ +// +val N = 26 +// +val A = +arrayref_tabulate_cloref +( + i2sz(N), lam(i) => int2char0(char2int0('a') + sz2i(i)) +) (* end of [val] *) +// +} (* end of [main0] *) diff --git a/Task/Generate-lower-case-ASCII-alphabet/AWK/generate-lower-case-ascii-alphabet.awk b/Task/Generate-lower-case-ASCII-alphabet/AWK/generate-lower-case-ascii-alphabet.awk new file mode 100644 index 0000000000..a6511ee058 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/AWK/generate-lower-case-ascii-alphabet.awk @@ -0,0 +1,11 @@ +# syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWK +BEGIN { + for (i=0; i<=255; i++) { + c = sprintf("%c",i) + if (c ~ /[[:lower:]]/) { + lower_chars = lower_chars c + } + } + printf("%s %d: %s\n",ARGV[0],length(lower_chars),lower_chars) + exit(0) +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-1.ada b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-1.ada new file mode 100644 index 0000000000..ec63f5da7a --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-1.ada @@ -0,0 +1 @@ + type Lower_Case is new Character range 'a' .. 'z'; diff --git a/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-2.ada b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-2.ada new file mode 100644 index 0000000000..625bacf161 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-2.ada @@ -0,0 +1,2 @@ + type Arr_Type is array (Integer range <>) of Lower_Case; + A : Arr_Type (1 .. 26) := "abcdefghijklmnopqrstuvwxyz"; diff --git a/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-3.ada b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-3.ada new file mode 100644 index 0000000000..1ec8fafd89 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-3.ada @@ -0,0 +1,6 @@ + B : Arr_Type (1 .. 26); +begin + B(B'First) := 'a'; + for I in B'First .. B'Last-1 loop + B(I+1) := Lower_Case'Succ(B(I)); + end loop; -- now all the B(I) are different diff --git a/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-1.applesoft b/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-1.applesoft new file mode 100644 index 0000000000..c6b29117a0 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-1.applesoft @@ -0,0 +1 @@ +L$="abcdefghijklmnopqrstuvwxyz" diff --git a/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-2.applesoft b/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-2.applesoft new file mode 100644 index 0000000000..6d2550d82e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Applesoft-BASIC/generate-lower-case-ascii-alphabet-2.applesoft @@ -0,0 +1 @@ +L$="":FORI=1TO26:L$=L$+CHR$(96+I):NEXT diff --git a/Task/Generate-lower-case-ASCII-alphabet/AutoHotkey/generate-lower-case-ascii-alphabet.ahk b/Task/Generate-lower-case-ASCII-alphabet/AutoHotkey/generate-lower-case-ascii-alphabet.ahk new file mode 100644 index 0000000000..e9a0c48db1 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/AutoHotkey/generate-lower-case-ascii-alphabet.ahk @@ -0,0 +1,3 @@ +a :={} +Loop, 26 + a.Insert(Chr(A_Index + 96)) diff --git a/Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc b/Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc new file mode 100644 index 0000000000..832c28fac7 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc @@ -0,0 +1,5 @@ + DIM lower&(25) + FOR i%=0TO25 + lower&(i%)=ASC"a"+i% + NEXT + END diff --git a/Task/Generate-lower-case-ASCII-alphabet/Bracmat/generate-lower-case-ascii-alphabet.bracmat b/Task/Generate-lower-case-ASCII-alphabet/Bracmat/generate-lower-case-ascii-alphabet.bracmat new file mode 100644 index 0000000000..7d0c5ecfdf --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Bracmat/generate-lower-case-ascii-alphabet.bracmat @@ -0,0 +1,6 @@ + a:?seq:?c +& whl + ' ( chr$(asc$!c+1):~>z:?c + & !seq !c:?seq + ) +& !seq diff --git a/Task/Generate-lower-case-ASCII-alphabet/C++/generate-lower-case-ascii-alphabet.cpp b/Task/Generate-lower-case-ASCII-alphabet/C++/generate-lower-case-ascii-alphabet.cpp new file mode 100644 index 0000000000..8ae4e1a0c5 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/C++/generate-lower-case-ascii-alphabet.cpp @@ -0,0 +1,8 @@ +#include +#include + +int main() { + std::string lower(26,' '); + + std::iota(lower.begin(), lower.end(), 'a'); +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs b/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs new file mode 100644 index 0000000000..a8336d6ffa --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs @@ -0,0 +1,24 @@ +namespace RosettaCode.GenerateLowerCaseASCIIAlphabet +{ + using System; + using System.Collections.Generic; + + internal class Program + { + private static IEnumerable Alphabet + { + get + { + for (var character = 'a'; character <= 'z'; character++) + { + yield return character; + } + } + } + + private static void Main() + { + Console.WriteLine(string.Join(string.Empty, Alphabet)); + } + } +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/C/generate-lower-case-ascii-alphabet.c b/Task/Generate-lower-case-ASCII-alphabet/C/generate-lower-case-ascii-alphabet.c new file mode 100644 index 0000000000..812eb4e1d9 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/C/generate-lower-case-ascii-alphabet.c @@ -0,0 +1,13 @@ +#include + +#define N 26 + +int main() { + unsigned char lower[N]; + + for (size_t i = 0; i < N; i++) { + lower[i] = i + 'a'; + } + + return EXIT_SUCCESS; +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Clojure/generate-lower-case-ascii-alphabet.clj b/Task/Generate-lower-case-ASCII-alphabet/Clojure/generate-lower-case-ascii-alphabet.clj new file mode 100644 index 0000000000..2dbdbe14c0 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Clojure/generate-lower-case-ascii-alphabet.clj @@ -0,0 +1 @@ +(map char (range (int \a) (inc (int \z)))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp new file mode 100644 index 0000000000..5ef72bd592 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp @@ -0,0 +1,4 @@ +(defvar *lower* + (loop with a = (char-code #\a) + for i upto 25 + collect (code-char (+ a i)))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-1.d b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-1.d new file mode 100644 index 0000000000..bc2effa250 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-1.d @@ -0,0 +1,3 @@ +import std.ascii: lowercase; + +void main() {} diff --git a/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-2.d b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-2.d new file mode 100644 index 0000000000..cc2e04a9b1 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-2.d @@ -0,0 +1,6 @@ +void main() { + char['z' - 'a' + 1] arr; + + foreach (immutable i, ref c; arr) + c = 'a' + i; +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-3.d b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-3.d new file mode 100644 index 0000000000..2373bcaa7f --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-3.d @@ -0,0 +1,5 @@ +void main() { + import std.range, std.algorithm, std.array; + + char[26] arr = 26.iota.map!(i => cast(char)('a' + i)).array; +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-4.d b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-4.d new file mode 100644 index 0000000000..eb3260857b --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/D/generate-lower-case-ascii-alphabet-4.d @@ -0,0 +1,8 @@ +void main() { + char[] arr; + + foreach (immutable char c; 'a' .. 'z' + 1) + arr ~= c; + + assert(arr == "abcdefghijklmnopqrstuvwxyz"); +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Delphi/generate-lower-case-ascii-alphabet.delphi b/Task/Generate-lower-case-ASCII-alphabet/Delphi/generate-lower-case-ascii-alphabet.delphi new file mode 100644 index 0000000000..18cb01ce8e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Delphi/generate-lower-case-ascii-alphabet.delphi @@ -0,0 +1,11 @@ +program atoz; + +var + ch : char; + +begin + for ch in ['a'..'z'] do + begin + write(ch); + end; +end. diff --git a/Task/Generate-lower-case-ASCII-alphabet/Factor/generate-lower-case-ascii-alphabet.factor b/Task/Generate-lower-case-ASCII-alphabet/Factor/generate-lower-case-ascii-alphabet.factor new file mode 100644 index 0000000000..2472d7a76e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Factor/generate-lower-case-ascii-alphabet.factor @@ -0,0 +1,7 @@ +USING: spelling ; ! ALPHABET + +ALPHABET print +0x61 0x7A [a,b] >string print +: russian-alphabet-without-io ( -- str ) 0x0430 0x0450 [a,b) >string ; +: russian-alphabet ( -- str ) 0x0451 6 russian-alphabet-without-io insert-nth ; +russian-alphabet print diff --git a/Task/Generate-lower-case-ASCII-alphabet/Fortran/generate-lower-case-ascii-alphabet.f b/Task/Generate-lower-case-ASCII-alphabet/Fortran/generate-lower-case-ascii-alphabet.f new file mode 100644 index 0000000000..a6eda8ab72 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Fortran/generate-lower-case-ascii-alphabet.f @@ -0,0 +1,6 @@ + character(26) :: alpha + integer :: i + + do i = 1, 26 + alpha(i:i) = achar(iachar('a') + i - 1) + end do diff --git a/Task/Generate-lower-case-ASCII-alphabet/Go/generate-lower-case-ascii-alphabet.go b/Task/Generate-lower-case-ASCII-alphabet/Go/generate-lower-case-ascii-alphabet.go new file mode 100644 index 0000000000..439c32eecf --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Go/generate-lower-case-ascii-alphabet.go @@ -0,0 +1,7 @@ +func loweralpha() string { + p := make([]byte, 26) + for i := range p { + p[i] = 'a' + byte(i) + } + return string(p) +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-1.groovy b/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-1.groovy new file mode 100644 index 0000000000..9a3cdc0988 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-1.groovy @@ -0,0 +1 @@ +def lower = ('a'..'z') diff --git a/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-2.groovy b/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-2.groovy new file mode 100644 index 0000000000..f0758abc90 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Groovy/generate-lower-case-ascii-alphabet-2.groovy @@ -0,0 +1 @@ +assert 'abcdefghijklmnopqrstuvwxyz' == lower.join('') diff --git a/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs new file mode 100644 index 0000000000..4629d65cb4 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs @@ -0,0 +1,4 @@ +lower = ['a' .. 'z'] + +main = do + print lower diff --git a/Task/Generate-lower-case-ASCII-alphabet/Icon/generate-lower-case-ascii-alphabet.icon b/Task/Generate-lower-case-ASCII-alphabet/Icon/generate-lower-case-ascii-alphabet.icon new file mode 100644 index 0000000000..47db8f4c88 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Icon/generate-lower-case-ascii-alphabet.icon @@ -0,0 +1,2 @@ +every a := put([], !&lcase) # array of 1 character per element +c := create !&lcase # lazy generation of letters in sequence diff --git a/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet.j b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet.j new file mode 100644 index 0000000000..3cda1ab708 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet.j @@ -0,0 +1,2 @@ + ([+i.@-.@-)&.(a.&i.)/'az' +abcdefghijklmnopqrstuvwxyz diff --git a/Task/Generate-lower-case-ASCII-alphabet/Java/generate-lower-case-ascii-alphabet.java b/Task/Generate-lower-case-ASCII-alphabet/Java/generate-lower-case-ascii-alphabet.java new file mode 100644 index 0000000000..10b44925a9 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Java/generate-lower-case-ascii-alphabet.java @@ -0,0 +1,9 @@ +public class LowerAscii { + + public static void main(String[] args) { + StringBuilder sb = new StringBuilder(26); + for (char ch = 'a'; ch <= 'z'; ch++) + sb.append(ch); + System.out.printf("lower ascii: %s, length: %s", sb, sb.length()); + } +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet.js new file mode 100644 index 0000000000..e4beb828a2 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet.js @@ -0,0 +1,4 @@ +var letters = [] +for (var i = 97; i <= 122; i++) { + letters.push(String.fromCodePoint(i)) +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia b/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia new file mode 100644 index 0000000000..3afcfb3430 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia @@ -0,0 +1,5 @@ +['a':'z'] + +[c for c = 'a':'z'] + +string('a':'z'...) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet.logo b/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet.logo new file mode 100644 index 0000000000..d8c50b4bdd --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet.logo @@ -0,0 +1 @@ +show map "char iseq 97 122 diff --git a/Task/Generate-lower-case-ASCII-alphabet/Mathematica/generate-lower-case-ascii-alphabet.math b/Task/Generate-lower-case-ASCII-alphabet/Mathematica/generate-lower-case-ascii-alphabet.math new file mode 100644 index 0000000000..ee30faa68f --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Mathematica/generate-lower-case-ascii-alphabet.math @@ -0,0 +1,2 @@ +start = 97; +lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}] diff --git a/Task/Generate-lower-case-ASCII-alphabet/Mercury/generate-lower-case-ascii-alphabet.mercury b/Task/Generate-lower-case-ASCII-alphabet/Mercury/generate-lower-case-ascii-alphabet.mercury new file mode 100644 index 0000000000..6d00ba82a9 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Mercury/generate-lower-case-ascii-alphabet.mercury @@ -0,0 +1,16 @@ +:- module gen_lowercase_ascii. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module char, int, list. + +main(!IO) :- + list.map(char.det_from_int, 0'a .. 0'z, Alphabet), + io.print_line(Alphabet, !IO). + +:- end_module gen_lowercase_ascii. diff --git a/Task/Generate-lower-case-ASCII-alphabet/PHP/generate-lower-case-ascii-alphabet.php b/Task/Generate-lower-case-ASCII-alphabet/PHP/generate-lower-case-ascii-alphabet.php new file mode 100644 index 0000000000..2391a10d9e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PHP/generate-lower-case-ascii-alphabet.php @@ -0,0 +1,4 @@ + diff --git a/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-1.pli b/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-1.pli new file mode 100644 index 0000000000..aa37e3d2d8 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-1.pli @@ -0,0 +1,15 @@ +gen: procedure options (main); /* 7 April 2014. */ + declare 1 ascii union, + 2 letters (26) character (1), + 2 iletters(26) unsigned fixed binary (8), + letter character(1); + declare i fixed binary; + + letters(1), letter = lowercase('A'); + + do i = 2 to 26; + iletters(i) = iletters(i-1) + 1; + end; + put edit (letters) (a); + +end gen; diff --git a/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-2.pli b/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-2.pli new file mode 100644 index 0000000000..7b6cdc09e0 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PL-I/generate-lower-case-ascii-alphabet-2.pli @@ -0,0 +1,5 @@ + /* Accessing library lower-case ASCII (PC only). */ + + letter = lowercase('A'); + i = index(collate(), letter); + put skip list (substr(collate, i, 26)); diff --git a/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 b/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 new file mode 100644 index 0000000000..555c738278 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 @@ -0,0 +1 @@ +say 'a'..'z' diff --git a/Task/Generate-lower-case-ASCII-alphabet/Perl/generate-lower-case-ascii-alphabet.pl b/Task/Generate-lower-case-ASCII-alphabet/Perl/generate-lower-case-ascii-alphabet.pl new file mode 100644 index 0000000000..d8f79f9921 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Perl/generate-lower-case-ascii-alphabet.pl @@ -0,0 +1 @@ +print 'a'..'z' diff --git a/Task/Generate-lower-case-ASCII-alphabet/PicoLisp/generate-lower-case-ascii-alphabet.l b/Task/Generate-lower-case-ASCII-alphabet/PicoLisp/generate-lower-case-ascii-alphabet.l new file mode 100644 index 0000000000..cbef4852bb --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PicoLisp/generate-lower-case-ascii-alphabet.l @@ -0,0 +1 @@ +(mapcar char (range (char "a") (char "z"))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Prolog/generate-lower-case-ascii-alphabet.pro b/Task/Generate-lower-case-ASCII-alphabet/Prolog/generate-lower-case-ascii-alphabet.pro new file mode 100644 index 0000000000..742aaf7eaf --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Prolog/generate-lower-case-ascii-alphabet.pro @@ -0,0 +1,4 @@ +a_to_z(From, To, L) :- + maplist(atom_codes, [From, To], [[C_From], [C_To]]), + bagof([C], between(C_From, C_To, C), L1), + maplist(atom_codes,L, L1). diff --git a/Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic b/Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic new file mode 100644 index 0000000000..baaeecce61 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic @@ -0,0 +1,4 @@ +Dim lower_case('z' - 'a') ;indexing goes from 0 -> 25 +For i = 0 To ArraySize(lower_case()) + lower_case(i) = i + 'a' +Next diff --git a/Task/Generate-lower-case-ASCII-alphabet/Python/generate-lower-case-ascii-alphabet.py b/Task/Generate-lower-case-ASCII-alphabet/Python/generate-lower-case-ascii-alphabet.py new file mode 100644 index 0000000000..77e3f13445 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Python/generate-lower-case-ascii-alphabet.py @@ -0,0 +1,5 @@ +# From the standard library: +from string import ascii_lowercase + +# Generation: +lower = [chr(i) for i in range(ord('a'), ord('z') + 1)] diff --git a/Task/Generate-lower-case-ASCII-alphabet/README b/Task/Generate-lower-case-ASCII-alphabet/README new file mode 100644 index 0000000000..e3045acee4 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet diff --git a/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-1.rexx b/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-1.rexx new file mode 100644 index 0000000000..898c42d79a --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-1.rexx @@ -0,0 +1,4 @@ +/* REXX --------------------------------------------------------------- +* 08.02.2014 Walter Pachl +*--------------------------------------------------------------------*/ +say xrange('a','z') diff --git a/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-2.rexx b/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-2.rexx new file mode 100644 index 0000000000..8c4db56916 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/REXX/generate-lower-case-ascii-alphabet-2.rexx @@ -0,0 +1,6 @@ +/*REXX pgm creates an indexable string of lowercase ASCII characters a ──► z */ +LC='' /*set lowercase letters list to null*/ + do j=0 for 2**8; _=d2c(j) /*convert decimal J to character. */ + if datatype(_,'L') then LC=LC||_ /*Lowercase? Then add it to LC list*/ + end /*j*/ /* [↑] add lowercase letters ──► LC*/ +say LC /*stick a fork in it, we're all done*/ diff --git a/Task/Generate-lower-case-ASCII-alphabet/Racket/generate-lower-case-ascii-alphabet.rkt b/Task/Generate-lower-case-ASCII-alphabet/Racket/generate-lower-case-ascii-alphabet.rkt new file mode 100644 index 0000000000..74e556f255 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Racket/generate-lower-case-ascii-alphabet.rkt @@ -0,0 +1 @@ +(define lowercase-letters (build-list 26 (lambda (x) (integer->char (+ x (char->integer #\a)))))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Ruby/generate-lower-case-ascii-alphabet.rb b/Task/Generate-lower-case-ASCII-alphabet/Ruby/generate-lower-case-ascii-alphabet.rb new file mode 100644 index 0000000000..5438cf236a --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Ruby/generate-lower-case-ascii-alphabet.rb @@ -0,0 +1,2 @@ +p ('a' .. 'z').to_a +p [*'a' .. 'z'] diff --git a/Task/Generate-lower-case-ASCII-alphabet/Scala/generate-lower-case-ascii-alphabet.scala b/Task/Generate-lower-case-ASCII-alphabet/Scala/generate-lower-case-ascii-alphabet.scala new file mode 100644 index 0000000000..a4cb6be6d6 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Scala/generate-lower-case-ascii-alphabet.scala @@ -0,0 +1,18 @@ +object Abc extends App { + val lowAlfa = 'a' to 'z' //That's all + // Now several tests + assert(lowAlfa.toSeq == Seq('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'), + "No complete lowercase alfabet.") + assert(lowAlfa.size == 26, "No 26 characters in alfabet") + assert(lowAlfa.start == 'a', "Character 'a' not first char! ???") + assert(lowAlfa.head == 'a', "Character 'a' not heading! ???") + assert(lowAlfa.head == lowAlfa(0), "Heading char is not first char.") + assert(lowAlfa contains 'n', "Character n not present.") + assert(lowAlfa.indexOf('n') == 13, "Character n not on the 14th position.") + assert(lowAlfa.last == lowAlfa(25), "Expected character (z)on the last and 26th pos.") + + println(s"Successfully completed without errors. [within ${ + scala.compat.Platform.currentTime - executionStart + } ms]") +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Scheme/generate-lower-case-ascii-alphabet.ss b/Task/Generate-lower-case-ASCII-alphabet/Scheme/generate-lower-case-ascii-alphabet.ss new file mode 100644 index 0000000000..60665b005b --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Scheme/generate-lower-case-ascii-alphabet.ss @@ -0,0 +1 @@ +(map integer->char (iota 26 (char->integer #\a))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Standard-ML/generate-lower-case-ascii-alphabet.ml b/Task/Generate-lower-case-ASCII-alphabet/Standard-ML/generate-lower-case-ascii-alphabet.ml new file mode 100644 index 0000000000..0bae0a8d96 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Standard-ML/generate-lower-case-ascii-alphabet.ml @@ -0,0 +1 @@ +val lowercase_letters = List.tabulate (26, fn x => chr (x + ord #"a")); diff --git a/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-1.tcl b/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-1.tcl new file mode 100644 index 0000000000..918333ccff --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-1.tcl @@ -0,0 +1 @@ +set alpha {a b c d e f g h i j k l m n o p q r s t u v w x y z} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-2.tcl b/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-2.tcl new file mode 100644 index 0000000000..ff38556e99 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Tcl/generate-lower-case-ascii-alphabet-2.tcl @@ -0,0 +1,7 @@ +set alpha [apply {{} { + scan "az" "%c%c" from to + for {set i $from} {$i <= $to} {incr i} { + lappend l [format "%c" $i] + } + return $l +}}] diff --git a/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-1.sh b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-1.sh new file mode 100644 index 0000000000..c70daea936 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-1.sh @@ -0,0 +1 @@ +lower=({a..z}) diff --git a/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-2.sh b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-2.sh new file mode 100644 index 0000000000..4b4b6ab584 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-2.sh @@ -0,0 +1 @@ +lower=({a-z}) diff --git a/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-3.sh b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-3.sh new file mode 100644 index 0000000000..4df79174b8 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/UNIX-Shell/generate-lower-case-ascii-alphabet-3.sh @@ -0,0 +1 @@ +echo "${lower[@]}" diff --git a/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-1.vim b/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-1.vim new file mode 100644 index 0000000000..840cafc869 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-1.vim @@ -0,0 +1,4 @@ +let lower = [] +for c in range(0, 25) + let lower += [nr2char(c + char2nr("a"))] +endfor diff --git a/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-2.vim b/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-2.vim new file mode 100644 index 0000000000..674a88f5d3 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Vim-Script/generate-lower-case-ascii-alphabet-2.vim @@ -0,0 +1 @@ +echo map(range(char2nr('a'), char2nr('z')), 'nr2char(v:val)') diff --git a/Task/Hash-join/00DESCRIPTION b/Task/Hash-join/00DESCRIPTION new file mode 100644 index 0000000000..b1e370dc0b --- /dev/null +++ b/Task/Hash-join/00DESCRIPTION @@ -0,0 +1,38 @@ +The classic [[wp:Hash Join|hash join]] algorithm for an inner join of two relations has the following steps: +
    +
  • Hash phase: Create a hash table for one of the two relations by applying a hash + function to the join attribute of each row. Ideally we should create a hash table for the + smaller relation, thus optimizing for creation time and memory size of the hash table.
  • +
  • Join phase: Scan the larger relation and find the relevant rows by looking in the + hash table created before.
  • +
+ +The algorithm is as follows: + + '''for each''' tuple ''s'' '''in''' ''S'' '''do''' + '''let''' ''h'' = hash on join attributes ''s''(b) + '''place''' ''s'' '''in''' hash table ''Sh'' '''in''' bucket '''keyed by''' hash value ''h'' + '''for each''' tuple ''r'' '''in''' ''R'' '''do''' + '''let''' ''h'' = hash on join attributes ''r''(a) + '''if''' ''h'' indicates a nonempty bucket (''B'') of hash table ''Sh'' + '''if''' ''h'' matches any ''s'' in ''B'' + '''concatenate''' ''r'' and ''s'' + '''place''' relation in ''Q'' + +'''Task:''' implement the Hash Join algorithm and show the result of joining two tables with it. +You should use your implementation to show the joining of these tables: +
+ + + + + + +
AgeName
27Jonah
18Alan
28Glory
18Popeye
28Alan
+ + + + + + +
NameNemesis
JonahWhales
JonahSpiders
AlanGhosts
AlanZombies
GloryBuffy
diff --git a/Task/Hash-join/Bracmat/hash-join.bracmat b/Task/Hash-join/Bracmat/hash-join.bracmat new file mode 100644 index 0000000000..608095cd91 --- /dev/null +++ b/Task/Hash-join/Bracmat/hash-join.bracmat @@ -0,0 +1,57 @@ +( (27.Jonah) + (18.Alan) + (28.Glory) + (18.Popeye) + (28.Alan) + : ?table-A +& (Jonah.Whales) + (Jonah.Spiders) + (Alan.Ghosts) + (Alan.Zombies) + (Glory.Buffy) + : ?table-B +& new$hash:?H +& !table-A:? [?lenA +& !table-B:? [?lenB +& ( join + = smalltab bigtab smallschema bigschema joinschema + , key val val2 keyval2 + . !arg + : (?smalltab.?bigtab.(=?smallschema.?bigschema.?joinschema)) + & :?rel + & !( + ' ( whl + ' ( !smalltab:$smallschema ?smalltab + & (H..insert)$(!key.!val) + ) + & whl + ' ( !bigtab:$bigschema ?bigtab + & ( (H..find)$!key:?keyval2 + & whl + ' ( !keyval2:(?key.?val2) ?keyval2 + & $joinschema !rel:?rel + ) + | + ) + ) + ) + ) + & !rel + ) +& out + $ ( join + $ ( !lenA:~(); + NameNemesis = new List(); + } + public List AgeName { get; set; } + public List NameNemesis { get; set; } + } + + public class AgeNameNemesis + { + public AgeNameNemesis(byte age, string name, string nemesis) + { + Age = age; + Name = name; + Nemesis = nemesis; + } + public byte Age { get; private set; } + public string Name { get; private set; } + public string Nemesis { get; private set; } + } + + class Program + { + public static void Main() + { + var data = GetData(); + var result = ExecuteHashJoin(data); + WriteResultToConsole(result); + } + + private static void WriteResultToConsole(List result) + { + result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", + ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); + } + + private static List ExecuteHashJoin(DataContext data) + { + return (data.AgeName.Join(data.NameNemesis, + ageName => ageName.Name, nameNemesis => nameNemesis.Name, + (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) + .ToList(); + } + + private static DataContext GetData() + { + var context = new DataContext(); + + context.AgeName.AddRange(new [] { + new AgeName(27, "Jonah"), + new AgeName(18, "Alan"), + new AgeName(28, "Glory"), + new AgeName(18, "Popeye"), + new AgeName(28, "Alan") + }); + + context.NameNemesis.AddRange(new[] + { + new NameNemesis("Jonah", "Whales"), + new NameNemesis("Jonah", "Spiders"), + new NameNemesis("Alan", "Ghosts"), + new NameNemesis("Alan", "Zombies"), + new NameNemesis("Glory", "Buffy") + }); + + return context; + } + } +} diff --git a/Task/Hash-join/Clojure/hash-join.clj b/Task/Hash-join/Clojure/hash-join.clj new file mode 100644 index 0000000000..b4eacf835b --- /dev/null +++ b/Task/Hash-join/Clojure/hash-join.clj @@ -0,0 +1,20 @@ +(defn hash-join [table1 col1 table2 col2] + (let [hashed (group-by col1 table1)] + (flatten + (for [r table2] + (for [s (hashed (col2 r))] + (merge s r)))))) + +(def s '({:age 27 :name "Jonah"} + {:age 18 :name "Alan"} + {:age 28 :name "Glory"} + {:age 18 :name "Popeye"} + {:age 28 :name "Alan"})) + +(def r '({:nemesis "Whales" :name "Jonah"} + {:nemesis "Spiders" :name "Jonah"} + {:nemesis "Ghosts" :name "Alan"} + {:nemesis "Zombies" :name "Alan"} + {:nemesis "Buffy" :name "Glory"})) + +(pprint (sort-by :name (hash-join s :name r :name))) diff --git a/Task/Hash-join/Common-Lisp/hash-join.lisp b/Task/Hash-join/Common-Lisp/hash-join.lisp new file mode 100644 index 0000000000..c529cf05cf --- /dev/null +++ b/Task/Hash-join/Common-Lisp/hash-join.lisp @@ -0,0 +1,17 @@ +(defparameter *table-A* '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan"))) + +(defparameter *table-B* '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy"))) + +;; Hash phase +(defparameter *hash-table* (make-hash-table :test #'equal)) + +(loop for (i r) in *table-A* + for value = (gethash r *hash-table* (list nil)) do + (setf (gethash r *hash-table*) value) + (push (list i r) (first value))) + +;; Join phase +(loop for (i r) in *table-B* do + (let ((val (car (gethash i *hash-table*)))) + (loop for (a b) in val do + (format t "{~a ~a} {~a ~a}~%" a b i r)))) diff --git a/Task/Hash-join/D/hash-join.d b/Task/Hash-join/D/hash-join.d new file mode 100644 index 0000000000..925cdde947 --- /dev/null +++ b/Task/Hash-join/D/hash-join.d @@ -0,0 +1,35 @@ +import std.stdio, std.typecons; + +auto hashJoin(size_t index1, size_t index2, T1, T2) + (in T1[] table1, in T2[] table2) pure /*nothrow*/ @safe +if (is(typeof(T1.init[index1]) == typeof(T2.init[index2]))) { + // Hash phase. + T1[][typeof(T1.init[index1])] h; + foreach (const s; table1) + h[s[index1]] ~= s; + + // Join phase. + Tuple!(const T1, const T2)[] result; + foreach (const r; table2) + foreach (const s; h.get(r[index2], null)) // Not nothrow. + result ~= tuple(s, r); + + return result; +} + +void main() { + alias T = tuple; + immutable table1 = [T(27, "Jonah"), + T(18, "Alan"), + T(28, "Glory"), + T(18, "Popeye"), + T(28, "Alan")]; + immutable table2 = [T("Jonah", "Whales"), + T("Jonah", "Spiders"), + T("Alan", "Ghosts"), + T("Alan", "Zombies"), + T("Glory", "Buffy")]; + + foreach (const row; hashJoin!(1, 0)(table1, table2)) + writefln("(%s, %5s) (%5s, %7s)", row[0][], row[1][]); +} diff --git a/Task/Hash-join/Deja-Vu/hash-join.djv b/Task/Hash-join/Deja-Vu/hash-join.djv new file mode 100644 index 0000000000..5c91a1e01c --- /dev/null +++ b/Task/Hash-join/Deja-Vu/hash-join.djv @@ -0,0 +1,19 @@ +hashJoin table1 index1 table2 index2: + local :h {} + # hash phase + for s in table1: + local :key s! index1 + if not has h key: + set-to h key [] + push-to h! key s + # join phase + [] + for r in table2: + for s in copy h! r! index2: + push-through swap [ s r ] + +local :table1 [ [ 27 "Jonah" ] [ 18 "Alan" ] [ 28 "Glory" ] [ 18 "Popeye" ] [ 28 "Alan" ] ] +local :table2 [ [ "Jonah" "Whales" ] [ "Jonah" "Spiders" ] [ "Alan" "Ghosts" ] [ "Alan" "Zombies" ] [ "Glory" "Buffy" ] ] + +for row in hashJoin table1 1 table2 0: + !. row diff --git a/Task/Hash-join/Erlang/hash-join.erl b/Task/Hash-join/Erlang/hash-join.erl new file mode 100644 index 0000000000..355ef56e3c --- /dev/null +++ b/Task/Hash-join/Erlang/hash-join.erl @@ -0,0 +1,17 @@ +-module( hash_join ). + +-export( [task/0] ). + +task() -> + Table_1 = [{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}], + Table_2 = [{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}], + Dict = lists:foldl( fun dict_append/2, dict:new(), Table_1 ), + lists:flatten( [dict_find( X, Dict ) || X <- Table_2] ). + + +dict_append( {Key, Value}, Acc ) -> dict:append( Value, {Key, Value}, Acc ). + +dict_find( {Key, Value}, Dict ) -> dict_find( dict:find(Key, Dict), Key, Value ). + +dict_find( error, _Key, _Value ) -> []; +dict_find( {ok, Values}, Key, Value ) -> [{X, {Key, Value}} || X <- Values]. diff --git a/Task/Hash-join/Go/hash-join.go b/Task/Hash-join/Go/hash-join.go new file mode 100644 index 0000000000..e3d20683ec --- /dev/null +++ b/Task/Hash-join/Go/hash-join.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +func main() { + tableA := []struct { + value int + key string + }{ + {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, + {28, "Alan"}, + } + tableB := []struct { + key string + value string + }{ + {"Jonah", "Whales"}, {"Jonah", "Spiders"}, + {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, + } + // hash phase + h := map[string][]int{} + for i, r := range tableA { + h[r.key] = append(h[r.key], i) + } + // join phase + for _, x := range tableB { + for _, a := range h[x.key] { + fmt.Println(tableA[a], x) + } + } +} diff --git a/Task/Hash-join/Groovy/hash-join-1.groovy b/Task/Hash-join/Groovy/hash-join-1.groovy new file mode 100644 index 0000000000..cc5c524d2e --- /dev/null +++ b/Task/Hash-join/Groovy/hash-join-1.groovy @@ -0,0 +1,15 @@ +def hashJoin(table1, col1, table2, col2) { + + def hashed = table1.groupBy { s -> s[col1] } + + def q = [] as Set + + table2.each { r -> + def join = hashed[r[col2]] + join.each { s -> + q << s.plus(r) + } + } + + q +} diff --git a/Task/Hash-join/Groovy/hash-join-2.groovy b/Task/Hash-join/Groovy/hash-join-2.groovy new file mode 100644 index 0000000000..3e9dd13f15 --- /dev/null +++ b/Task/Hash-join/Groovy/hash-join-2.groovy @@ -0,0 +1,8 @@ +def hashJoin(table1, col1, table2, col2) { + + def hashed = table1.groupBy { s -> s[col1] } + + table2.collect { r -> + hashed[r[col2]].collect { s -> s.plus(r) } + }.flatten() +} diff --git a/Task/Hash-join/Groovy/hash-join-3.groovy b/Task/Hash-join/Groovy/hash-join-3.groovy new file mode 100644 index 0000000000..51c06a3b54 --- /dev/null +++ b/Task/Hash-join/Groovy/hash-join-3.groovy @@ -0,0 +1,13 @@ +def s = [[age: 27, name: 'Jonah'], + [age: 18, name: 'Alan'], + [age: 28, name: 'Glory'], + [age: 18, name: 'Popeye'], + [age: 28, name: 'Alan']] + +def r = [[name: 'Jonah', nemesis: 'Whales'], + [name: 'Jonah', nemesis: 'Spiders'], + [name: 'Alan', nemesis: 'Ghosts'], + [name: 'Alan', nemesis: 'Zombies'], + [name: 'Glory', nemesis: 'Buffy']] + +hashJoin(s, "name", r, "name").sort {it.name}.each { println it } diff --git a/Task/Hash-join/Haskell/hash-join-1.hs b/Task/Hash-join/Haskell/hash-join-1.hs new file mode 100644 index 0000000000..673efb840e --- /dev/null +++ b/Task/Hash-join/Haskell/hash-join-1.hs @@ -0,0 +1,28 @@ +{-# LANGUAGE LambdaCase, TupleSections #-} +import qualified Data.HashTable.ST.Basic as H +import Data.Hashable +import Control.Monad.ST +import Control.Monad +import Data.STRef + +hashJoin :: (Eq k, Hashable k) => + [t] -> (t -> k) -> [a] -> (a -> k) -> [(t, a)] +hashJoin xs fx ys fy = runST $ do + l <- newSTRef [] + ht <- H.new + forM_ ys $ \y -> H.insert ht (fy y) =<< + (H.lookup ht (fy y) >>= \case + Nothing -> return [y] + Just v -> return (y:v)) + forM_ xs $ \x -> do + H.lookup ht (fx x) >>= \case + Nothing -> return () + Just v -> modifySTRef' l ((map (x,) v) ++) + readSTRef l + +test = mapM_ print $ hashJoin + [(1, "Jonah"), (2, "Alan"), (3, "Glory"), (4, "Popeye")] + snd + [("Jonah", "Whales"), ("Jonah", "Spiders"), + ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] + fst diff --git a/Task/Hash-join/Haskell/hash-join-2.hs b/Task/Hash-join/Haskell/hash-join-2.hs new file mode 100644 index 0000000000..26d6f96b76 --- /dev/null +++ b/Task/Hash-join/Haskell/hash-join-2.hs @@ -0,0 +1,18 @@ +{-# LANGUAGE TupleSections #-} +import qualified Data.Map as M +import Data.List +import Data.Maybe +import Control.Applicative + +mapJoin xs fx ys fy = joined + where yMap = foldl' f M.empty ys + f m y = M.insertWith (++) (fy y) [y] m + joined = concat . catMaybes . + map (\x -> map (x,) <$> M.lookup (fx x) yMap) $ xs + +test = mapM_ print $ mapJoin + [(1, "Jonah"), (2, "Alan"), (3, "Glory"), (4, "Popeye")] + snd + [("Jonah", "Whales"), ("Jonah", "Spiders"), + ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] + fst diff --git a/Task/Hash-join/J/hash-join-1.j b/Task/Hash-join/J/hash-join-1.j new file mode 100644 index 0000000000..bf922675c0 --- /dev/null +++ b/Task/Hash-join/J/hash-join-1.j @@ -0,0 +1,15 @@ +table1=: ;:;._2(0 :0) + 27 Jonah + 18 Alan + 28 Glory + 18 Popeye + 28 Alan +) + +table2=: ;:;._2(0 :0) + Jonah Whales + Jonah Spiders + Alan Ghosts + Alan Zombies + Glory Buffy +) diff --git a/Task/Hash-join/J/hash-join-2.j b/Task/Hash-join/J/hash-join-2.j new file mode 100644 index 0000000000..6e243ccbe6 --- /dev/null +++ b/Task/Hash-join/J/hash-join-2.j @@ -0,0 +1,9 @@ +hash=: ] +dojoin=:3 :0 + c1=. {.{.y + c2=. (1 {"1 y) -. a: + c3=. (2 {"1 y) -. a: + >{c1;c2;Length[t2],tmp=t1;t1=t2;t2=tmp;]; +h= GroupBy[t1,First]; +f[{a_,b_List}]:={a,#}&/@b; +Partition[Flatten[Map[f,{#[[2;;]],h[#[[1]]]}&/@t2 +]],Length[t1[[1]]]+Length[t2[[1]]]-1] +]; diff --git a/Task/Hash-join/OCaml/hash-join.ocaml b/Task/Hash-join/OCaml/hash-join.ocaml new file mode 100644 index 0000000000..4e26cd45a1 --- /dev/null +++ b/Task/Hash-join/OCaml/hash-join.ocaml @@ -0,0 +1,8 @@ +let hash_join table1 f1 table2 f2 = + let h = Hashtbl.create 42 in + (* hash phase *) + List.iter (fun s -> + Hashtbl.add h (f1 s) s) table1; + (* join phase *) + List.concat (List.map (fun r -> + List.map (fun s -> s, r) (Hashtbl.find_all h (f2 r))) table2) diff --git a/Task/Hash-join/Oberon-2/hash-join.oberon-2 b/Task/Hash-join/Oberon-2/hash-join.oberon-2 new file mode 100644 index 0000000000..0ae6b2e28a --- /dev/null +++ b/Task/Hash-join/Oberon-2/hash-join.oberon-2 @@ -0,0 +1,94 @@ +MODULE HashJoin; +IMPORT + ADT:Dictionary, + ADT:LinkedList, + NPCT:Tools, + Object, + Object:Boxed, + Out; +TYPE + (* Some Aliases *) + Age= Boxed.LongInt; + Name= STRING; + Nemesis= STRING; + + (* Generic Tuple *) + Tuple(E1: Object.Object; E2: Object.Object) = POINTER TO TupleDesc(E1,E2); + TupleDesc(E1: Object.Object; E2: Object.Object) = RECORD + (Object.ObjectDesc) + _1: E1; + _2: E2; + END; + + (* Relations *) + RelationA = ARRAY 5 OF Tuple(Age,Name); + RelationB = ARRAY 5 OF Tuple(Name,Nemesis); + +VAR + tableA: RelationA; + tableB: RelationB; + dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age)); + ll: LinkedList.LinkedList(Age); + + PROCEDURE (t: Tuple(E1, E2)) INIT*(e1: E1; e2: E2); + BEGIN + t._1 := e1; + t._2 := e2; + END INIT; + + PROCEDURE DoHashPhase(t: RelationA;VAR dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age))); + VAR + i: INTEGER; + ll: LinkedList.LinkedList(Age); + BEGIN + i := 0; + WHILE (i < LEN(t)) & (t[i] # NIL) DO + IF (dict.HasKey(t[i]._2)) THEN + ll := dict.Get(t[i]._2); + ELSE + ll := NEW(LinkedList.LinkedList(Age)); + dict.Set(t[i]._2,ll) + END; + ll.Append(t[i]._1); + INC(i) + END + END DoHashPhase; + + PROCEDURE DoJoinPhase(t: RelationB; dict: Dictionary.Dictionary(Name,LinkedList.LinkedList(Age))); + VAR + i: INTEGER; + age: Age; + iterll: LinkedList.Iterator(Age); + BEGIN + FOR i := 0 TO LEN(t) - 1 DO + ll := dict.Get(t[i]._1); + iterll := ll.GetIterator(NIL); + WHILE iterll.HasNext() DO + age := iterll.Next(); + Out.LongInt(age.value,4); + Out.Object(Tools.AdjustRight(t[i]._1,10)); + Out.Object(Tools.AdjustRight(t[i]._2,10));Out.Ln + END + END + END DoJoinPhase; + +BEGIN + (* tableA initialization *) + tableA[0] := NEW(Tuple(Age,Name),NEW(Age,27),"Jonah"); + tableA[1] := NEW(Tuple(Age,Name),NEW(Age,18),"Alan"); + tableA[2] := NEW(Tuple(Age,Name),NEW(Age,28),"Glory"); + tableA[3] := NEW(Tuple(Age,Name),NEW(Age,18),"Popeye"); + tableA[4] := NEW(Tuple(Age,Name),NEW(Age,28),"Alan"); + + (* tableB initialization *) + tableB[0] := NEW(Tuple(Name,Nemesis),"Jonah","Whales"); + tableB[1] := NEW(Tuple(Name,Nemesis),"Jonah","Spiders"); + tableB[2] := NEW(Tuple(Name,Nemesis),"Alan","Ghost"); + tableB[3] := NEW(Tuple(Name,Nemesis),"Alan","Zombies"); + tableB[4] := NEW(Tuple(Name,Nemesis),"Glory","Buffy"); + + dict := NEW(Dictionary.Dictionary(Name,LinkedList.LinkedList(Age))); + + DoHashPhase(tableA,dict); + DoJoinPhase(tableB,dict); +END HashJoin. diff --git a/Task/Hash-join/PHP/hash-join.php b/Task/Hash-join/PHP/hash-join.php new file mode 100644 index 0000000000..c696c325a6 --- /dev/null +++ b/Task/Hash-join/PHP/hash-join.php @@ -0,0 +1,27 @@ + diff --git a/Task/Hash-join/Perl-6/hash-join.pl6 b/Task/Hash-join/Perl-6/hash-join.pl6 new file mode 100644 index 0000000000..8320528b31 --- /dev/null +++ b/Task/Hash-join/Perl-6/hash-join.pl6 @@ -0,0 +1,18 @@ +my @A = [1, "Jonah"], + [2, "Alan"], + [3, "Glory"], + [4, "Popeye"]; + +my @B = ["Jonah", "Whales"], + ["Jonah", "Spiders"], + ["Alan", "Ghosts"], + ["Alan", "Zombies"], + ["Glory", "Buffy"]; + +sub hash-join(@a, &a, @b, &b) { + my %hash{Any}; + %hash{.&a} = $_ for @a; + ([%hash{.&b} // next, $_] for @b); +} + +.perl.say for hash-join @A, *.[1], @B, *.[0]; diff --git a/Task/Hash-join/Perl/hash-join.pl b/Task/Hash-join/Perl/hash-join.pl new file mode 100644 index 0000000000..0970fc040c --- /dev/null +++ b/Task/Hash-join/Perl/hash-join.pl @@ -0,0 +1,30 @@ +use Data::Dumper qw(Dumper); + +sub hashJoin { + my ($table1, $index1, $table2, $index2) = @_; + my %h; + # hash phase + foreach my $s (@$table1) { + push @{ $h{$s->[$index1]} }, $s; + } + # join phase + map { my $r = $_; + map [$_, $r], @{ $h{$r->[$index2]} } + } @$table2; +} + +@table1 = ([27, "Jonah"], + [18, "Alan"], + [28, "Glory"], + [18, "Popeye"], + [28, "Alan"]); +@table2 = (["Jonah", "Whales"], + ["Jonah", "Spiders"], + ["Alan", "Ghosts"], + ["Alan", "Zombies"], + ["Glory", "Buffy"]); + +$Data::Dumper::Indent = 0; +foreach my $row (hashJoin(\@table1, 1, \@table2, 0)) { + print Dumper($row), "\n"; +} diff --git a/Task/Hash-join/Python/hash-join.py b/Task/Hash-join/Python/hash-join.py new file mode 100644 index 0000000000..c145e77137 --- /dev/null +++ b/Task/Hash-join/Python/hash-join.py @@ -0,0 +1,23 @@ +from collections import defaultdict + +def hashJoin(table1, index1, table2, index2): + h = defaultdict(list) + # hash phase + for s in table1: + h[s[index1]].append(s) + # join phase + return [(s, r) for r in table2 for s in h[r[index2]]] + +table1 = [(27, "Jonah"), + (18, "Alan"), + (28, "Glory"), + (18, "Popeye"), + (28, "Alan")] +table2 = [("Jonah", "Whales"), + ("Jonah", "Spiders"), + ("Alan", "Ghosts"), + ("Alan", "Zombies"), + ("Glory", "Buffy")] + +for row in hashJoin(table1, 1, table2, 0): + print(row) diff --git a/Task/Hash-join/README b/Task/Hash-join/README new file mode 100644 index 0000000000..9641093c78 --- /dev/null +++ b/Task/Hash-join/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Hash_join diff --git a/Task/Hash-join/REXX/hash-join.rexx b/Task/Hash-join/REXX/hash-join.rexx new file mode 100644 index 0000000000..b42a075a3b --- /dev/null +++ b/Task/Hash-join/REXX/hash-join.rexx @@ -0,0 +1,33 @@ +/*REXX pgm demonstrates the classic hash join algorithm for 2 relations.*/ + S. = ; R. = + S.1 = 27 'Jonah' ; R.1 = 'Jonah Whales' + S.2 = 18 'Alan' ; R.2 = 'Jonah Spiders' + S.3 = 28 'Glory' ; R.3 = 'Alan Ghosts' + S.4 = 18 'Popeye' ; R.4 = 'Alan Zombies' + S.5 = 28 'Alan' ; R.5 = 'Glory Buffy' +hash.= /*initialize the hash table. */ + do #=1 while S.#\==''; parse var S.# age name /*extract info*/ + hash.name=hash.name # /*build a hash table entry. */ + end /*#*/ /* [↑] REXX does the heavy work.*/ +#=#-1 /*adjust for DO loop (#) overage.*/ + do j=1 while R.j\=='' /*process a nemesis for a name. */ + parse var R.j x nemesis /*extract name and it's nemesis. */ + if hash.x=='' then do /*Not in hash? Then a new name.*/ + #=#+1 /*bump the number of S entries. */ + S.#=',' x /*add new name to the S table. */ + hash.x=# /*add new name to the hash table.*/ + end /* [↑] this DO isn't used today.*/ + do k=1 for words(hash.x); _=word(hash.x,k) /*get pointer.*/ + S._=S._ nemesis /*add nemesis──► applicable hash.*/ + end /*k*/ + end /*j*/ +_='─' /*character used for separater. */ +pad=left('',6-2) /*spacing used in hdr/sep/output.*/ +say pad center('age',3) pad center('name',20) pad center('nemesis',30) +say pad center('───',3) pad center('' ,20,_) pad center('' ,30,_) + + do n=1 for #; parse var S.n age name nems /*get info. */ + if nems=='' then iterate /*if no nemesis, then don't show.*/ + say pad right(age,3) pad center(name,20) pad nems /*show an S.*/ + end /*n*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Hash-join/Racket/hash-join.rkt b/Task/Hash-join/Racket/hash-join.rkt new file mode 100644 index 0000000000..f5e68a9b99 --- /dev/null +++ b/Task/Hash-join/Racket/hash-join.rkt @@ -0,0 +1,29 @@ +#lang racket +(struct A (age name)) +(struct B (name nemesis)) +(struct AB (name age nemesis) #:transparent) + +(define Ages-table + (list (A 27 "Jonah") (A 18 "Alan") + (A 28 "Glory") (A 18 "Popeye") + (A 28 "Alan"))) + +(define Nemeses-table + (list + (B "Jonah" "Whales") (B "Jonah" "Spiders") + (B "Alan" "Ghosts") (B "Alan" "Zombies") + (B "Glory" "Buffy"))) + +;; Hash phase +(define name->ages# + (for/fold ((rv (hash))) + ((a (in-list Ages-table))) + (match-define (A age name) a) + (hash-update rv name (λ (ages) (append ages (list age))) null))) + +;; Join phase +(for*/list + ((b (in-list Nemeses-table)) + (key (in-value (B-name b))) + (age (in-list (hash-ref name->ages# key)))) + (AB key age (B-nemesis b))) diff --git a/Task/Hash-join/Ruby/hash-join.rb b/Task/Hash-join/Ruby/hash-join.rb new file mode 100644 index 0000000000..05eb89087a --- /dev/null +++ b/Task/Hash-join/Ruby/hash-join.rb @@ -0,0 +1,22 @@ +def hashJoin(table1, index1, table2, index2) + # hash phase + h = table1.group_by {|s| s[index1]} + h.default = [] + # join phase + table2.collect {|r| + h[r[index2]].collect {|s| [s, r]} + }.flatten(1) +end + +table1 = [[27, "Jonah"], + [18, "Alan"], + [28, "Glory"], + [18, "Popeye"], + [28, "Alan"]] +table2 = [["Jonah", "Whales"], + ["Jonah", "Spiders"], + ["Alan", "Ghosts"], + ["Alan", "Zombies"], + ["Glory", "Buffy"]] + +hashJoin(table1, 1, table2, 0).each { |row| p row } diff --git a/Task/Hash-join/SQL/hash-join-1.sql b/Task/Hash-join/SQL/hash-join-1.sql new file mode 100644 index 0000000000..b22597ce71 --- /dev/null +++ b/Task/Hash-join/SQL/hash-join-1.sql @@ -0,0 +1,13 @@ +create table people (age decimal(3), name varchar(16)); +insert into people (age, name) values (27, 'Jonah'); +insert into people (age, name) values (18, 'Alan'); +insert into people (age, name) values (28, 'Glory'); +insert into people (age, name) values (18, 'Popeye'); +insert into people (age, name) values (28, 'Alan'); + +create table nemesises (name varchar(16), nemesis varchar(16)); +insert into nemesises (name, nemesis) values ('Jonah', 'Whales'); +insert into nemesises (name, nemesis) values ('Jonah', 'Spiders'); +insert into nemesises (name, nemesis) values ('Alan', 'Ghosts'); +insert into nemesises (name, nemesis) values ('Alan', 'Zombies'); +insert into nemesises (name, nemesis) values ('Glory', 'Buffy'); diff --git a/Task/Hash-join/SQL/hash-join-2.sql b/Task/Hash-join/SQL/hash-join-2.sql new file mode 100644 index 0000000000..d84f4732a8 --- /dev/null +++ b/Task/Hash-join/SQL/hash-join-2.sql @@ -0,0 +1 @@ +select * from people p join nemesises n on p.name = n.name diff --git a/Task/Hash-join/Scala/hash-join.scala b/Task/Hash-join/Scala/hash-join.scala new file mode 100644 index 0000000000..46e8395fc1 --- /dev/null +++ b/Task/Hash-join/Scala/hash-join.scala @@ -0,0 +1,19 @@ +def join[Type](left: Seq[Seq[Type]], right: Seq[Seq[Type]]) = { + val hash = right.groupBy(_.head) withDefaultValue Seq() + left.flatMap(cols => hash(cols.last).map(cols ++ _.tail)) +} + +// Example: + +val table1 = List(List("27", "Jonah"), + List("18", "Alan"), + List("28", "Glory"), + List("18", "Popeye"), + List("28", "Alan")) +val table2 = List(List("Jonah", "Whales"), + List("Jonah", "Spiders"), + List("Alan", "Ghosts"), + List("Alan", "Zombies"), + List("Glory", "Buffy")) + +println(join(table1, table2) mkString "\n") diff --git a/Task/Hash-join/Scheme/hash-join.ss b/Task/Hash-join/Scheme/hash-join.ss new file mode 100644 index 0000000000..bb647d25d2 --- /dev/null +++ b/Task/Hash-join/Scheme/hash-join.ss @@ -0,0 +1,20 @@ +(use srfi-42) + +(define ages '((27 Jonah) (18 Alan) (28 Glory) (18 Popeye) (28 Alan))) + +(define nemeses '((Jonah Whales) (Jonah Spiders) (Alan Ghosts) + (Alan Zombies) (Glory Buffy) + (unknown nothing))) + +(define hash (make-hash-table 'equal?)) + +(dolist (item ages) + (hash-table-push! hash (last item) (car item))) + +(do-ec + (: person nemeses) + (:let name (car person)) + (if (hash-table-exists? hash name)) + (: age (~ hash name)) + (print (list (list age name) + person))) diff --git a/Task/Hash-join/TXR/hash-join.txr b/Task/Hash-join/TXR/hash-join.txr new file mode 100644 index 0000000000..73dc78b5de --- /dev/null +++ b/Task/Hash-join/TXR/hash-join.txr @@ -0,0 +1,20 @@ +@(do + (defvar age-name '((27 Jonah) + (18 Alan) + (28 Glory) + (18 Popeye) + (28 Alan))) + + (defvar nemesis-name '((Jonah Whales) + (Jonah Spiders) + (Alan Ghosts) + (Alan Zombies) + (Glory Buffy))) + + (defun hash-join (left left-key right right-key) + (let ((join-hash [group-by left-key left])) ;; hash phase + (append-each ((r-entry right)) ;; join phase + (collect-each ((l-entry [join-hash [right-key r-entry]])) + ^(,l-entry ,r-entry))))) + + (format t "~s\n" [hash-join age-name second nemesis-name first])) diff --git a/Task/Hash-join/Tcl/hash-join.tcl b/Task/Hash-join/Tcl/hash-join.tcl new file mode 100644 index 0000000000..a6185ac0b9 --- /dev/null +++ b/Task/Hash-join/Tcl/hash-join.tcl @@ -0,0 +1,39 @@ +package require Tcl 8.6 +# Only for lmap, which can be replaced with foreach + +proc joinTables {tableA a tableB b} { + # Optimisation: if the first table is longer, do in reverse order + if {[llength $tableB] < [llength $tableA]} { + return [lmap pair [joinTables $tableB $b $tableA $a] { + lreverse $pair + }] + } + + foreach value $tableA { + lappend hashmap([lindex $value $a]) [lreplace $value $a $a] + #dict version# dict lappend hashmap [lindex $value $a] [lreplace $value $a $a] + } + set result {} + foreach value $tableB { + set key [lindex $value $b] + if {![info exists hashmap($key)]} continue + #dict version# if {![dict exists $hashmap $key]} continue + foreach first $hashmap($key) { + #dict version# foreach first [dict get $hashmap $key] + lappend result [list {*}$first $key {*}[lreplace $value $b $b]] + } + } + return $result +} + +set tableA { + {27 "Jonah"} {18 "Alan"} {28 "Glory"} {18 "Popeye"} {28 "Alan"} +} +set tableB { + {"Jonah" "Whales"} {"Jonah" "Spiders"} {"Alan" "Ghosts"} {"Alan" "Zombies"} + {"Glory" "Buffy"} +} +set joined [joinTables $tableA 1 $tableB 0] +foreach row $joined { + puts $row +} diff --git a/Task/Hello-world-Newbie/00DESCRIPTION b/Task/Hello-world-Newbie/00DESCRIPTION new file mode 100644 index 0000000000..83b4dc0ee4 --- /dev/null +++ b/Task/Hello-world-Newbie/00DESCRIPTION @@ -0,0 +1,13 @@ +Guide a new user of a language through the steps necessary +to install the programming language and selection of a [[Editor|text editor]] if needed, +to run the languages' example in the [[Hello world/Text]] task. +* Assume the language-newbie is a programmer in another language. +* Assume the language-newbie is competent in installing software for the platform. +* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor). +* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here). +* Remember to state where to view the output. +* If particular IDE's or editors are required that are not standard, then point to/explain their installation too. + +;Note: +* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated. +* You may use sub-headings if giving instructions for multiple platforms. diff --git a/Task/Hello-world-Newbie/ALGOL-68/hello-world-newbie.alg b/Task/Hello-world-Newbie/ALGOL-68/hello-world-newbie.alg new file mode 100644 index 0000000000..bb912a9c4e --- /dev/null +++ b/Task/Hello-world-Newbie/ALGOL-68/hello-world-newbie.alg @@ -0,0 +1,3 @@ +main: ( + printf($"Goodbye, World!"l$) +) diff --git a/Task/Hello-world-Newbie/AWK/hello-world-newbie.awk b/Task/Hello-world-Newbie/AWK/hello-world-newbie.awk new file mode 100644 index 0000000000..006089e07b --- /dev/null +++ b/Task/Hello-world-Newbie/AWK/hello-world-newbie.awk @@ -0,0 +1,3 @@ +BEGIN { + print "Hello" 3-1 "U", sprintf("%c",33) +} diff --git a/Task/Hello-world-Newbie/AutoHotkey/hello-world-newbie.ahk b/Task/Hello-world-Newbie/AutoHotkey/hello-world-newbie.ahk new file mode 100644 index 0000000000..6729d18e90 --- /dev/null +++ b/Task/Hello-world-Newbie/AutoHotkey/hello-world-newbie.ahk @@ -0,0 +1 @@ +MsgBox, Hello World! diff --git a/Task/Hello-world-Newbie/COBOL/hello-world-newbie-1.cobol b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-1.cobol new file mode 100644 index 0000000000..d347b19f08 --- /dev/null +++ b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-1.cobol @@ -0,0 +1 @@ +$ sudo apt-get install open-cobol diff --git a/Task/Hello-world-Newbie/COBOL/hello-world-newbie-2.cobol b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-2.cobol new file mode 100644 index 0000000000..ae66ec22c6 --- /dev/null +++ b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-2.cobol @@ -0,0 +1,7 @@ +program-id. hello-world. + +procedure division. + display "Hello, World!" + + goback + . diff --git a/Task/Hello-world-Newbie/COBOL/hello-world-newbie-3.cobol b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-3.cobol new file mode 100644 index 0000000000..9ca85b4951 --- /dev/null +++ b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-3.cobol @@ -0,0 +1 @@ +$ cobc -x -Wall -free ./hello.cob diff --git a/Task/Hello-world-Newbie/COBOL/hello-world-newbie-4.cobol b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-4.cobol new file mode 100644 index 0000000000..ac9a63d7ab --- /dev/null +++ b/Task/Hello-world-Newbie/COBOL/hello-world-newbie-4.cobol @@ -0,0 +1,2 @@ +$ ./hello +Hello, World! diff --git a/Task/Hello-world-Newbie/Clojure/hello-world-newbie-1.clj b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-1.clj new file mode 100644 index 0000000000..6331c40f47 --- /dev/null +++ b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-1.clj @@ -0,0 +1 @@ +$ lein new app my-hello diff --git a/Task/Hello-world-Newbie/Clojure/hello-world-newbie-2.clj b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-2.clj new file mode 100644 index 0000000000..8984860c6b --- /dev/null +++ b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-2.clj @@ -0,0 +1,3 @@ +$ cd my-hello +$ lein run +Hello, World! diff --git a/Task/Hello-world-Newbie/Clojure/hello-world-newbie-3.clj b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-3.clj new file mode 100644 index 0000000000..80aa575eca --- /dev/null +++ b/Task/Hello-world-Newbie/Clojure/hello-world-newbie-3.clj @@ -0,0 +1 @@ +$ lein repl diff --git a/Task/Hello-world-Newbie/D/hello-world-newbie.d b/Task/Hello-world-Newbie/D/hello-world-newbie.d new file mode 100644 index 0000000000..447b3b7fad --- /dev/null +++ b/Task/Hello-world-Newbie/D/hello-world-newbie.d @@ -0,0 +1,6 @@ +import std.stdio; + +void main() +{ + writeln("Hello world!"); +} diff --git a/Task/Hello-world-Newbie/Erlang/hello-world-newbie.erl b/Task/Hello-world-Newbie/Erlang/hello-world-newbie.erl new file mode 100644 index 0000000000..fe27008f47 --- /dev/null +++ b/Task/Hello-world-Newbie/Erlang/hello-world-newbie.erl @@ -0,0 +1,6 @@ +% Implemented by Arjun Sunel +-module(helloworld). +-export([main/0]). + +main() -> + io:fwrite("Hello world!\n"). diff --git a/Task/Hello-world-Newbie/Haskell/hello-world-newbie-1.hs b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-1.hs new file mode 100644 index 0000000000..d021d2fb44 --- /dev/null +++ b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-1.hs @@ -0,0 +1 @@ +$ sudo apt-get install ghc diff --git a/Task/Hello-world-Newbie/Haskell/hello-world-newbie-2.hs b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-2.hs new file mode 100644 index 0000000000..39cf248329 --- /dev/null +++ b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-2.hs @@ -0,0 +1,4 @@ +$ touch hello.hs +$ cat > hello.hs << HERE +main = putStrLn "Hello, World!" +HERE diff --git a/Task/Hello-world-Newbie/Haskell/hello-world-newbie-3.hs b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-3.hs new file mode 100644 index 0000000000..c0dfd6b326 --- /dev/null +++ b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-3.hs @@ -0,0 +1 @@ +$ ghc hello.hs -o hello diff --git a/Task/Hello-world-Newbie/Haskell/hello-world-newbie-4.hs b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-4.hs new file mode 100644 index 0000000000..ac9a63d7ab --- /dev/null +++ b/Task/Hello-world-Newbie/Haskell/hello-world-newbie-4.hs @@ -0,0 +1,2 @@ +$ ./hello +Hello, World! diff --git a/Task/Hello-world-Newbie/J/hello-world-newbie.j b/Task/Hello-world-Newbie/J/hello-world-newbie.j new file mode 100644 index 0000000000..ff76edc774 --- /dev/null +++ b/Task/Hello-world-Newbie/J/hello-world-newbie.j @@ -0,0 +1 @@ +'Goodbye, World!' diff --git a/Task/Hello-world-Newbie/Locomotive-Basic/hello-world-newbie.locomotive b/Task/Hello-world-Newbie/Locomotive-Basic/hello-world-newbie.locomotive new file mode 100644 index 0000000000..8cad9413a4 --- /dev/null +++ b/Task/Hello-world-Newbie/Locomotive-Basic/hello-world-newbie.locomotive @@ -0,0 +1,2 @@ +10 print "Goodbye, World!" +run diff --git a/Task/Hello-world-Newbie/OCaml/hello-world-newbie-1.ocaml b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-1.ocaml new file mode 100644 index 0000000000..bb7a2d2ad4 --- /dev/null +++ b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-1.ocaml @@ -0,0 +1 @@ +print_string "Hello world!\n";; diff --git a/Task/Hello-world-Newbie/OCaml/hello-world-newbie-2.ocaml b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-2.ocaml new file mode 100644 index 0000000000..b571b1367a --- /dev/null +++ b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-2.ocaml @@ -0,0 +1 @@ +ocamlc -o hello hello.ml diff --git a/Task/Hello-world-Newbie/OCaml/hello-world-newbie-3.ocaml b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-3.ocaml new file mode 100644 index 0000000000..37cb64306d --- /dev/null +++ b/Task/Hello-world-Newbie/OCaml/hello-world-newbie-3.ocaml @@ -0,0 +1 @@ +./hello diff --git a/Task/Hello-world-Newbie/PARI-GP/hello-world-newbie.pari b/Task/Hello-world-Newbie/PARI-GP/hello-world-newbie.pari new file mode 100644 index 0000000000..f7cf60e14f --- /dev/null +++ b/Task/Hello-world-Newbie/PARI-GP/hello-world-newbie.pari @@ -0,0 +1 @@ +print("Hello, world!") diff --git a/Task/Hello-world-Newbie/Perl/hello-world-newbie.pl b/Task/Hello-world-Newbie/Perl/hello-world-newbie.pl new file mode 100644 index 0000000000..d1869628df --- /dev/null +++ b/Task/Hello-world-Newbie/Perl/hello-world-newbie.pl @@ -0,0 +1,69 @@ +=head1 Obtaining perl + +On the majority of UNIX and UNIX-like operating systems +(Linux, Solaris, AIX, HPUX, et cetera), perl will already be installed. +Mac OS X also ships with perl. +Note that "Perl" refers to the language +while "perl" refers to the interpreter used to run Perl programs. + +Windows does not ship with perl. Instead, you will have to install one of +the following perl distributions: + +=over 4 + +=item Strawberry Perl + +L: A 100% Open Source Perl for +Windows that is exactly the same as Perl everywhere else; this includes using +modules from CPAN, without the need for binary packages. + +=item DWIM Perl for Windows + +L: A 100% Open Source +Perl for Windows, based on Strawberry Perl. +It aims to include as many useful CPAN modules as possible. + +=item ActiveState Perl + +L + +=back + +Links and further instructions on installation can be found on +L. + +Once perl is installed, the task of printing "Hello, World!" is quite simple. +From the command line, first check if your environment's C variable +knows where to find perl. +On most systems, this can be achieved by entering C; +if it spits out something like F, you're good to go! +If it tells you + + which: no perl in (...) + +it means you need to add perl to your environment's C variable. +This is done on most systems by entering + + export PATH=$PATH:[...] + +where [...] is the full path to your perl installation (usually /usr/bin/perl). + +If you do not have the C command, you can probably just type C +to see if it fires up the perl interpreter. +If it does, press Ctrl+D to exit it and proceed. +Otherwise, perform the steps above to add perl to your PATH variable. + +Once perl is installed, one-liners can be executed from the command line +by invoking perl with the C<-e> switch. + $ perl -e 'print "Hello, World!\n";' +To create a script file that's more permanent, it can be put in a text file. +The name can be anything, but F<.pl> is encouraged. +The #!/usr/bin/perl at the beginning is called the shebang line; +if the operating system supports it, it tells where to find the perl interpreter. +If the script is run with C, this line will be ignored-- +this is for invoking the file as an executable. + +=cut + +#!/usr/bin/perl +print "Hello, World!\n"; diff --git a/Task/Hello-world-Newbie/Python/hello-world-newbie.py b/Task/Hello-world-Newbie/Python/hello-world-newbie.py new file mode 100644 index 0000000000..a9f594ad30 --- /dev/null +++ b/Task/Hello-world-Newbie/Python/hello-world-newbie.py @@ -0,0 +1 @@ +print "Goodbye, World!" diff --git a/Task/Hello-world-Newbie/README b/Task/Hello-world-Newbie/README new file mode 100644 index 0000000000..ee25f23754 --- /dev/null +++ b/Task/Hello-world-Newbie/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Hello_world/Newbie diff --git a/Task/Hello-world-Newbie/REXX/hello-world-newbie.rexx b/Task/Hello-world-Newbie/REXX/hello-world-newbie.rexx new file mode 100644 index 0000000000..598a8ce5b6 --- /dev/null +++ b/Task/Hello-world-Newbie/REXX/hello-world-newbie.rexx @@ -0,0 +1,2 @@ +/*REXX program to greet the world enthusiastically. */ +say "Hello world!" diff --git a/Task/Hello-world-Newbie/Rust/hello-world-newbie.rust b/Task/Hello-world-Newbie/Rust/hello-world-newbie.rust new file mode 100644 index 0000000000..e0b5e275a6 --- /dev/null +++ b/Task/Hello-world-Newbie/Rust/hello-world-newbie.rust @@ -0,0 +1,3 @@ +fn main() { + println!("Hello world!"); +} diff --git a/Task/Hello-world-Newbie/Scala/hello-world-newbie.scala b/Task/Hello-world-Newbie/Scala/hello-world-newbie.scala new file mode 100644 index 0000000000..1bc761c155 --- /dev/null +++ b/Task/Hello-world-Newbie/Scala/hello-world-newbie.scala @@ -0,0 +1 @@ +scala -e 'println(\"Hello_world\")' diff --git a/Task/Hello-world-Newbie/TI-83-BASIC/hello-world-newbie.ti-83 b/Task/Hello-world-Newbie/TI-83-BASIC/hello-world-newbie.ti-83 new file mode 100644 index 0000000000..74348a800e --- /dev/null +++ b/Task/Hello-world-Newbie/TI-83-BASIC/hello-world-newbie.ti-83 @@ -0,0 +1,2 @@ +PROGRAM:MYPROGRM +:Disp "HELLO, WORLD!" diff --git a/Task/Hello-world-Newbie/Tcl/hello-world-newbie.tcl b/Task/Hello-world-Newbie/Tcl/hello-world-newbie.tcl new file mode 100644 index 0000000000..b85a0422ff --- /dev/null +++ b/Task/Hello-world-Newbie/Tcl/hello-world-newbie.tcl @@ -0,0 +1 @@ +puts "Hello World" diff --git a/Task/Hello-world-Newbie/ZX-Spectrum-Basic/hello-world-newbie.zx b/Task/Hello-world-Newbie/ZX-Spectrum-Basic/hello-world-newbie.zx new file mode 100644 index 0000000000..7bf0a45ac1 --- /dev/null +++ b/Task/Hello-world-Newbie/ZX-Spectrum-Basic/hello-world-newbie.zx @@ -0,0 +1 @@ +10 PRINT "Hello" diff --git a/Task/Heronian-triangles/00DESCRIPTION b/Task/Heronian-triangles/00DESCRIPTION new file mode 100644 index 0000000000..a6616f4325 --- /dev/null +++ b/Task/Heronian-triangles/00DESCRIPTION @@ -0,0 +1,29 @@ +[[wp:Heron's formula|Hero's formula]] for the area of a triangle given the length of its three sides +''a'', ''b'', and ''c'' is given by: + +:A = \sqrt{s(s-a)(s-b)(s-c)}, + +where ''s'' is half the perimeter of the triangle; that is, + +:s=\frac{a+b+c}{2}. + +'''[http://www.had2know.com/academics/heronian-triangles-generator-calculator.html Heronian triangles]''' +are triangles whose sides ''and area'' are all integers. +:An example is the triangle with sides 3, 4, 5 whose area is 6 (and whose perimeter is 12). + +Note that any triangle whose sides are all an integer multiple of 3,4,5; such as 6,8,10, will +also be a Heronian triangle. + +Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor +of all three sides is 1. This will exclude, for example triangle 6,8,10 + +'''The task''' is to: +# Create a named function/method/procedure/... that implements Hero's formula. +# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. +# Show the count of how many triangles are found. +# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths +# Show the first ten ordered triangles in a table of sides, perimeter, and area. +# Show a similar ordered table for those triangles with area = 210 +Show all output here. + +'''Note''': when generating triangles it may help to restrict a <= b <= c diff --git a/Task/Heronian-triangles/D/heronian-triangles.d b/Task/Heronian-triangles/D/heronian-triangles.d new file mode 100644 index 0000000000..6a2109aca9 --- /dev/null +++ b/Task/Heronian-triangles/D/heronian-triangles.d @@ -0,0 +1,45 @@ +import std.stdio, std.math, std.range, std.algorithm, std.numeric, std.traits, std.typecons; + +double hero(in uint a, in uint b, in uint c) pure nothrow @safe @nogc { + immutable s = (a + b + c) / 2.0; + immutable a2 = s * (s - a) * (s - b) * (s - c); + return (a2 > 0) ? a2.sqrt : 0.0; +} + +bool isHeronian(in uint a, in uint b, in uint c) pure nothrow @safe @nogc { + immutable h = hero(a, b, c); + return h > 0 && h.floor == h.ceil; +} + +T gcd3(T)(in T x, in T y, in T z) pure nothrow @safe @nogc { + return gcd(gcd(x, y), z); +} + +void main() /*@safe*/ { + enum uint maxSide = 200; + + // Sort by increasing area, perimeter, then sides. + //auto h = cartesianProduct!3(iota(1, maxSide + 1)) + auto r = iota(1, maxSide + 1); + const h = cartesianProduct(r, r, r) + //.filter!({a, b, c} => ... + .filter!(t => t[0] <= t[1] && t[1] <= t[2] && + t[0] + t[1] > t[2] && + t[].gcd3 == 1 && t[].isHeronian) + .array + .schwartzSort!(t => tuple(t[].hero, t[].only.sum, t.reverse)) + .release; + + static void showTriangles(R)(R ts) @safe { + "Area Perimeter Sides".writeln; + foreach (immutable t; ts) + writefln("%3s %8d %3dx%dx%d", t[].hero, t[].only.sum, t[]); + } + + writefln("Primitive Heronian triangles with sides up to %d: %d", maxSide, h.length); + "\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:".writeln; + showTriangles(h.take(10)); + + "\nAll with area 210 subject to the previous ordering:".writeln; + showTriangles(h.filter!(t => t[].hero == 210)); +} diff --git a/Task/Heronian-triangles/Haskell/heronian-triangles.hs b/Task/Heronian-triangles/Haskell/heronian-triangles.hs new file mode 100644 index 0000000000..dbbf2ea1fd --- /dev/null +++ b/Task/Heronian-triangles/Haskell/heronian-triangles.hs @@ -0,0 +1,63 @@ +import qualified Data.List as L +import Data.Maybe +import Data.Ord +import Text.Printf + +-- Determine if a number n is a perfect square and return its square root if so. +-- This is used instead of sqrt to avoid fixed sized floating point numbers. +perfectSqrt :: Integral a => a -> Maybe a +perfectSqrt n + | n == 1 = Just 1 + | n < 4 = Nothing + | otherwise = + let search low high = + let guess = (low + high) `div` 2 + square = guess ^ 2 + next + | square == n = Just guess + | low == guess = Nothing + | square < n = search guess high + | otherwise = search low guess + in next + in search 0 n + +-- Determine the area of a Heronian triangle if it is one. +heronTri :: Integral a => a -> a -> a -> Maybe a +heronTri a b c = + let -- Rewrite Heron's formula to factor out the term 16 under the root. + areaSq16 = (a + b + c) * (b + c - a) * (a + c - b) * (a + b - c) + (areaSq, r) = areaSq16 `divMod` 16 + in if r == 0 + then perfectSqrt areaSq + else Nothing + +isPrimitive :: Integral a => a -> a -> a -> a +isPrimitive a b c = gcd a (gcd b c) + +third (_, _, x, _, _) = x +fourth (_, _, _, x, _) = x +fifth (_, _, _, _, x) = x + +orders :: Ord b => [(a -> b)] -> a -> a -> Ordering +orders [f] a b = comparing f a b +orders (f:fx) a b = + case comparing f a b of + EQ -> orders fx a b + n -> n + +main :: IO () +main = do + let range = [1 .. 200] + tris :: [(Integer, Integer, Integer, Integer, Integer)] + tris = L.sortBy (orders [fifth, fourth, third]) + $ map (\(a, b, c, d, e) -> (a, b, c, d, fromJust e)) + $ filter (isJust . fifth) + [(a, b, c, a + b + c, heronTri a b c) + | a <- range, b <- range, c <- range + , a <= b, b <= c, isPrimitive a b c == 1] + printTri (a, b, c, d, e) = printf "%3d %3d %3d %9d %4d\n" a b c d e + printf "Heronian triangles found: %d\n\n" $ length tris + putStrLn " Sides Perimeter Area" + mapM_ printTri $ take 10 tris + putStrLn "" + mapM_ printTri $ filter ((== 210) . fifth) tris diff --git a/Task/Heronian-triangles/J/heronian-triangles-1.j b/Task/Heronian-triangles/J/heronian-triangles-1.j new file mode 100644 index 0000000000..4f428a035d --- /dev/null +++ b/Task/Heronian-triangles/J/heronian-triangles-1.j @@ -0,0 +1,9 @@ +a=:0&{"1 +b=:1&{"1 +c=:2&{"1 +s=:(a+b+c)%2: +A=:2 %: s*(s-a)*(s-b)*(s-c) +P=:+/"1 +isprimhero=:(0&~:*(=<.@+))@A*1=a+.b+.c + +tri=: (/: A,.P,.{:"1) (#~ isprimhero)~./:"1~1+200 200 200#:i.200^3 diff --git a/Task/Heronian-triangles/J/heronian-triangles-2.j b/Task/Heronian-triangles/J/heronian-triangles-2.j new file mode 100644 index 0000000000..4852956e0a --- /dev/null +++ b/Task/Heronian-triangles/J/heronian-triangles-2.j @@ -0,0 +1,22 @@ + #tri +517 + + 10{.(,._,.A,.P) tri + 3 4 5 _ 6 12 + 5 5 6 _ 12 16 + 5 5 8 _ 12 18 + 4 13 15 _ 24 32 + 5 12 13 _ 30 30 + 9 10 17 _ 36 36 + 3 25 26 _ 36 54 + 7 15 20 _ 42 42 +10 13 13 _ 60 36 + 8 15 17 _ 60 40 + + (#~210=A) (,._,.A,.P) tri +17 25 28 _ 210 70 +20 21 29 _ 210 70 +12 35 37 _ 210 84 +17 28 39 _ 210 84 + 7 65 68 _ 210 140 + 3 148 149 _ 210 300 diff --git a/Task/Heronian-triangles/Java/heronian-triangles-1.java b/Task/Heronian-triangles/Java/heronian-triangles-1.java new file mode 100644 index 0000000000..c93822fcb2 --- /dev/null +++ b/Task/Heronian-triangles/Java/heronian-triangles-1.java @@ -0,0 +1,57 @@ +import java.util.ArrayList; +public class Heron { + public static void main(String[] args) { + ArrayList list = new ArrayList(); + for(int c = 1; c <= 200; c++){ + for(int b = 1; b <= c; b++){ + for(int a = 1; a <= b; a++){ + if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c) + list.add(new int[]{a, b, c, a + b + c, (int)heronArea(a, b, c)}); + } + } + } + sort(list); + System.out.printf("Number of primitive Heronian triangles with sides up to 200: %d\n\nFirst ten when ordered by increasing area, then perimeter:\nSides Perimeter Area", list.size()); + for(int i = 0; i < 10; i++){ + System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); + } + System.out.printf("\n\nArea = 210\nSides Perimeter Area"); + for(int i = 0; i < list.size(); i++){ + if(list.get(i)[4] == 210) + System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); + } + } + public static double heronArea(int a, int b, int c){ + double s = (a + b + c)/ 2f; + return Math.sqrt(s *(s -a)*(s - b)*(s - c)); + } + public static boolean isHeron(double h){ + return h % 1 == 0 && h > 0; + } + public static int gcd(int a, int b){ + int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a; + while(leftover != 0){ + leftover = dividend % divisor; + if(leftover > 0){ + dividend = divisor; + divisor = leftover; + } + } + return divisor; + } + public static void sort(ArrayList list){ + boolean swapped = true; + int[] temp; + while(swapped){ + swapped = false; + for(int i = 1; i < list.size(); i++){ + if(list.get(i)[4] < list.get(i - 1)[4] || list.get(i)[4] == list.get(i - 1)[4] && list.get(i)[3] < list.get(i - 1)[3]){ + temp = list.get(i); + list.set(i, list.get(i - 1)); + list.set(i - 1, temp); + swapped = true; + } + } + } + } +} diff --git a/Task/Heronian-triangles/Java/heronian-triangles-2.java b/Task/Heronian-triangles/Java/heronian-triangles-2.java new file mode 100644 index 0000000000..4e65cc8305 --- /dev/null +++ b/Task/Heronian-triangles/Java/heronian-triangles-2.java @@ -0,0 +1,23 @@ +Number of primitive Heronian triangles with sides up to 200: 517 + +First ten when ordered by increasing area, then perimeter: +Sides Perimeter Area +3 x 4 x 5 12 6 +5 x 5 x 6 16 12 +5 x 5 x 8 18 12 +4 x 13 x 15 32 24 +5 x 12 x 13 30 30 +9 x 10 x 17 36 36 +3 x 25 x 26 54 36 +7 x 15 x 20 42 42 +10 x 13 x 13 36 60 +8 x 15 x 17 40 60 + +Area = 210 +Sides Perimeter Area +17 x 25 x 28 70 210 +20 x 21 x 29 70 210 +12 x 35 x 37 84 210 +17 x 28 x 39 84 210 +7 x 65 x 68 140 210 +3 x 148 x 149 300 210 diff --git a/Task/Heronian-triangles/JavaScript/heronian-triangles-1.js b/Task/Heronian-triangles/JavaScript/heronian-triangles-1.js new file mode 100644 index 0000000000..33f903fe5f --- /dev/null +++ b/Task/Heronian-triangles/JavaScript/heronian-triangles-1.js @@ -0,0 +1,50 @@ +window.onload = function(){ + var list = []; + var j = 0; + for(var c = 1; c <= 200; c++) + for(var b = 1; b <= c; b++) + for(var a = 1; a <= b; a++) + if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c))) + list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c)); + sort(list); + document.write("

Primitive Heronian triangles with sides up to 200: " + list.length + "

First ten when ordered by increasing area, then perimeter:

"); + for(var i = 0; i < 10; i++) + document.write(""); + document.write("
SidesPerimeterArea
" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "" + list[i][3] + "" + list[i][4] + "

Area = 210

"); + for(var i = 0; i < list.length; i++) + if(list[i][4] == 210) + document.write(""); + function heronArea(a, b, c){ + var s = (a + b + c)/ 2; + return Math.sqrt(s *(s -a)*(s - b)*(s - c)); + } + function isHeron(h){ + return h % 1 == 0 && h > 0; + } + function gcd(a, b){ + var leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a; + while(leftover != 0){ + leftover = dividend % divisor; + if(leftover > 0){ + dividend = divisor; + divisor = leftover; + } + } + return divisor; + } + function sort(list){ + var swapped = true; + var temp = []; + while(swapped){ + swapped = false; + for(var i = 1; i < list.length; i++){ + if(list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){ + temp = list[i]; + list[i] = list[i - 1]; + list[i - 1] = temp; + swapped = true; + } + } + } + } +} diff --git a/Task/Heronian-triangles/JavaScript/heronian-triangles-2.js b/Task/Heronian-triangles/JavaScript/heronian-triangles-2.js new file mode 100644 index 0000000000..c4aad17b75 --- /dev/null +++ b/Task/Heronian-triangles/JavaScript/heronian-triangles-2.js @@ -0,0 +1,23 @@ +Primitive Heronian triangles with sides up to 200: 517 + +First ten when ordered by increasing area, then perimeter: +Sides Perimeter Area +3 x 4 x 5 12 6 +5 x 5 x 6 16 12 +5 x 5 x 8 18 12 +4 x 13 x 15 32 24 +5 x 12 x 13 30 30 +9 x 10 x 17 36 36 +3 x 25 x 26 54 36 +7 x 15 x 20 42 42 +10 x 13 x 13 36 60 +8 x 15 x 17 40 60 + +Area = 210 +Sides Perimeter Area +17 x 25 x 28 70 210 +20 x 21 x 29 70 210 +12 x 35 x 37 84 210 +17 x 28 x 39 84 210 +7 x 65 x 68 140 210 +3 x 148 x 149 300 210 diff --git a/Task/Heronian-triangles/Perl-6/heronian-triangles.pl6 b/Task/Heronian-triangles/Perl-6/heronian-triangles.pl6 new file mode 100644 index 0000000000..14e16b0c84 --- /dev/null +++ b/Task/Heronian-triangles/Perl-6/heronian-triangles.pl6 @@ -0,0 +1,42 @@ +sub hero($a, $b, $c) { + my $s = ($a + $b + $c) / 2; + my $a2 = $s * ($s - $a) * ($s - $b) * ($s - $c); + $a2.sqrt; +} + +sub heronian-area($a, $b, $c) { + $_ when Int given hero($a, $b, $c).narrow; +} + +sub primitive-heronian-area($a, $b, $c) { + heronian-area $a, $b, $c + if 1 == [gcd] $a, $b, $c; +} + +sub show { + say " Area Perimeter Sides"; + for @_ -> [$area, $perim, $c, $b, $a] { + printf "%6d %6d %12s\n", $area, $perim, "$a×$b×$c"; + } +} + +sub MAIN ($maxside = 200, $first = 10, $witharea = 210) { + my \h = sort gather + for 1 .. $maxside -> $c { + for 1 .. $c -> $b { + for $c - $b + 1 .. $b -> $a { + if primitive-heronian-area($a,$b,$c) -> $area { + take [$area, $a+$b+$c, $c, $b, $a]; + } + } + } + } + + say "Primitive Heronian triangles with sides up to $maxside: ", +h; + + say "\nFirst $first:"; + show h[^$first]; + + say "\nArea $witharea:"; + show h.grep: *[0] == $witharea; +} diff --git a/Task/Heronian-triangles/Perl/heronian-triangles.pl b/Task/Heronian-triangles/Perl/heronian-triangles.pl new file mode 100644 index 0000000000..9f93717b4e --- /dev/null +++ b/Task/Heronian-triangles/Perl/heronian-triangles.pl @@ -0,0 +1,63 @@ +use strict; +use warnings; +use List::Util qw(max); + +sub gcd { $_[1] == 0 ? $_[0] : gcd($_[1], $_[0] % $_[1]) } + +sub hero { + my ($a, $b, $c) = @_[0,1,2]; + my $s = ($a + $b + $c) / 2; + sqrt $s*($s - $a)*($s - $b)*($s - $c); +} + +sub heronian_area { + my $hero = hero my ($a, $b, $c) = @_[0,1,2]; + sprintf("%.0f", $hero) eq $hero ? $hero : 0 +} + +sub primitive_heronian_area { + my ($a, $b, $c) = @_[0,1,2]; + heronian_area($a, $b, $c) if 1 == gcd $a, gcd $b, $c; +} + +sub show { + print " Area Perimeter Sides\n"; + for (@_) { + my ($area, $perim, $c, $b, $a) = @$_; + printf "%7d %9d %d×%d×%d\n", $area, $perim, $a, $b, $c; + } +} + +sub main { + my $maxside = shift // 200; + my $first = shift // 10; + my $witharea = shift // 210; + my @h; + for my $c (1 .. $maxside) { + for my $b (1 .. $c) { + for my $a ($c - $b + 1 .. $b) { + if (my $area = primitive_heronian_area $a, $b, $c) { + push @h, [$area, $a+$b+$c, $c, $b, $a]; + } + } + } + } + @h = sort { + $a->[0] <=> $b->[0] + or + $a->[1] <=> $b->[1] + or + max(@$a[2,3,4]) <=> max(@$b[2,3,4]) + } @h; + printf "Primitive Heronian triangles with sides up to %d: %d\n", + $maxside, + scalar @h; + print "First:\n"; + show @h[0 .. $first - 1]; + print "Area $witharea:\n"; + show grep { $_->[0] == $witharea } @h; + + +} + +&main(); diff --git a/Task/Heronian-triangles/PowerShell/heronian-triangles-1.psh b/Task/Heronian-triangles/PowerShell/heronian-triangles-1.psh new file mode 100644 index 0000000000..cc58872035 --- /dev/null +++ b/Task/Heronian-triangles/PowerShell/heronian-triangles-1.psh @@ -0,0 +1,47 @@ +function Get-Gcd($a, $b){ + if($a -ge $b){ + $dividend = $a + $divisor = $b + } + else{ + $dividend = $b + $divisor = $a + } + $leftover = 1 + while($leftover -ne 0){ + $leftover = $dividend % $divisor + if($leftover -ne 0){ + $dividend = $divisor + $divisor = $leftover + } + } + $divisor +} +function Is-Heron($heronArea){ + $heronArea -gt 0 -and $heronArea % 1 -eq 0 +} +function Get-HeronArea($a, $b, $c){ + $s = ($a + $b + $c) / 2 + [math]::Sqrt($s * ($s - $a) * ($s - $b) * ($s - $c)) +} +$result = @() +foreach ($c in 1..200){ + for($b = 1; $b -le $c; $b++){ + for($a = 1; $a -le $b; $a++){ + if((Get-Gcd $c (Get-Gcd $b $a)) -eq 1 -and (Is-Heron(Get-HeronArea $a $b $c))){ + $result += @(,@($a, $b, $c,($a + $b + $c), (Get-HeronArea $a $b $c))) + } + } + } +} +$result = $result | sort-object @{Expression={$_[4]}}, @{Expression={$_[3]}}, @{Expression={$_[2]}} +"Primitive Heronian triangles with sides up to 200: $($result.length)`nFirst ten when ordered by increasing area, then perimeter,then maximum sides:`nSides`t`t`t`tPerimeter`tArea" +for($i = 0; $i -lt 10; $i++){ +"$($result[$i][0])`t$($result[$i][1])`t$($result[$i][2])`t`t`t$($result[$i][3])`t`t`t$($result[$i][4])" +} +"`nArea = 210`nSides`t`t`t`tPerimeter`tArea" +foreach($i in $result){ + if($i[4] -eq 210){ + "$($i[0])`t$($i[1])`t$($i[2])`t`t`t$($i[3])`t`t`t$($i[4])" + } +} diff --git a/Task/Heronian-triangles/PowerShell/heronian-triangles-2.psh b/Task/Heronian-triangles/PowerShell/heronian-triangles-2.psh new file mode 100644 index 0000000000..398cb0dccd --- /dev/null +++ b/Task/Heronian-triangles/PowerShell/heronian-triangles-2.psh @@ -0,0 +1,23 @@ +Primitive Heronian triangles with sides up to 200: 517 + +First ten when ordered by increasing area, then perimeter,then maximum sides: +Sides Perimeter Area +3 4 5 12 6 +5 5 6 16 12 +5 5 8 18 12 +4 13 15 32 24 +5 12 13 30 30 +9 10 17 36 36 +3 25 26 54 36 +7 15 20 42 42 +10 13 13 36 60 +8 15 17 40 60 + +Area = 210 +Sides Perimeter Area +17 25 28 70 210 +20 21 29 70 210 +12 35 37 84 210 +17 28 39 84 210 +7 65 68 140 210 +3 148 149 300 210 diff --git a/Task/Heronian-triangles/Python/heronian-triangles.py b/Task/Heronian-triangles/Python/heronian-triangles.py new file mode 100644 index 0000000000..dfe9173c8d --- /dev/null +++ b/Task/Heronian-triangles/Python/heronian-triangles.py @@ -0,0 +1,33 @@ +from math import sqrt +from fractions import gcd +from itertools import product + + +def hero(a, b, c): + s = (a + b + c) / 2 + a2 = s*(s-a)*(s-b)*(s-c) + return sqrt(a2) if a2 > 0 else 0 + + +def is_heronian(a, b, c): + a = hero(a, b, c) + return a > 0 and a.is_integer() + + +def gcd3(x, y, z): + return gcd(gcd(x, y), z) + + +if __name__ == '__main__': + maxside = 200 + h = [(a, b, c) for a,b,c in product(range(1, maxside + 1), repeat=3) + if a <= b <= c and a + b > c and gcd3(a, b, c) == 1 and is_heronian(a, b, c)] + h.sort(key = lambda x: (hero(*x), sum(x), x[::-1])) # By increasing area, perimeter, then sides + print('Primitive Heronian triangles with sides up to %i:' % maxside, len(h)) + print('\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:') + print('\n'.join(' %14r perim: %3i area: %i' + % (sides, sum(sides), hero(*sides)) for sides in h[:10])) + print('\nAll with area 210 subject to the previous ordering:') + print('\n'.join(' %14r perim: %3i area: %i' + % (sides, sum(sides), hero(*sides)) for sides in h + if hero(*sides) == 210)) diff --git a/Task/Heronian-triangles/README b/Task/Heronian-triangles/README new file mode 100644 index 0000000000..199873c657 --- /dev/null +++ b/Task/Heronian-triangles/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Heronian_triangles diff --git a/Task/Heronian-triangles/REXX/heronian-triangles.rexx b/Task/Heronian-triangles/REXX/heronian-triangles.rexx new file mode 100644 index 0000000000..4a7ed8dfaf --- /dev/null +++ b/Task/Heronian-triangles/REXX/heronian-triangles.rexx @@ -0,0 +1,53 @@ +/*REXX pgm generates primitive Heronian triangles by side length & area.*/ +parse arg N first area . /*get optional N (sides). */ +if N=='' | N==',' then N=200 /*maybe use the default. */ +if first=='' | first==',' then first= 10 /* " " " " */ +if area=='' | area==',' then area=210 /* " " " " */ +numeric digits 99; numeric digits max(9, 1+length(N**5)) /*ensure 'nuff*/ +call Heron /*invoke Heron subroutine. */ +say # ' primitive Heronian triangles found with sides up to ' N " (inclusive)." +call show , 'listing of the first ' first ' primitive Heronian triangles:' +call show area, 'listing of the (above) found primitive Heronian triangles with an area of ' area +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────HERON subroutine────────────────────*/ +Heron: @.=.; #=0; minP=9e9; maxP=0; minA=9e9; maxA=0; Ln=length(N) + #.=0; #.2=1 #.3=1; #.7=1; #.8=1 /*¬good √.*/ + do a=3 to N /*start at a minimum side length.*/ + ev= \ (a//2); inc=1+ev /*if A is even, B & C must be odd*/ + do b=a+ev to N by inc; ab=a+b /*AB: is used for summing below.*/ + do c=b to N by inc; p=ab+c; s=p/2 /*calc Perimeter, S*/ + _=s*(s-a)*(s-b)*(s-c); if _<=0 then iterate /*_ isn't positive.*/ + if pos(.,_)\==0 then iterate /*not an integer. */ + parse var _ '' -1 q ; if #.q then iterate /*not good square. */ + ar=iSQRT(_); if ar*ar\==_ then iterate /*area not integer.*/ + if hGCD(a,b,c)\==1 then iterate /*GCD of sides ¬1. */ + #=#+1 /*got prim. H. tri.*/ + minP=min( p,minP); maxP=max( p,maxP); Lp=length(maxP) + minA=min(ar,minA); maxA=max(ar,maxA); La=length(maxA); @.ar= + if @.ar.p.0==. then @.ar.p.0=0; _=@.ar.p.0+1 /*bump triangle ctr*/ + @.ar.p.0=_; @.ar.p._=right(a,Ln) right(b,Ln) right(c,Ln) /*unique*/ + end /*c*/ /* [↑] keep each unique P items.*/ + end /*b*/ + end /*a*/ +return # /*return # of Heronian triangles.*/ +/*──────────────────────────────────HGCD subroutine─────────────────────*/ +hGCD: procedure; parse arg x; do j=2 for 2 /*sub handles exactly 3 args*/ +y=arg(j); do until y==0; parse value x//y y with y x; end; end; return x +/*──────────────────────────────────ISQRT subroutine────────────────────*/ +iSQRT: procedure; parse arg x; x=x%1; if x==0 | x==1 then return x; q=1 + do while q<=x; q=q*4; end; r=0 /*Q will be > X at loop 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 /* R is a postive integer. */ +/*──────────────────────────────────SHOW subroutine─────────────────────*/ +show: m=0; say; say; parse arg ae; say arg(2); if ae\=='' then first=9e9 +say; y=left('',9) /* [↓] skip the nothings. */ + do i=minA to maxA; if @.i==. then iterate + if ae\=='' & i\==ae then iterate /*Area specified? Then check*/ + do j=minP to maxP until m>=first /*only list FIRST entries.*/ + if @.i.j.0==. then iterate /*Not defined? Then skip it.*/ + do k=1 for @.i.j.0; m=m+1 /*visit each perimeter entry*/ + say right(m,9) y'area:' right(i,La) y"perimeter:" right(j,Lp) y'sides:' @.i.j.k + end /*k*/ + end /*j*/ /* [↑] use known perimeters*/ + end /*i*/ /* [↑] show found triangles*/ +return diff --git a/Task/Heronian-triangles/Racket/heronian-triangles.rkt b/Task/Heronian-triangles/Racket/heronian-triangles.rkt new file mode 100644 index 0000000000..0e3b433579 --- /dev/null +++ b/Task/Heronian-triangles/Racket/heronian-triangles.rkt @@ -0,0 +1,55 @@ +#lang racket +(require xml/xml data/order) + +;; Returns the area of triangle sides a, b, c +(define (A a b c) + (define s (/ (+ a b c) 2)) ; where s=\frac{a+b+c}{2}. + (sqrt (* s (- s a) (- s b) (- s c)))) ; A = \sqrt{s(s-a)(s-b)(s-c)} + +;; Returns same as A iff a, b, c and A are integers; #f otherwise +(define (heronian?-area a b c) + (and (integer? a) (integer? b) (integer? c) + (let ((h (A a b c))) (and (integer? h) h)))) + +;; Returns same as heronian?-area, with the additional condition that (gcd a b c) = 1 +(define (primitive-heronian?-area a b c) + (and (= 1 (gcd a b c)) + (heronian?-area a b c))) + +(define (generate-heronian-triangles max-side) + (for*/list + ((a (in-range 1 (add1 max-side))) + (b (in-range 1 (add1 a))) + (c (in-range 1 (add1 b))) + #:when (< a (+ b c)) + (h (in-value (primitive-heronian?-area a b c))) + #:when h) + (define rv (vector h (+ a b c) (sort (list a b c) >))) ; datum-order can sort this for the tables + rv)) + +;; Order the triangles by first increasing area, then by increasing perimeter, +;; then by increasing maximum side lengths +(define (tritds (match-lambda [`#(,h ,p ,s) `((td ,(~a s)) (td ,(~a p)) (td ,(~a h)))])) + +(define (triangles->table ts) + `(table + (tr (th "#") (th "sides") (th "perimiter") (th "area")) "\n" + ,@(for/list ((i (in-naturals 1)) (t ts)) `(tr (td ,(~a i)) ,@(triangle->tds t) "\n")))) + +(define (sorted-triangles-table triangles) + (triangles->table (sort triangles tristring div-out))) diff --git a/Task/Heronian-triangles/Ruby/heronian-triangles.rb b/Task/Heronian-triangles/Ruby/heronian-triangles.rb new file mode 100644 index 0000000000..72e7404ff7 --- /dev/null +++ b/Task/Heronian-triangles/Ruby/heronian-triangles.rb @@ -0,0 +1,46 @@ +class Triangle + def self.valid?(a,b,c) # class method + short, middle, long = [a, b, c].sort + short + middle > long + end + + attr_reader :sides, :perimeter, :area + + def initialize(a,b,c) + @sides = [a, b, c].sort + @perimeter = a + b + c + s = @perimeter / 2.0 + @area = Math.sqrt(s * (s - a) * (s - b) * (s - c)) + end + + def heronian? + area == area.to_i + end + + def <=>(other) + [area, perimeter, sides] <=> [other.area, other.perimeter, other.sides] + end + + def to_s + "%-11s%6d%8.1f" % [sides.join('x'), perimeter, area] + end +end + +max, area = 200, 210 +prim_triangles = [] +1.upto(max) do |a| + a.upto(max) do |b| + b.upto(max) do |c| + next if a.gcd(b).gcd(c) > 1 + prim_triangles << Triangle.new(a, b, c) if Triangle.valid?(a, b, c) + end + end +end + +sorted = prim_triangles.select(&:heronian?).sort + +puts "Primitive heronian triangles with sides upto #{max}: #{sorted.size}" +puts "\nsides perim. area" +puts sorted.first(10).map(&:to_s) +puts "\nTriangles with an area of: #{area}" +sorted.each{|tr| puts tr if tr.area == area} diff --git a/Task/Hickerson-series-of-almost-integers/00DESCRIPTION b/Task/Hickerson-series-of-almost-integers/00DESCRIPTION new file mode 100644 index 0000000000..aae9265387 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/00DESCRIPTION @@ -0,0 +1,15 @@ +The following function, due to D Hickerson, is said to generate "Almost integers" by the [http://mathworld.wolfram.com/AlmostInteger.html "Almost Integer" page of Wolfram Mathworld]. (December 31 2013). + +The function is: + +:h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}} + +It is said to produce "almost integers" for n between 1 and 17. +The purpose of the task is to verify this assertion. + +Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation + +The task is to calculate all values of the function checking and stating which are "almost integers". + +Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example: + h(18) = 3385534663256845326.39... diff --git a/Task/Hickerson-series-of-almost-integers/Bracmat/hickerson-series-of-almost-integers.bracmat b/Task/Hickerson-series-of-almost-integers/Bracmat/hickerson-series-of-almost-integers.bracmat new file mode 100644 index 0000000000..2915fa9ed4 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Bracmat/hickerson-series-of-almost-integers.bracmat @@ -0,0 +1,28 @@ +( 0:?n +& 1:?fac +& whl + ' ( 1+!n:~>17:?n + & !n*!fac:?fac + & -1:?k + & 0:?L2 + & 0:?oldN + & whl + ' ( 1+!k:?k + & ((2*!k+1)*9^!k)^-1+!L2:?L2 + & !fac*1/2*(2/3*!L2)^(-1*(!n+1)):?N + & div$(1000*!N+1/2.1):?newN + & !newN:~!oldN:?oldN + ) + & out + $ ( str$("h(" !n ") =") + ( div$(!newN.1000):?intpart + & @(!newN:!intpart ?decimalpart) + & str$(!intpart "." !decimalpart) + ) + ( @(!decimalpart:(0|9) ?) + & "is an almost-integer." + | "is NOT an almost-integer." + ) + ) + ) +); diff --git a/Task/Hickerson-series-of-almost-integers/C++/hickerson-series-of-almost-integers.cpp b/Task/Hickerson-series-of-almost-integers/C++/hickerson-series-of-almost-integers.cpp new file mode 100644 index 0000000000..23a4a0b295 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/C++/hickerson-series-of-almost-integers.cpp @@ -0,0 +1,18 @@ +#include +#include +#include +#include +typedef boost::multiprecision::cpp_dec_float_50 decfloat; + +int main() +{ + const decfloat ln_two = boost::math::constants::ln_two(); + decfloat numerator = 1, denominator = ln_two; + + for(int n = 1; n <= 17; n++) { + decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; + decfloat tenths_dig = floor((h - floor(h)) * 10); + std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << + (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; + } +} diff --git a/Task/Hickerson-series-of-almost-integers/C/hickerson-series-of-almost-integers.c b/Task/Hickerson-series-of-almost-integers/C/hickerson-series-of-almost-integers.c new file mode 100644 index 0000000000..533977da93 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/C/hickerson-series-of-almost-integers.c @@ -0,0 +1,29 @@ +#include +#include + +void h(int n) +{ + MPFR_DECL_INIT(a, 200); + MPFR_DECL_INIT(b, 200); + + mpfr_fac_ui(a, n, MPFR_RNDD); // a = n! + + mpfr_set_ui(b, 2, MPFR_RNDD); // b = 2 + mpfr_log(b, b, MPFR_RNDD); // b = log(b) + mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); // b = b^(n+1) + + mpfr_div(a, a, b, MPFR_RNDD); // a = a / b + mpfr_div_ui(a, a, 2, MPFR_RNDD); // a = a / 2 + + mpfr_frac(b, a, MPFR_RNDD); // b = a - [a] + mpfr_printf("%2d: %23.4Rf %c\n", n, a, + mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); +} + +int main(void) +{ + int n; + for (n = 1; n <= 17; n++) h(n); + + return 0; +} diff --git a/Task/Hickerson-series-of-almost-integers/COBOL/hickerson-series-of-almost-integers.cobol b/Task/Hickerson-series-of-almost-integers/COBOL/hickerson-series-of-almost-integers.cobol new file mode 100644 index 0000000000..9992daa905 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/COBOL/hickerson-series-of-almost-integers.cobol @@ -0,0 +1,29 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. hickerson-series. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION ALL INTRINSIC + . +DATA DIVISION. +WORKING-STORAGE SECTION. +01 n PIC 99 COMP. + +01 h PIC Z(19)9.9(10). + +01 First-Decimal-Digit-Pos CONSTANT 22. + +PROCEDURE DIVISION. + PERFORM VARYING n FROM 0 BY 1 UNTIL n > 17 + COMPUTE h = FACTORIAL(n) / (2 * LOG(2) ** (n + 1)) + DISPLAY "h(" n ") = " h " which is " NO ADVANCING + IF h (First-Decimal-Digit-Pos:1) = "0" OR "9" + DISPLAY "an almost integer." + ELSE + DISPLAY "not an almost integer." + END-IF + END-PERFORM + . +END PROGRAM hickerson-series. diff --git a/Task/Hickerson-series-of-almost-integers/Clojure/hickerson-series-of-almost-integers.clj b/Task/Hickerson-series-of-almost-integers/Clojure/hickerson-series-of-almost-integers.clj new file mode 100644 index 0000000000..5ae5b76ab8 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Clojure/hickerson-series-of-almost-integers.clj @@ -0,0 +1,20 @@ +(defn hickerson + "Hickerson number, calculated with BigDecimals and manually-entered high-precision value for ln(2)." + [n] + (let [n! (apply *' (range 1M (inc n)))] + (.divide n! (*' 2 (.pow 0.693147180559945309417232121458M (inc n))) + 30 BigDecimal/ROUND_HALF_UP))) + +(defn almost-integer? + "Tests whether the first digit after the decimal is 0 or 9." + [x] + (let [first-digit (int (mod (.divide (*' x 10) 1.0M 0 BigDecimal/ROUND_DOWN) + 10))] + (or (= 0 first-digit) (= 9 first-digit)))) + +; Execute for side effects +(doseq [n (range 1 18) :let [h (hickerson n)]] + (println (format "%2d %24.5f" n h) + (if (almost-integer? h) + "almost integer" + "NOT almost integer"))) diff --git a/Task/Hickerson-series-of-almost-integers/D/hickerson-series-of-almost-integers.d b/Task/Hickerson-series-of-almost-integers/D/hickerson-series-of-almost-integers.d new file mode 100644 index 0000000000..2cb3b3af0e --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/D/hickerson-series-of-almost-integers.d @@ -0,0 +1,10 @@ +void main() { + import std.stdio, std.algorithm, std.mathspecial; + + foreach (immutable n; 1 .. 18) { + immutable x = gamma(n + 1) / (2 * LN2 ^^ (n + 1)), + tenths = cast(int)floor((x - x.floor) * 10); + writefln("H(%2d)=%22.2f is %snearly integer.", n, x, + tenths.among!(0, 9) ? "" : "NOT "); + } +} diff --git a/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f b/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f new file mode 100644 index 0000000000..a19d0672cb --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f @@ -0,0 +1,23 @@ +Program Hickerson +! 3 February 2014 +! not all Fortran compilers provide REAL*16 and INTEGER*8 +implicit none +real(kind=kind(1q0)) :: s +integer(kind=kind(1_8)) :: i,n,f,is + +do n = 1, 17 + s = 0.5q0 / log(2q0) + do i = 1,n + s = (s * i) / log(2q0) + end do + + is = s + f = (s-is)*10 !first digit after decimal point + if (f == 0 .or. f == 9) then + write(*,10)n,s,'' + else + write(*,10)n,s,' NOT' + endif +end do +10 format('h(',i2,') = ',F23.3,' is',A,' an almost-integer') +end program Hickerson diff --git a/Task/Hickerson-series-of-almost-integers/Go/hickerson-series-of-almost-integers.go b/Task/Hickerson-series-of-almost-integers/Go/hickerson-series-of-almost-integers.go new file mode 100644 index 0000000000..d9fc34d7a2 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Go/hickerson-series-of-almost-integers.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") + h := big.NewRat(1, 2) + h.Quo(h, ln2) + var f big.Rat + var w big.Int + for i := int64(1); i <= 17; i++ { + h.Quo(h.Mul(h, f.SetInt64(i)), ln2) + w.Quo(h.Num(), h.Denom()) + f.Sub(h, f.SetInt(&w)) + y, _ := f.Float64() + d := fmt.Sprintf("%.3f", y) + fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", + i, &w, d[1:], d[2] == '0' || d[2] == '9') + } +} diff --git a/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-1.j b/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-1.j new file mode 100644 index 0000000000..b2efee263b --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-1.j @@ -0,0 +1,2 @@ +ln2=: [: +/ 1 % [: (*2x&^) 1+i. +h=: ! % 2*(ln2 99)^>: diff --git a/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-2.j b/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-2.j new file mode 100644 index 0000000000..d3720e3fb0 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/J/hickerson-series-of-almost-integers-2.j @@ -0,0 +1,18 @@ + 1 23j3": (h ,.~ 0 9 e.~ 10 <.@* 1 | h) x:1+i.17 +1 1.041 +1 3.003 +1 12.996 +1 74.999 +1 541.002 +1 4683.001 +1 47292.999 +1 545834.998 +1 7087261.002 +1 102247563.005 +1 1622632572.998 +1 28091567594.982 +1 526858348381.001 +1 10641342970443.085 +1 230283190977853.037 +0 5315654681981354.513 +0 130370767029135900.458 diff --git a/Task/Hickerson-series-of-almost-integers/Mathematica/hickerson-series-of-almost-integers.math b/Task/Hickerson-series-of-almost-integers/Mathematica/hickerson-series-of-almost-integers.math new file mode 100644 index 0000000000..85d8bad862 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Mathematica/hickerson-series-of-almost-integers.math @@ -0,0 +1,4 @@ +h[n_] = n!/(2 (Log[2])^(n + 1)); +firstdecimal[x_] := Floor[10 x] - 10 Floor[x]; +almostIntegerQ[x_] := firstdecimal[x] == 0 || firstdecimal[x] == 9; +Table[{i, AccountingForm[N[h[i], 50], {Infinity, 5}], almostIntegerQ[N[h[i], 50]]}, {i, 1, 17}] // TableForm diff --git a/Task/Hickerson-series-of-almost-integers/PARI-GP/hickerson-series-of-almost-integers.pari b/Task/Hickerson-series-of-almost-integers/PARI-GP/hickerson-series-of-almost-integers.pari new file mode 100644 index 0000000000..5ff94891da --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/PARI-GP/hickerson-series-of-almost-integers.pari @@ -0,0 +1,3 @@ +h(n)=n!/2/log(2)^(n+1) +almost(x)=abs(x-round(x))<.1 +select(n->almost(h(n)),[1..17]) diff --git a/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-1.pli b/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-1.pli new file mode 100644 index 0000000000..d835177cf9 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-1.pli @@ -0,0 +1,22 @@ +Hickerson: procedure options (main); /* 12 January 2014 */ + declare s float (18), (i, n) fixed binary; + declare is fixed decimal (30); + declare f fixed decimal (4,3); + + do n = 1 to 16; /* 17 exceeds hardware precision */ + s = 0.5Q0 / 0.693147180559945309417232121458; + do i = 1 to n; + s = (s * i) / 0.693147180559945309417232121458; + end; + + is = s; + f = s-is; + is = 10*f; + put skip edit (n, s) (f(2), f(30,3)); + if is = 0 | is = 9 then + put edit (' is a near integer') (A); + else + put edit (' is not a near integer') (A); + end; + +end Hickerson; diff --git a/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-2.pli b/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-2.pli new file mode 100644 index 0000000000..d6c37dbbfb --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/PL-I/hickerson-series-of-almost-integers-2.pli @@ -0,0 +1,16 @@ +do n = 1 to 18; + s = divide( float(0.5), float(0.693147180559945309417232121458) ); + do i = 1 to n; + s = divide ( multiply(s, float(i)), float(0.693147180559945309417232121458) ); + end; + is = trunc(s); + f = subtract(s, is); + is = multiply(float(10), f); + is = trunc(is); + put skip edit (n) (f(3)); call output_fixed (s, 'F(60,4)' ); + + if compare(is, float(0)) = 0 | compare(is, float(9)) = 0 then + put edit (' is a near integer') (A); + else + put edit (' is not a near integer') (A); + end; diff --git a/Task/Hickerson-series-of-almost-integers/Perl-6/hickerson-series-of-almost-integers.pl6 b/Task/Hickerson-series-of-almost-integers/Perl-6/hickerson-series-of-almost-integers.pl6 new file mode 100644 index 0000000000..b75fdcdbea --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Perl-6/hickerson-series-of-almost-integers.pl6 @@ -0,0 +1,9 @@ +constant ln2 = [+] (1/2.FatRat, */2 ... *) Z/ 1 .. 100; +constant h = [\*] 1/2, 1..* X/ ln2; + +use Test; +plan *; + +for h[1..17] { + ok m/'.'<[09]>/, .round(0.001) +} diff --git a/Task/Hickerson-series-of-almost-integers/Perl/hickerson-series-of-almost-integers.pl b/Task/Hickerson-series-of-almost-integers/Perl/hickerson-series-of-almost-integers.pl new file mode 100644 index 0000000000..1acfde25dc --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Perl/hickerson-series-of-almost-integers.pl @@ -0,0 +1,14 @@ +use strict; +use warnings; +use Math::BigFloat; + +my $iln2 = 1 / Math::BigFloat->new(2)->blog; +my $h = $iln2 / 2; + +for my $n ( 1 .. 17 ) { + $h *= $iln2; + $h *= $n; + my $s = $h->copy->bfround(-3)->bstr; + printf "h(%2d) = %22s is%s almost an integer.\n", + $n, $s, ($s =~ /\.[09]/ ? "" : " NOT"); +} diff --git a/Task/Hickerson-series-of-almost-integers/Python/hickerson-series-of-almost-integers.py b/Task/Hickerson-series-of-almost-integers/Python/hickerson-series-of-almost-integers.py new file mode 100644 index 0000000000..37b26059bb --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Python/hickerson-series-of-almost-integers.py @@ -0,0 +1,18 @@ +from decimal import Decimal +import math + +def h(n): + 'Simple, reduced precision calculation' + return math.factorial(n) / (2 * math.log(2) ** (n + 1)) + +def h2(n): + 'Extended precision Hickerson function' + return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) + +for n in range(18): + x = h2(n) + norm = str(x.normalize()) + almostinteger = (' Nearly integer' + if 'E' not in norm and ('.0' in norm or '.9' in norm) + else ' NOT nearly integer!') + print('n:%2i h:%s%s' % (n, norm, almostinteger)) diff --git a/Task/Hickerson-series-of-almost-integers/README b/Task/Hickerson-series-of-almost-integers/README new file mode 100644 index 0000000000..c7b752a0c9 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Hickerson_series_of_almost_integers diff --git a/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers.rexx b/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers.rexx new file mode 100644 index 0000000000..d7c63bcb2b --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers.rexx @@ -0,0 +1,89 @@ +/* REXX --------------------------------------------------------------- +* 04.01.2014 Walter Pachl - using a rather aged ln function of mine +* with probably unreasonably high precision +* 05.01.2014 added n=18 +*--------------------------------------------------------------------*/ +Numeric Digits 100 +Do n=1 To 18 + x=format(def(),20,10) + Parse Var x '.' +1 d +1 + If pos(d,'09')>0 Then + tag='almost an integer' + Else + tag='' + Say right(n,2) x tag + End +Exit + +def: + x=fact(n)/(2*ln(2,200)**(n + 1)) + Return x + +ln: Procedure +/*********************************************************************** +* Return ln(x) -- with specified precision +* Three different series are used for the ranges 0 to 0.5 +* 0.5 to 1.5 +* 1.5 to infinity +* 920903 Walter Pachl +***********************************************************************/ + Parse Arg x,prec,b + If prec='' Then prec=9 + Numeric Digits (2*prec) + Numeric Fuzz 3 + Select + When x<=0 Then r='*** invalid argument ***' + When x<0.5 Then Do + z=(x-1)/(x+1) + o=z + r=z + k=1 + Do i=3 By 2 + ra=r + k=k+1 + o=o*z*z + r=r+o/i + If r=ra Then Leave + End + r=2*r + End + When x<1.5 Then Do + z=(x-1) + o=z + r=z + k=1 + Do i=2 By 1 + ra=r + k=k+1 + o=-o*z + r=r+o/i + If r=ra Then Leave + End + End + Otherwise /* 1.5<=x */ Do + z=(x+1)/(x-1) + o=1/z + r=o + k=1 + Do i=3 By 2 + ra=r + k=k+1 + o=o/(z*z) + r=r+o/i + If r=ra Then Leave + End + r=2*r + End + End + If b<>'' Then + r=r/ln(b) + Numeric Digits (prec) + Return r+0 + +fact: Procedure + Parse Arg m + fact=1 + Do i=2 To m + fact=fact*i + End + Return fact diff --git a/Task/Hickerson-series-of-almost-integers/Racket/hickerson-series-of-almost-integers.rkt b/Task/Hickerson-series-of-almost-integers/Racket/hickerson-series-of-almost-integers.rkt new file mode 100644 index 0000000000..3dc5373732 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Racket/hickerson-series-of-almost-integers.rkt @@ -0,0 +1,19 @@ +#lang racket +(require math/bigfloat) + +(define (hickerson n) + (bf/ (bffactorial n) + 2.bf + (bfexpt (bflog 2.bf) (bf (+ n 1))))) + +(for ([n (in-range 18)]) + (define hickerson-n (hickerson n)) + (define first-decimal + (bigfloat->integer (bftruncate (bf* 10.bf (bffrac hickerson-n))))) + (define almost-integer (if (or (= first-decimal 0) (= first-decimal 9)) + "is Nearly integer" + "is not Nearly integer!")) + (printf "~a: ~a ~a\n" + (~r n #:min-width 2) + (bigfloat->string hickerson-n) + almost-integer)) diff --git a/Task/Hickerson-series-of-almost-integers/Ruby/hickerson-series-of-almost-integers.rb b/Task/Hickerson-series-of-almost-integers/Ruby/hickerson-series-of-almost-integers.rb new file mode 100644 index 0000000000..bd11f65630 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Ruby/hickerson-series-of-almost-integers.rb @@ -0,0 +1,20 @@ +require "bigdecimal" + +LN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats +FACTORIALS = Hash.new{|h,k,v| h[k]=k * h[k-1]} +FACTORIALS[0] = 1 + +def hickerson(n) + FACTORIALS[n] / (2 * LN2 ** (n+1)) +end + +def nearly_int?(n) + int = n.round + n.between?(int - 0.1, int + 0.1) +end + +1.upto(17) do |n| + h = hickerson(n) + str = nearly_int?(h) ? "nearly integer" : "NOT nearly integer" + puts "n:%3i h: %s\t%s" % [n, h.to_s('F')[0,25], str] #increase the 25 to print more digits, there are 856 of them +end diff --git a/Task/Hickerson-series-of-almost-integers/Seed7/hickerson-series-of-almost-integers.seed7 b/Task/Hickerson-series-of-almost-integers/Seed7/hickerson-series-of-almost-integers.seed7 new file mode 100644 index 0000000000..db08886385 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Seed7/hickerson-series-of-almost-integers.seed7 @@ -0,0 +1,17 @@ +$ include "seed7_05.s7i"; + include "bigrat.s7i"; + +const proc: main is func + local + const bigRational: ln2 is 6931471805599453094172_ / 10000000000000000000000_; + var bigRational: h is 1_ / 2_ / ln2; + var integer: n is 0; + var string: stri is ""; + begin + for n range 1 to 17 do + h := h * bigRational conv n / ln2; + stri := h digits 3; + writeln(n lpad 2 <& stri lpad 23 <& " is almost integer: " <& + stri[succ(pos(stri, '.'))] in {'0', '9'}); + end for; + end func; diff --git a/Task/Hickerson-series-of-almost-integers/Tcl/hickerson-series-of-almost-integers.tcl b/Task/Hickerson-series-of-almost-integers/Tcl/hickerson-series-of-almost-integers.tcl new file mode 100644 index 0000000000..4191c3739a --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Tcl/hickerson-series-of-almost-integers.tcl @@ -0,0 +1,18 @@ +package require math::bigfloat +namespace import math::bigfloat::* + +# Precision is an arbitrary value large enough to provide clear demonstration +proc hickerson {n {precision 28}} { + set fac 1 + for {set i 1} {$i <= $n} {incr i} {set fac [expr {$fac * $i}]} + set numerator [int2float $fac $precision] + set 2 [int2float 2 $precision] + set denominator [mul $2 [pow [log $2] [expr {$n + 1}]]] + return [tostr -nosci [div $numerator $denominator]] +} + +for {set n 1} {$n <= 17} {incr n} { + set h [hickerson $n] + set almost [regexp {\.[09]} $h] + puts [format "h(%d) = %s (%salmost integer)" $n $h [expr {$almost ? "" : "not "}]] +} diff --git a/Task/IBAN/00DESCRIPTION b/Task/IBAN/00DESCRIPTION new file mode 100644 index 0000000000..8e52defff4 --- /dev/null +++ b/Task/IBAN/00DESCRIPTION @@ -0,0 +1,8 @@ +{{wikipedia}} +The [[wp:International_Bank_Account_Number|International Bank Account Number (IBAN)]] is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating [[wp:Transcription_error|transcription errors]].
+The IBAN consists of up to 34 alphanumeric characters: first the two-letter ISO 3166-1 alpha-2 country code, then two check digits, and finally a country-specific Basic Bank Account Number (BBAN).
+The check digits enable a sanity check of the bank account number to confirm its integrity even before submitting a transaction. + +The task here is to validate the following fictitious IBAN: GB82 WEST 1234 5698 7654 32. + +Details of the algorithm can be found on the Wikipedia page. diff --git a/Task/IBAN/00META.yaml b/Task/IBAN/00META.yaml new file mode 100644 index 0000000000..0b9ae97960 --- /dev/null +++ b/Task/IBAN/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Checksums diff --git a/Task/IBAN/Ada/iban-1.ada b/Task/IBAN/Ada/iban-1.ada new file mode 100644 index 0000000000..1f8c34b349 --- /dev/null +++ b/Task/IBAN/Ada/iban-1.ada @@ -0,0 +1,3 @@ +package Iban_Code is + function Is_Legal(Iban : String) return Boolean; +end Iban_Code; diff --git a/Task/IBAN/Ada/iban-2.ada b/Task/IBAN/Ada/iban-2.ada new file mode 100644 index 0000000000..f0b5327053 --- /dev/null +++ b/Task/IBAN/Ada/iban-2.ada @@ -0,0 +1,88 @@ +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Containers.Hashed_Maps; +with Ada.Strings.Hash; + +package body Iban_Code is + + subtype Nation is String (1..2); + + package String_Integer is new Ada.Containers.Hashed_Maps + (Nation, Integer, Ada.Strings.Hash, Equivalent_Keys => "="); + + Nations : String_Integer.Map; + + function Is_Legal(Iban : String) return Boolean + is + Temp : String(Iban'Range) := (others => ' '); + Count : Integer; + Ch : Character; + Num : Integer := 0; + begin + -- remove blank spaces and check characters + Count := Temp'First; + for I in Iban'Range loop + case Iban(I) is + when ' ' => null; + when 'a'..'z' => + Temp(Count) := To_Upper(Iban(I)); + Count := Count + 1; + when 'A'..'Z'|'0'..'9' => + Temp(Count) := Iban(I); + Count := Count + 1; + when others => return False; + end case; + end loop; + -- check nation code and length + if not Nations.Contains (Temp(1..2)) or else + Nations.Element (Temp(1..2))/= Count - 1 then + return False; + end if; + -- move the 4 initial characters to the end + Temp(Temp'First..Count-1) := Temp(5..Count-1) & Temp(Temp'First..4); + -- compute remainder modulo 97 + for I in Temp'First..Count-1 loop + Ch := Temp(I); + if Ch in '0'..'9' then + Num := Integer'Value(Integer'Image(Num) & Ch) mod 97; + else + Num := (Num * 100 + + (Character'Pos(Ch) - Character'Pos('A') + 10)) mod 97; + end if; + end loop; + return Num = 1; + end Is_Legal; + +begin + Nations.insert("AL", 28); Nations.insert("AD", 24); + Nations.insert("AT", 20); Nations.insert("AZ", 28); + Nations.insert("BE", 16); Nations.insert("BH", 22); + Nations.insert("BA", 20); Nations.insert("BR", 29); + Nations.insert("BG", 22); Nations.insert("CR", 21); + Nations.insert("HR", 21); Nations.insert("CY", 28); + Nations.insert("CZ", 24); Nations.insert("DK", 18); + Nations.insert("DO", 28); Nations.insert("EE", 20); + Nations.insert("FO", 18); Nations.insert("FI", 18); + Nations.insert("FR", 27); Nations.insert("GE", 22); + Nations.insert("DE", 22); Nations.insert("GI", 23); + Nations.insert("GR", 27); Nations.insert("GL", 18); + Nations.insert("GT", 28); Nations.insert("HU", 28); + Nations.insert("IS", 26); Nations.insert("IE", 22); + Nations.insert("IL", 23); Nations.insert("IT", 27); + Nations.insert("KZ", 20); Nations.insert("KW", 30); + Nations.insert("LV", 21); Nations.insert("LB", 28); + Nations.insert("LI", 21); Nations.insert("LT", 20); + Nations.insert("LU", 20); Nations.insert("MK", 19); + Nations.insert("MT", 31); Nations.insert("MR", 27); + Nations.insert("MU", 30); Nations.insert("MC", 27); + Nations.insert("MD", 24); Nations.insert("ME", 22); + Nations.insert("NL", 18); Nations.insert("NO", 15); + Nations.insert("PK", 24); Nations.insert("PS", 29); + Nations.insert("PL", 28); Nations.insert("PT", 25); + Nations.insert("RO", 24); Nations.insert("SM", 27); + Nations.insert("SA", 24); Nations.insert("RS", 22); + Nations.insert("SK", 24); Nations.insert("SI", 19); + Nations.insert("ES", 24); Nations.insert("SE", 24); + Nations.insert("CH", 21); Nations.insert("TN", 24); + Nations.insert("TR", 26); Nations.insert("AE", 23); + Nations.insert("GB", 22); Nations.insert("VG", 24); +end Iban_Code; diff --git a/Task/IBAN/Ada/iban-3.ada b/Task/IBAN/Ada/iban-3.ada new file mode 100644 index 0000000000..a525989153 --- /dev/null +++ b/Task/IBAN/Ada/iban-3.ada @@ -0,0 +1,21 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Iban_Code; + +procedure Check_Iban is + + procedure Check(Iban : String) is + begin + if Iban_Code.Is_Legal(Iban) then + Put_Line(Iban & " is valid."); + else + Put_Line(Iban & " is not valid."); + end if; + end Check; + +begin + Check("GB82 WEST 1234 5698 7654 32"); + Check("GB82WEST12345698765432"); + Check("gb82 west 1234 5698 7654 32"); + Check("GB82 TEST 1234 5698 7654 32"); + Check("GB82 WEST 1243 5698 7654 32"); +end Check_Iban; diff --git a/Task/IBAN/AutoHotkey/iban.ahk b/Task/IBAN/AutoHotkey/iban.ahk new file mode 100644 index 0000000000..66d3efea58 --- /dev/null +++ b/Task/IBAN/AutoHotkey/iban.ahk @@ -0,0 +1,43 @@ +IBANs := ["GB82 WEST 1234 5698 7654 32" + , "gb82 WEST 1234 5698 7654 32" + , "GB82WEST12345698765432" + , "GB82 WEST 234 5698 7654 32" + , "GB82 WEST 1234 5698 7654 33" + , "AE82 WEST 1234 5698 7654 32"] +for k, v in IBANs + Output .= v " is" (ValidIBAN(v) ? "" : " not") " valid.`n" +MsgBox, % Output + +ValidIBAN(n) { + static CC := {AL:28, AD:24, AT:20, AZ:28, BH:22, BE:16, BA:20, BR:29, BG:22, CR:21 + , HR:21, CY:28, CZ:24, DK:18, DO:28, EE:20, FO:18, FI:18, FR:27, GE:22 + , DE:22, GI:23, GR:27, GL:18, GT:28, HU:28, IS:26, IE:22, IL:23, IT:27 + , JO:30, KZ:20, KW:30, LV:21, LB:28, LI:21, LT:20, LU:20, MK:19, MT:31 + , MR:27, MU:30, MC:27, MD:24, ME:22, NL:18, NO:15, PK:24, PS:29, PL:28 + , PT:25, QA:29, RO:24, SM:27, SA:24, RS:22, SK:24, SI:19, ES:24, SE:24 + , CH:21, TN:24, TR:26, AE:23, GB:22, VG:24} + StringReplace, n, n, % A_Space,, A + ;Check that the total IBAN length is correct as per the country + if (StrLen(n) != CC[SubStr(n, 1, 2)]) + return false + StringUpper, n, n + ;Move the four initial characters to the end of the string + n := SubStr(n, 5) SubStr(n, 1, 4) + ;Replace each letter in the string with two digits + Loop, Parse, n + { + if A_LoopField is alpha + nn .= Asc(A_LoopField) - 55 + else + nn .= A_LoopField + } + return Mod97(nn) = 1 +} + +Mod97(a) { + while a { + rem := Mod(rem SubStr(a, 1, 15), 97) + a := SubStr(a, 16) + } + return rem +} diff --git a/Task/IBAN/BBC-BASIC/iban.bbc b/Task/IBAN/BBC-BASIC/iban.bbc new file mode 100644 index 0000000000..da319847d6 --- /dev/null +++ b/Task/IBAN/BBC-BASIC/iban.bbc @@ -0,0 +1,93 @@ + REM Used the following as official standard: + REM http://www.cnb.cz/cs/platebni_styk/iban/download/EBS204.pdf + + REM Pairs of ISO 3166 country code & expected IBAN length for this country + COULEN$="AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 CR21 HR21 CY28 CZ24 DK18 DO28 EE20 "+\ + \ "FO18 FI18 FR27 GE22 DE22 GI23 GR27 GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 "+\ + \ "LV21 LB28 LI21 LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 PS29 "+\ + \ "PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 TN24 TR26 AE23 GB22 VG24" + + PROCIBANcheck("GB82 WEST 1234 5698 7654 32"):REM Paper IBAN notation (with the spaces) + PROCIBANcheck("GB82WEST12345698765432") :REM Digital IBAN notation (without the spaces) + PROCIBANcheck("gb82 west 1234 5698 7654 32") + PROCIBANcheck("GB82 TEST 1234 5698 7654 32") + PROCIBANcheck("GR16 0110 1250 0000 0001 2300 695") + PROCIBANcheck("GB29 NWBK 6016 1331 9268 19") + PROCIBANcheck("SA03 8000 0000 6080 1016 7519") + PROCIBANcheck("CH93 0076 2011 6238 5295 7") + PROCIBANcheck("IL62 0108 0000 0009 9999 999") + PROCIBANcheck("IL62-0108-0000-0009-9999-999") + PROCIBANcheck("US12 3456 7890 0987 6543 210") + PROCIBANcheck("GR16 0110 1250 0000 0001 2300 695X") + END + + DEF PROCIBANcheck(iban$) + LOCAL err$,i%,match%,explen%,digiban$,tmpiban$,bignum$,c%,kk% + + REM Search for country code and fetch expected length + i%=1:explen%=0 + WHILE explen%=0 AND i%0 + + REM Continue if country code found + IF match% THEN + REM Remove space = convert to digital IBAN + digiban$="" + FOR i%=1TOLENiban$ + IF MID$(iban$,i%,1)>" " digiban$+=MID$(iban$,i%,1) + NEXT + REM Compare length with expected length + match%=explen%=LENdigiban$ + + REM Continue if length is correct + IF match% THEN + REM Create temporary string with country code appended + tmpiban$=MID$(digiban$,5)+MID$(digiban$,1,2) + REM Make big number, replacing letters by numbers using next conversion table: A=10 ... Z=35 + bignum$="" + FOR i%=1TOLENtmpiban$ + c%=ASCMID$(tmpiban$,i%,1) + IF c%>57 bignum$+=STR$(c%-55) ELSE bignum$+=STR$(c%-48) + NEXT + REM MOD 97 on bignum$+"00" and subtract result from 98 to obtain control number + kk%=98-FNmod97(bignum$+"00") + REM Compare with control number in IBAN + match%=VALMID$(iban$,3,2)=kk% + + REM Continue if control number matches + IF match% THEN + REM Append kk% to bignum$ and determine if MOD 97 results in 1 + match%=FNmod97(bignum$+RIGHT$("0"+STR$kk%,2))=1 + + REM Continue if MOD 97 + IF match% THEN + REM Was last test + ELSE + err$="result from modulo 97" + ENDIF + ELSE + err$="check digits, should be: "+STR$kk% + ENDIF + ELSE + err$="code length, expected length: "+STR$explen% + ENDIF + ELSE + err$="country code: "+LEFT$(iban$,2) + ENDIF + + IF match% PRINT " "; ELSE PRINT "in";:err$="***error!*** invalid "+err$ + PRINT "valid IBAN: ";iban$TAB(50)err$ + ENDPROC + + DEF FNmod97(num$) + LOCAL mod$ + mod$=LEFT$(num$,2) + num$=MID$(num$,3) + WHILE num$>"" + mod$=RIGHT$("0"+STR$(VAL(mod$+LEFT$(num$,7))MOD97),2) + num$=MID$(num$,8) + ENDWHILE + =VALmod$ diff --git a/Task/IBAN/Bracmat/iban.bracmat b/Task/IBAN/Bracmat/iban.bracmat new file mode 100644 index 0000000000..430a9d23f4 --- /dev/null +++ b/Task/IBAN/Bracmat/iban.bracmat @@ -0,0 +1,51 @@ +( ( IBAN-check + = table country cd len N c + . (AL.28) (AD.24) (AT.20) (AZ.28) (BE.16) (BH.22) (BA.20) (BR.29) + (BG.22) (CR.21) (HR.21) (CY.28) (CZ.24) (DK.18) (DO.28) (EE.20) + (FO.18) (FI.18) (FR.27) (GE.22) (DE.22) (GI.23) (GR.27) (GL.18) + (GT.28) (HU.28) (IS.26) (IE.22) (IL.23) (IT.27) (KZ.20) (KW.30) + (LV.21) (LB.28) (LI.21) (LT.20) (LU.20) (MK.19) (MT.31) (MR.27) + (MU.30) (MC.27) (MD.24) (ME.22) (NL.18) (NO.15) (PK.24) (PS.29) + (PL.28) (PT.25) (RO.24) (SM.27) (SA.24) (RS.22) (SK.24) (SI.19) + (ES.24) (SE.24) (CH.21) (TN.24) (TR.26) (AE.23) (GB.22) (VG.24) + : ?table + & @(!arg:?country [2 ?cd [4 ?arg) + & str$(!arg !country !cd):?arg + & ( !table:? (!country.?len) ? + & :?N + & ( @( !arg + : ? + ( %@?c ? + & ( !c:# + | !c:~Z + & asc$!c+-1*asc$A+10:?c + & 1+!len:?len + | !c:" "&:?c + | + ) + & !N !c:?N + & ~ + ) + ) + | str$!N:?N:# + & ( @(!N:? [!len) + & ( mod$(!N,97):1&out$OK + | out$"wrong check digits" + ) + | out$"wrong length" + ) + | @(!N:? ~#%?c ?) + & out$(str$("invalid character: '" !c "'")) + ) + | out$(str$("invalid country code: '" !country "'")) + ) + ) +& IBAN-check$"GB82 WEST 1234 5698 7654 32 9" +& IBAN-check$"GX82 WEST 1234 5698 7654 32" +& IBAN-check$"GB82 WEST 1234 5698 7654 32" +& IBAN-check$GB82WEST12345698765432 +& IBAN-check$"gb82 west 1234 5698 7654 32" +& IBAN-check$"GB82 TEST 1234 5698 7654 32" +& IBAN-check$"GB82 WEST 1243 5698 7654 32" +& IBAN-check$"GB82 west 1243 5698 7654 32" +); diff --git a/Task/IBAN/C++/iban.cpp b/Task/IBAN/C++/iban.cpp new file mode 100644 index 0000000000..890d3bef24 --- /dev/null +++ b/Task/IBAN/C++/iban.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +using namespace boost::algorithm ; + +bool isValid ( const std::string &ibanstring ) { + + static std::map countrycodes + { {"AL" , 28} , {"AD" , 24} , {"AT" , 20} , {"AZ" , 28 } , + {"BE" , 16} , {"BH" , 22} , {"BA" , 20} , {"BR" , 29 } , + {"BG" , 22} , {"CR" , 21} , {"HR" , 21} , {"CY" , 28 } , + {"CZ" , 24} , {"DK" , 18} , {"DO" , 28} , {"EE" , 20 } , + {"FO" , 18} , {"FI" , 18} , {"FR" , 27} , {"GE" , 22 } , + {"DE" , 22} , {"GI" , 23} , {"GR" , 27} , {"GL" , 18 } , + {"GT" , 28} , {"HU" , 28} , {"IS" , 26} , {"IE" , 22 } , + {"IL" , 23} , {"IT" , 27} , {"KZ" , 20} , {"KW" , 30 } , + {"LV" , 21} , {"LB" , 28} , {"LI" , 21} , {"LT" , 20 } , + {"LU" , 20} , {"MK" , 19} , {"MT" , 31} , {"MR" , 27 } , + {"MU" , 30} , {"MC" , 27} , {"MD" , 24} , {"ME" , 22 } , + {"NL" , 18} , {"NO" , 15} , {"PK" , 24} , {"PS" , 29 } , + {"PL" , 28} , {"PT" , 25} , {"RO" , 24} , {"SM" , 27 } , + {"SA" , 24} , {"RS" , 22} , {"SK" , 24} , {"SI" , 19 } , + {"ES" , 24} , {"SE" , 24} , {"CH" , 21} , {"TN" , 24 } , + {"TR" , 26} , {"AE" , 23} , {"GB" , 22} , {"VG" , 24 } } ; + std::string teststring( ibanstring ) ; + erase_all( teststring , " " ) ; //defined in boost/algorithm/string.hpp + if ( countrycodes.find( teststring.substr(0 , 2 )) == countrycodes.end( ) ) + return false ; + if ( teststring.length( ) != countrycodes[ teststring.substr( 0 , 2 ) ] ) + return false ; + if ( ! ( all ( teststring , is_alnum( ) ) ) ) + return false ; + to_upper( teststring ) ; + teststring = teststring.append( teststring.substr( 0 , 4 ) ) ; + teststring.assign( teststring.substr( 4 ) ) ; + std::string numberstring ;//will contain the letter substitutions + for ( int i = 0 ; i < teststring.length( ) ; i++ ) { + if ( std::isdigit( teststring[ i ] ) ) + numberstring = numberstring + teststring[ i ] ; + if ( std::isupper( teststring[ i ] ) ) + numberstring = numberstring + std::to_string( static_cast( teststring[ i ] ) - 55 ) ; + } + //implements a stepwise check for mod 97 in chunks of 9 at the first time + // , then in chunks of seven prepended by the last mod 97 operation converted + //to a string + int segstart = 0 ; + int step = 9 ; + std::string prepended ; + long number = 0 ; + while ( segstart < numberstring.length( ) - step ) { + number = std::stol( prepended + numberstring.substr( segstart , step ) ) ; + int remainder = number % 97 ; + prepended = std::to_string( remainder ) ; + if ( remainder < 10 ) + prepended = "0" + prepended ; + segstart = segstart + step ; + step = 7 ; + } + number = std::stol( prepended + numberstring.substr( segstart )) ; + return ( number % 97 == 1 ) ; +} + +int main( ) { + std::cout << "GB82 WEST 1234 5698 7654 32 is " << ( isValid( "GB82 WEST 1234 5698 7654 32" ) ? "" : "not " ) + << "valid!" << std::endl ; + std::cout << "GB82TEST12345698765432 is " << ( isValid( "GB82TEST12345698765432" ) ? "" : "not " ) + << "valid!" << std::endl ; + return 0 ; +} diff --git a/Task/IBAN/C-sharp/iban-1.cs b/Task/IBAN/C-sharp/iban-1.cs new file mode 100644 index 0000000000..5008d9f5d8 --- /dev/null +++ b/Task/IBAN/C-sharp/iban-1.cs @@ -0,0 +1,120 @@ + public class IbanValidator : IValidateTypes + { + public ValidationResult Validate(string value) + { + // Check if value is missing + if (string.IsNullOrEmpty(value)) + return ValidationResult.ValueMissing; + + if (value.Length < 2) + return ValidationResult.ValueTooSmall; + + var countryCode = value.Substring(0, 2).ToUpper(); + + int lengthForCountryCode; + + var countryCodeKnown = _lengths.TryGetValue(countryCode, out lengthForCountryCode); + if (!countryCodeKnown) + { + return ValidationResult.CountryCodeNotKnown; + } + + // Check length. + if (value.Length < lengthForCountryCode) + return ValidationResult.ValueTooSmall; + + if (value.Length > lengthForCountryCode) + return ValidationResult.ValueTooBig; + + value = value.ToUpper(); + var newIban = value.Substring(4) + value.Substring(0, 4); + + newIban = Regex.Replace(newIban, @"\D", match => ((int) match.Value[0] - 55).ToString()); + + var remainder = BigInteger.Parse(newIban) % 97; + + if (remainder != 1) + return ValidationResult.ValueFailsModule97Check; + + + return ValidationResult.IsValid; + } + + public enum ValidationResult + { + IsValid, + ValueMissing, + ValueTooSmall, + ValueTooBig, + ValueFailsModule97Check, + CountryCodeNotKnown + } + + private static Dictionary _lengths = new Dictionary + { + {"AL", 28}, + {"AD", 24}, + {"AT", 20}, + {"AZ", 28}, + {"BE", 16}, + {"BH", 22}, + {"BA", 20}, + {"BR", 29}, + {"BG", 22}, + {"CR", 21}, + {"HR", 21}, + {"CY", 28}, + {"CZ", 24}, + {"DK", 18}, + {"DO", 28}, + {"EE", 20}, + {"FO", 18}, + {"FI", 18}, + {"FR", 27}, + {"GE", 22}, + {"DE", 22}, + {"GI", 23}, + {"GR", 27}, + {"GL", 18}, + {"GT", 28}, + {"HU", 28}, + {"IS", 26}, + {"IE", 22}, + {"IL", 23}, + {"IT", 27}, + {"KZ", 20}, + {"KW", 30}, + {"LV", 21}, + {"LB", 28}, + {"LI", 21}, + {"LT", 20}, + {"LU", 20}, + {"MK", 19}, + {"MT", 31}, + {"MR", 27}, + {"MU", 30}, + {"MC", 27}, + {"MD", 24}, + {"ME", 22}, + {"NL", 18}, + {"NO", 15}, + {"PK", 24}, + {"PS", 29}, + {"PL", 28}, + {"PT", 25}, + {"RO", 24}, + {"SM", 27}, + {"SA", 24}, + {"RS", 22}, + {"SK", 24}, + {"SI", 19}, + {"ES", 24}, + {"SE", 24}, + {"CH", 21}, + {"TN", 24}, + {"TR", 26}, + {"AE", 23}, + {"GB", 22}, + {"VG", 24} + }; + } diff --git a/Task/IBAN/C-sharp/iban-2.cs b/Task/IBAN/C-sharp/iban-2.cs new file mode 100644 index 0000000000..b439c42c89 --- /dev/null +++ b/Task/IBAN/C-sharp/iban-2.cs @@ -0,0 +1,100 @@ + public class When_the_IbanValidator_is_told_to_Validate + { + [Fact] + public void It_should_return_an_error_when_there_is_no_value_provided() + { + // Assert + const string value = ""; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.ValueMissing, result); + } + + [Fact] + public void It_should_return_an_error_when_the_value_length_is_to_short() + { + // Assert + const string value = "BE1800165492356"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.ValueTooSmall, result); + } + + [Fact] + public void It_should_return_an_error_when_the_value_length_is_to_big() + { + // Assert + const string value = "BE180016549235656"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.ValueTooBig, result); + } + + [Fact] + public void It_should_return_an_error_when_the_value_fails_the_module_check() + { + // Assert + const string value = "BE18001654923566"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.ValueFailsModule97Check, result); + } + + [Fact] + public void It_should_return_an_error_when_an_unkown_country_prefix_used() + { + // Assert + const string value = "XX82WEST12345698765432"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.CountryCodeNotKnown, result); + } + + [Fact] + public void It_should_return_valid_when_a_valid_value_is_provided() + { + // Assert + const string value = "BE18001654923565"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.IsValid, result); + } + + [Fact] + public void It_should_return_valid_when_a_valid_foreign_value_is_provided() + { + // Assert + const string value = "GB82WEST12345698765432"; + var validator = new IbanValidator(); + + // Act + var result = validator.Validate(value); + + // Assert + Assert.Equal(ValidationResult.IsValid, result); + } + } diff --git a/Task/IBAN/C/iban.c b/Task/IBAN/C/iban.c new file mode 100644 index 0000000000..9f2dc19ecf --- /dev/null +++ b/Task/IBAN/C/iban.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include + +#define V(cc, exp) if (!strncmp(iban, cc, 2)) return len == exp + +/* Validate country code against expected length. */ +int valid_cc(const char *iban, int len) +{ + V("AL", 28); V("AD", 24); V("AT", 20); V("AZ", 28); V("BE", 16); V("BH", 22); V("BA", 20); V("BR", 29); + V("BG", 22); V("CR", 21); V("HR", 21); V("CY", 28); V("CZ", 24); V("DK", 18); V("DO", 28); V("EE", 20); + V("FO", 18); V("FI", 18); V("FR", 27); V("GE", 22); V("DE", 22); V("GI", 23); V("GR", 27); V("GL", 18); + V("GT", 28); V("HU", 28); V("IS", 26); V("IE", 22); V("IL", 23); V("IT", 27); V("KZ", 20); V("KW", 30); + V("LV", 21); V("LB", 28); V("LI", 21); V("LT", 20); V("LU", 20); V("MK", 19); V("MT", 31); V("MR", 27); + V("MU", 30); V("MC", 27); V("MD", 24); V("ME", 22); V("NL", 18); V("NO", 15); V("PK", 24); V("PS", 29); + V("PL", 28); V("PT", 25); V("RO", 24); V("SM", 27); V("SA", 24); V("RS", 22); V("SK", 24); V("SI", 19); + V("ES", 24); V("SE", 24); V("CH", 21); V("TN", 24); V("TR", 26); V("AE", 23); V("GB", 22); V("VG", 24); + + return 0; +} + +/* Remove blanks from s in-place, return its new length. */ +int strip(char *s) +{ + int i = -1, m = 0; + + while(s[++i]) { + s[i - m] = s[i]; + m += s[i] <= 32; + } + + s[i - m] = 0; + return i - m; +} + +/* Calculate the mod 97 of an arbitrarily large number (as a string). */ +int mod97(const char *s, int len) +{ + int i, j, parts = len / 7; + char rem[10] = "00"; + + for (i = 1; i <= parts + (len % 7 != 0); ++i) { + strncpy(rem + 2, s + (i - 1) * 7, 7); + j = atoi(rem) % 97; + rem[0] = j / 10 + '0'; + rem[1] = j % 10 + '0'; + } + + return atoi(rem) % 97; +} + +int valid_iban(char *iban) +{ + int i, j, l = 0, sz = strip(iban); + char *rot, *trans; + + /* Ensure upper alphanumeric input and count letters. */ + for (i = 0; i < sz; ++i) { + if (!isdigit(iban[i]) && !isupper(iban[i])) + return 0; + l += !!isupper(iban[i]); + } + + if (!valid_cc(iban, sz)) + return 0; + + /* Move the first four characters to the end. */ + rot = alloca(sz); + strcpy(rot, iban + 4); + strncpy(rot + sz - 4, iban, 4); + + /* Allocate space for the transformed IBAN. */ + trans = alloca(sz + l); + trans[sz + l] = 0; + + /* Convert A to 10, B to 11, etc. */ + for (i = j = 0; i < sz; ++i, ++j) { + if (isdigit(rot[i])) + trans[j] = rot[i]; + else { + trans[j] = (rot[i] - 55) / 10 + '0'; + trans[++j] = (rot[i] - 55) % 10 + '0'; + } + } + + return mod97(trans, sz + l) == 1; +} + +int main(int _, char **argv) +{ + while (--_, *++argv) + printf("%s is %svalid.\n", *argv, valid_iban(*argv) ? "" : "in"); + + return 0; +} diff --git a/Task/IBAN/COBOL/iban.cobol b/Task/IBAN/COBOL/iban.cobol new file mode 100644 index 0000000000..164c15bbdc --- /dev/null +++ b/Task/IBAN/COBOL/iban.cobol @@ -0,0 +1,161 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. iban-main. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 iban PIC X(50). + 01 iban-flag PIC X. + 88 is-valid VALUE "Y", FALSE "N". + + PROCEDURE DIVISION. + main-line. + MOVE "GB82 WEST 1234 5698 7654 32" TO iban + PERFORM display-validity + + MOVE "GB82 TEST 1234 5698 7654 32" TO iban + PERFORM display-validity + + GOBACK + . + display-validity. + CALL "validate-iban" USING CONTENT iban, REFERENCE iban-flag + IF is-valid + DISPLAY FUNCTION TRIM(iban) " is valid." + ELSE + DISPLAY FUNCTION TRIM(iban) " is not valid." + END-IF + . + END PROGRAM iban-main. + + + IDENTIFICATION DIVISION. + PROGRAM-ID. validate-iban. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 country-lengths-area VALUE "AD24AE23AL28AT20AZ28BA20BE16" + & "BG22BH22BR29CH21CR21CY28CZ24DE22DK18DO28EE20ES24FI18FO18F" + & "R27GB22GE22GI23GL18GR27GT28HR21HU28IE22IL23IS26IT27KW30KZ" + & "20LB28LI21LT20LU20LV21MC27MD24ME22MK19MR27MT31MU30NL18NO1" + & "5PK24PL28PS29PT25RO24RS22SA24SE24SI19SK24SM27TN24TR26VG24" + . + 03 country-lengths OCCURS 64 TIMES + INDEXED BY country-lengths-idx. + 05 country-code PIC XX. + 05 country-len PIC 99. + + 01 offset PIC 99. + + 01 i PIC 99. + + 01 len PIC 99. + + LINKAGE SECTION. + 01 iban PIC X(50). + + 01 valid-flag PIC X. + 88 is-valid VALUE "Y", FALSE "N". + + PROCEDURE DIVISION USING iban, valid-flag. + MOVE FUNCTION UPPER-CASE(iban) TO iban + CALL "remove-spaces" USING iban + + *> Check if country-code and length are correct + INITIALIZE len + INSPECT iban TALLYING len FOR CHARACTERS BEFORE SPACE + SET country-lengths-idx TO 1 + SEARCH country-lengths + AT END + SET is-valid TO FALSE + GOBACK + + WHEN country-code (country-lengths-idx) = iban (1:2) + IF country-len (country-lengths-idx) NOT = len + SET is-valid TO FALSE + GOBACK + END-IF + END-SEARCH + + CALL "create-iban-number" USING CONTENT len, REFERENCE iban + + *> Mod 97 number formed. + IF FUNCTION MOD(iban, 97) = 1 + SET is-valid TO TRUE + ELSE + SET is-valid TO FALSE + END-IF + . + + IDENTIFICATION DIVISION. + PROGRAM-ID. remove-spaces. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 i PIC 99. + 01 offset PIC 99. + + LINKAGE SECTION. + 01 str PIC X(50). + + PROCEDURE DIVISION USING str. + INITIALIZE offset + PERFORM VARYING i FROM 1 BY 1 UNTIL i > 50 + EVALUATE TRUE + WHEN str (i:1) = SPACE + ADD 1 TO offset + + WHEN offset NOT = ZERO + MOVE str (i:1) TO str (i - offset:1) + END-EVALUATE + END-PERFORM + MOVE SPACES TO str (50 - offset + 1:) + . + END PROGRAM remove-spaces. + + + IDENTIFICATION DIVISION. + PROGRAM-ID. create-iban-number. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 first-four PIC X(4). + + 01 iban-num PIC X(50). + 01 digit-num PIC 99 VALUE 1. + + 01 i PIC 99. + + 01 letter-num PIC 99. + + LINKAGE SECTION. + 01 len PIC 99. + + 01 iban PIC X(50). + + PROCEDURE DIVISION USING len, iban. + *> Move characters into final positions. + MOVE iban (1:4) TO first-four + MOVE iban (5:) TO iban + MOVE first-four TO iban (len - 3:) + + *> Convert letters to numbers. + INITIALIZE iban-num, digit-num ALL TO VALUE + PERFORM VARYING i FROM 1 BY 1 + UNTIL i > len OR iban (i:1) = SPACE + IF iban (i:1) IS NUMERIC + MOVE iban (i:1) TO iban-num (digit-num:1) + ADD 1 TO digit-num + ELSE + COMPUTE letter-num = + FUNCTION ORD(iban (i:1)) - FUNCTION ORD("A") + 10 + MOVE letter-num TO iban-num (digit-num:2) + ADD 2 TO digit-num + END-IF + END-PERFORM + + MOVE iban-num TO iban + . + + END PROGRAM create-iban-number. + + END PROGRAM validate-iban. diff --git a/Task/IBAN/Cache-ObjectScript/iban.cos b/Task/IBAN/Cache-ObjectScript/iban.cos new file mode 100644 index 0000000000..7f07c372eb --- /dev/null +++ b/Task/IBAN/Cache-ObjectScript/iban.cos @@ -0,0 +1,98 @@ +Class Utils.Validate [ Abstract ] +{ + +ClassMethod VerifyIBAN(pIBAN As %String = "") As %Boolean +{ + // remove spaces and define parts + Set iban=$Translate(pIBAN, " ") + Set cc=$Extract(iban, 1, 2) + Set cd=$Extract(iban, 3, 4) + Set bban=$Extract(iban, 5, *) + + // ensure IBAN is correct format + If $Match(iban, ..GetIBANPattern(cc))=0 Quit 0 + + // compare result and return + Quit cd=..GetIBANCheckDigit(cc, bban) +} + +ClassMethod GetIBANCheckDigit(pCC As %String, pBBAN As %String) As %Integer [ Internal, Private ] +{ + Set str=pBBAN_pCC_"00" + For i=1:1 { + Set chr=$Extract(str, i) If chr="" Quit + If chr?1U Set $Extract(str, i)=$ASCII(chr)-55 + } + Set cd=98-..GetModulus(str, 97) + Quit $Select($Length(cd)=2: cd, 1: "0"_cd) +} + +ClassMethod GetModulus(pNum As %Integer, pDiv As %Integer) As %Integer [ Internal, Private ] +{ + While $Length(pNum)>9 { + Set $Extract(pNum, 1, 9)=$Extract(pNum, 1, 9)#pDiv + } + Quit pNum#pDiv +} + +ClassMethod GetIBANPattern(pCC As %String = "") As %String [ Internal, Private ] +{ + Quit $Case(pCC, + "AL": "^AL\d{10}[0-9A-Z]{16}$", + "AD": "^AD\d{10}[0-9A-Z]{12}$", + "AT": "^AT\d{18}$", + "BH": "^BH\d{2}[A-Z]{4}[0-9A-Z]{14}$", + "BE": "^BE\d{14}$", + "BA": "^BA\d{18}$", + "BG": "^BG\d{2}[A-Z]{4}\d{6}[0-9A-Z]{8}$", + "HR": "^HR\d{19}$", + "CY": "^CY\d{10}[0-9A-Z]{16}$", + "CZ": "^CZ\d{22}$", + "DK": "^DK\d{16}$|^FO\d{16}$|^GL\d{16}$", + "DO": "^DO\d{2}[0-9A-Z]{4}\d{20}$", + "EE": "^EE\d{18}$", + "FI": "^FI\d{16}$", + "FR": "^FR\d{12}[0-9A-Z]{11}\d{2}$", + "GE": "^GE\d{2}[A-Z]{2}\d{16}$", + "DE": "^DE\d{20}$", + "GI": "^GI\d{2}[A-Z]{4}[0-9A-Z]{15}$", + "GR": "^GR\d{9}[0-9A-Z]{16}$", + "HU": "^HU\d{26}$", + "IS": "^IS\d{24}$", + "IE": "^IE\d{2}[A-Z]{4}\d{14}$", + "IL": "^IL\d{21}$", + "IT": "^IT\d{2}[A-Z]\d{10}[0-9A-Z]{12}$", + "KZ": "^[A-Z]{2}\d{5}[0-9A-Z]{13}$", + "KW": "^KW\d{2}[A-Z]{4}22!$", + "LV": "^LV\d{2}[A-Z]{4}[0-9A-Z]{13}$", + "LB": "^LB\d{6}[0-9A-Z]{20}$", + "LI": "^LI\d{7}[0-9A-Z]{12}$", + "LT": "^LT\d{18}$", + "LU": "^LU\d{5}[0-9A-Z]{13}$", + "MK": "^MK\d{5}[0-9A-Z]{10}\d{2}$", + "MT": "^MT\d{2}[A-Z]{4}\d{5}[0-9A-Z]{18}$", + "MR": "^MR13\d{23}$", + "MU": "^MU\d{2}[A-Z]{4}\d{19}[A-Z]{3}$", + "MC": "^MC\d{12}[0-9A-Z]{11}\d{2}$", + "ME": "^ME\d{20}$", + "NL": "^NL\d{2}[A-Z]{4}\d{10}$", + "NO": "^NO\d{13}$", + "PL": "^PL\d{10}[0-9A-Z]{,16}n$", + "PT": "^PT\d{23}$", + "RO": "^RO\d{2}[A-Z]{4}[0-9A-Z]{16}$", + "SM": "^SM\d{2}[A-Z]\d{10}[0-9A-Z]{12}$", + "SA": "^SA\d{4}[0-9A-Z]{18}$", + "RS": "^RS\d{20}$", + "SK": "^SK\d{22}$", + "SI": "^SI\d{17}$", + "ES": "^ES\d{22}$", + "SE": "^SE\d{22}$", + "CH": "^CH\d{7}[0-9A-Z]{12}$", + "TN": "^TN59\d{20}$", + "TR": "^TR\d{7}[0-9A-Z]{17}$", + "AE": "^AE\d{21}$", + "GB": "^GB\d{2}[A-Z]{4}\d{14}$", + : " ") +} + +} diff --git a/Task/IBAN/Clojure/iban.clj b/Task/IBAN/Clojure/iban.clj new file mode 100644 index 0000000000..53884b84f3 --- /dev/null +++ b/Task/IBAN/Clojure/iban.clj @@ -0,0 +1,24 @@ +(def explen + {"AL" 28 "AD" 24 "AT" 20 "AZ" 28 "BE" 16 "BH" 22 "BA" 20 "BR" 29 + "BG" 22 "CR" 21 "HR" 21 "CY" 28 "CZ" 24 "DK" 18 "DO" 28 "EE" 20 + "FO" 18 "FI" 18 "FR" 27 "GE" 22 "DE" 22 "GI" 23 "GR" 27 "GL" 18 + "GT" 28 "HU" 28 "IS" 26 "IE" 22 "IL" 23 "IT" 27 "KZ" 20 "KW" 30 + "LV" 21 "LB" 28 "LI" 21 "LT" 20 "LU" 20 "MK" 19 "MT" 31 "MR" 27 + "MU" 30 "MC" 27 "MD" 24 "ME" 22 "NL" 18 "NO" 15 "PK" 24 "PS" 29 + "PL" 28 "PT" 25 "RO" 24 "SM" 27 "SA" 24 "RS" 22 "SK" 24 "SI" 19 + "ES" 24 "SE" 24 "CH" 21 "TN" 24 "TR" 26 "AE" 23 "GB" 22 "VG" 24}) + +(defn valid-iban? [iban] + (let [iban (apply str (remove #{\space \tab} iban))] + (cond + ; Ensure upper alphanumeric input. + (not (re-find #"^[\dA-Z]+$" iban)) false + ; Validate country code against expected length. + (not= (explen (subs iban 0 2)) (count iban)) false + :else + (let [rot (flatten (apply conj (split-at 4 iban))) + trans (map #(read-string (str "36r" %)) rot)] + (= 1 (mod (bigint (apply str trans)) 97)))))) + +(prn (valid-iban? "GB82 WEST 1234 5698 7654 32") ; true + (valid-iban? "GB82 TEST 1234 5698 7654 32")) ; false diff --git a/Task/IBAN/Common-Lisp/iban.lisp b/Task/IBAN/Common-Lisp/iban.lisp new file mode 100644 index 0000000000..c4f950505c --- /dev/null +++ b/Task/IBAN/Common-Lisp/iban.lisp @@ -0,0 +1,60 @@ +;; +;; List of the IBAN code lengths per country. +;; +(defvar *IBAN-code-length* '((15 . ("NO")) + (16 . ("BE")) + (18 . ("DK" "FO" "FI" "GL" "NL")) + (19 . ("MK" "SI")) + (20 . ("AT" "BA" "EE" "KZ" "LT" "LU")) + (21 . ("CR" "HR" "LV" "LI" "CH")) + (22 . ("BH" "BG" "GE" "DE" "IE" "ME" "RS" "GB")) + (23 . ("GI" "IL" "AE")) + (24 . ("AD" "CZ" "MD" "PK" "RO" "SA" "SK" "ES" "SE" "TN" "VG")) + (25 . ("PT")) + (26 . ("IS" "TR")) + (27 . ("FR" "GR" "IT" "MR" "MC" "SM")) + (28 . ("AL" "AZ" "CY" "DO" "GT" "HU" "LB" "PL")) + (29 . ("BR" "PS")) + (30 . ("KW" "MU")) + (31 . ("MT")))) + +;; +;; The IBAN-character function verifies whether the number contains the correct characters only. There is +;; a built in function to verify for alphanumeric characters, but it includes characters beyond ASCII range. +;; +(defun IBAN-characters (iban) + (flet ((valid-alphanum (ch) (or (and (char<= #\A ch) (char>= #\Z ch)) (and (char<= #\0 ch) (char>= #\9 ch))))) + (loop :for char :across iban + :finally (return t) + :do + (when (not (valid-alphanum char)) + (return nil))))) + +;; +;; The function IBAN-length verifies that the length of the number is correct. The code lengths +;; are retrieved from the table *IBAN-code-lengths*. +;; +(defun IBAN-length (iban) + (loop :for (len . country) :in *IBAN-code-length* + :with iban-country = (subseq iban 0 2) + :do + (when (find iban-country country :test #'string=) (return (= len (length iban)))))) + +;; +;; The function IBAN-to-integer converts an IBAN code into an integer number. +;; Note: The conversion follows the rules stated in the wiki page. +;; +(defun IBAN-to-integer (iban) + (let ((character-base (- (char-code #\A) 10))) + (parse-integer + (format nil "~{~a~}" (map 'list #'(lambda(X) (if (alpha-char-p X) (- (char-code X) character-base) X )) + (concatenate 'string (subseq iban 4) (subseq iban 0 4))))))) +;; +;; The function IBAN-verify checks that the code contains right character set, has the +;; country specific length and has the correct check sum. +;; +(defun IBAN-verify (iban) + (flet ((validp (X) (and (IBAN-characters X) + (IBAN-length X) + (= 1 (mod (IBAN-to-integer X) 97))))) + (validp (remove #\Space iban)))) diff --git a/Task/IBAN/D/iban.d b/Task/IBAN/D/iban.d new file mode 100644 index 0000000000..48dd2eeae8 --- /dev/null +++ b/Task/IBAN/D/iban.d @@ -0,0 +1,37 @@ +import std.stdio, std.string, std.regex, std.conv, std.bigint, + std.algorithm, std.ascii; + +immutable int[string] country2len; +static this() { + country2len = ["AL":28, "AD":24, "AT":20, "AZ":28, "BE":16, + "BH":22, "BA":20, "BR":29, "BG":22, "CR":21, "HR":21, "CY":28, + "CZ":24, "DK":18, "DO":28, "EE":20, "FO":18, "FI":18, "FR":27, + "GE":22, "DE":22, "GI":23, "GR":27, "GL":18, "GT":28, "HU":28, + "IS":26, "IE":22, "IL":23, "IT":27, "KZ":20, "KW":30, "LV":21, + "LB":28, "LI":21, "LT":20, "LU":20, "MK":19, "MT":31, "MR":27, + "MU":30, "MC":27, "MD":24, "ME":22, "NL":18, "NO":15, "PK":24, + "PS":29, "PL":28, "PT":25, "RO":24, "SM":27, "SA":24, "RS":22, + "SK":24, "SI":19, "ES":24, "SE":24, "CH":21, "TN":24, "TR":26, + "AE":23, "GB":22, "VG":24]; +} + +bool validIBAN(string iban) { + // Ensure upper alphanumeric input. + iban = iban.removechars(whitespace); + if (!iban.match(r"^[\dA-Z]+$")) + return false; + + // Validate country code against expected length. + if (iban.length != country2len[iban[0 .. 2]]) + return false; + + // Shift and convert. BASE 36: 0..9,A..Z -> 0..35. + iban = iban[4 .. $] ~ iban[0 .. 4]; + return iban.map!(c => [c].to!int(36).text).join.BigInt % 97 == 1; +} + +void main() { + foreach (account; ["GB82 WEST 1234 5698 7654 32", + "GB82 TEST 1234 5698 7654 32"]) + writefln("%s validation is: %s", account, account.validIBAN); +} diff --git a/Task/IBAN/Go/iban.go b/Task/IBAN/Go/iban.go new file mode 100644 index 0000000000..e627a94a92 --- /dev/null +++ b/Task/IBAN/Go/iban.go @@ -0,0 +1,61 @@ +package main + +import ( + "fmt" + "strings" + "strconv" + "math/big" +) + +var lCode = map[string]int { + "AL": 28, "AD": 24, "AT": 20, "AZ": 28, "BE": 16, "BH": 22, "BA": 20, "BR": 29, + "BG": 22, "CR": 21, "HR": 21, "CY": 28, "CZ": 24, "DK": 18, "DO": 28, "EE": 20, + "FO": 18, "FI": 18, "FR": 27, "GE": 22, "DE": 22, "GI": 23, "GR": 27, "GL": 18, + "GT": 28, "HU": 28, "IS": 26, "IE": 22, "IL": 23, "IT": 27, "KZ": 20, "KW": 30, + "LV": 21, "LB": 28, "LI": 21, "LT": 20, "LU": 20, "MK": 19, "MT": 31, "MR": 27, + "MU": 30, "MC": 27, "MD": 24, "ME": 22, "NL": 18, "NO": 15, "PK": 24, "PS": 29, + "PL": 28, "PT": 25, "RO": 24, "SM": 27, "SA": 24, "RS": 22, "SK": 24, "SI": 19, + "ES": 24, "SE": 24, "CH": 21, "TN": 24, "TR": 26, "AE": 23, "GB": 22, "VG": 24, +} + +var sCode = map[string]int { + "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, + "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15, "G": 16, + "H": 17, "I": 18, "J": 19, "K": 20, "L": 21, "M": 22, "N": 23, + "O": 24, "P": 25, "Q": 26, "R": 27, "S": 28, "T": 29, "U": 30, + "V": 31, "W": 32, "X": 33, "Y": 34, "Z": 35, +} + +func main() { + + var iban string + var r, s, t, st []string + u := new(big.Int) + v := new(big.Int) + w := new(big.Int) + + iban = "GB82 TEST 1234 5698 7654 32" + r = strings.Split(iban, " ") + s = strings.Split(r[0], "") + t = strings.Split(r[1], "") + + st = []string{ strconv.Itoa(sCode[t[0]]), + strconv.Itoa(sCode[t[1]]), + strconv.Itoa(sCode[t[2]]), + strconv.Itoa(sCode[t[3]]), + strings.Join(r[2:6], ""), + strconv.Itoa(sCode[s[0]]), + strconv.Itoa(sCode[s[1]]), + strings.Join(s[2:4], ""), + } + + u.SetString(strings.Join(st, ""), 10) + v.SetInt64(97) + w.Mod(u, v) + + if w.Uint64() == 1 && lCode[strings.Join(s[0:2], "")] == len(strings.Join(r, "")) { + fmt.Printf("IBAN %s looks good!\n", iban) + } else { + fmt.Printf("IBAN %s looks wrong!\n", iban) + } +} diff --git a/Task/IBAN/Groovy/iban-1.groovy b/Task/IBAN/Groovy/iban-1.groovy new file mode 100644 index 0000000000..45b17cde65 --- /dev/null +++ b/Task/IBAN/Groovy/iban-1.groovy @@ -0,0 +1,16 @@ +def validateIBAN(String iban) { + def iso = [AL: 28, AD: 24, AT: 20, AZ: 28, BE: 16, BH: 22, BA: 20, BR: 29, BG: 22, + HR: 21, CY: 28, CZ: 24, DK: 18, DO: 28, EE: 20, FO: 18, FI: 18, FR: 27, GE: 22, DE: 22, GI: 23, + GL: 18, GT: 28, HU: 28, IS: 26, IE: 22, IL: 23, IT: 27, KZ: 20, KW: 30, LV: 21, LB: 28, LI: 21, + LT: 20, LU: 20, MK: 19, MT: 31, MR: 27, MU: 30, MC: 27, MD: 24, ME: 22, NL: 18, NO: 15, PK: 24, + PS: 29, PL: 28, PT: 25, RO: 24, SM: 27, SA: 24, RS: 22, SK: 24, SI: 19, ES: 24, SE: 24, CH: 21, + TN: 24, TR: 26, AE: 23, GB: 22, VG: 24, GR: 27, CR: 21] + + iban = iban.replaceAll(/\s/, '').toUpperCase() + if (iban.size() < 4 || iso[iban[0..1]] != iban.size()) return false + + iban = iban[4..-1] + iban[0..<4] + + def number = iban.collect { Character.digit(it as char, 36) }.join('') + (number as BigInteger).mod(97) == 1 +} diff --git a/Task/IBAN/Groovy/iban-2.groovy b/Task/IBAN/Groovy/iban-2.groovy new file mode 100644 index 0000000000..c1d13a388d --- /dev/null +++ b/Task/IBAN/Groovy/iban-2.groovy @@ -0,0 +1,7 @@ +[ 'GB82 WEST 1234 5698 7654 32', + 'GB82 TEST 1234 5698 7654 32', + 'GB81 WEST 1234 5698 7654 32', + 'SA03 8000 0000 6080 1016 7519', + 'CH93 0076 2011 6238 5295 7' ].each { iban -> + println "$iban is ${validateIBAN(iban) ? 'valid' : 'invalid'}" +} diff --git a/Task/IBAN/Haskell/iban.hs b/Task/IBAN/Haskell/iban.hs new file mode 100644 index 0000000000..7e6962a6c1 --- /dev/null +++ b/Task/IBAN/Haskell/iban.hs @@ -0,0 +1,55 @@ +import Data.Char (toUpper) + +validateIBAN :: String -> Either String String +validateIBAN [] = Left "No IBAN number." +validateIBAN xs = + case lookupCountry of + Nothing -> invalidBecause "Country does not exist." + Just l -> if length normalized /= l + then invalidBecause "Number length does not match." + else check + where + -- remove blanks and make all letters uppercase + normalized = map toUpper $ concat $ words xs + -- get the country code + country = take 2 normalized + -- search number length + lookupCountry = lookup country countries + countries :: [(String, Int)] + countries = zip (words "AL AT BE BA BG HR CZ DO FO FR DE GR GT \ + \IS IL KZ LV LI LU MT MU MD NL PK PL RO SA SK ES CH TR GB \ + \AD AZ BH BR CR CY DK EE FI GE GI GL HU IE IT KW LB LT MK \ + \MR MC ME NO PS PT SM RS SI SE TN AE VG") + [28,20,16,20,22,21,24,28,18,27,22,27,28,26,23,20,21,21,20, + 31,30,24,18,24,28,24,24,24,24,21,26,22,24,28,22,29,21,28,18, + 20,18,22,23,18,28,22,27,30,28,20,19,27,27,22,15,29,25,27,22, + 19,24,24,23,24] + digits = ['0'..'9'] + letters = ['A'..'Z'] + -- letters to be replaced + replDigits = zip letters $ map show [10..35] + -- digits and letters allowed in the IBAN number + validDigits = digits ++ letters + -- see if all digits and letters in the IBAN number are allowed + sane = all (`elem` validDigits) normalized + -- take the first 4 digits from the number and put them at its end + (p1, p2) = splitAt 4 normalized + p3 = p2 ++ p1 + -- convert the letters to numbers and + -- convert the result to an integer + p4 :: Integer + p4 = read $ concat $ convertLetters p3 + convertLetters [] = [] + convertLetters (x:xs) + | x `elem` digits = [x] : convertLetters xs + | otherwise = let (Just ys) = lookup x replDigits + in ys : convertLetters xs + -- see if the number is valid + check = if sane + then if p4 `mod` 97 == 1 + then Right xs + else invalidBecause "Validation failed." + else invalidBecause "Number contains illegal digits." + + invalidBecause reason = Left $ "Invalid IBAN number " ++ xs ++ + ": " ++ reason diff --git a/Task/IBAN/J/iban.j b/Task/IBAN/J/iban.j new file mode 100644 index 0000000000..a3f93c00c1 --- /dev/null +++ b/Task/IBAN/J/iban.j @@ -0,0 +1,34 @@ +NB. delete any blank characters +delblk =. #~ ' '&~: +NB. rearrange +rot =. '00' ,~ 2&}. @: (2&|.) +NB. characters -> "digits" +dig =. a. {~ (a.i.'0')+i.10 +dig =. dig,a. {~ (a.i.'A')+i.26 +todig =. dig&i. +coded =. [: ". 'x' ,~ delblk @: ": @: todig + +NB. calculate check sum +cs =: 98 - 97 | coded @: rot @: delblk f. + +NB. check sum as text +cstxt =. _2{. '0', [: ": cs +NB. replace first two characters +chgps =. [,2}.] +NB. shift country code +rotlc =. 2&|. +NB. insert check digits (position 3 and 4) +insertps =. chgps &.rotlc + +NB. IBAN with newly calculated check digits +ibancd =: (cstxt insertps ]) f. + +NB. check / generate check digits +ibancheck =: ] (]`('ok'"_) @. -:) ibancd + +NB. groups of four characters +insertblk =. #~ # $ 1 1 1 1j1"_ +quads =: insertblk @: delblk f. + +NB. IBAN +iban =: quads @: ibancheck diff --git a/Task/IBAN/Java/iban.java b/Task/IBAN/Java/iban.java new file mode 100644 index 0000000000..162cf8680a --- /dev/null +++ b/Task/IBAN/Java/iban.java @@ -0,0 +1,47 @@ +import java.math.BigInteger; +import java.util.*; + +public class IBAN { + static final Map isoPairs; + + static final String iso = "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 " + + "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 " + + "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 LB28 LI21 " + + "LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 " + + "PS29 PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 " + + "TN24 TR26 AE23 GB22 VG24 GR27 CR21"; + + static { + isoPairs = new HashMap<>(); + for (String p : iso.split(" ")) + isoPairs.put(p.substring(0, 2), Integer.parseInt(p.substring(2))); + } + + public static void main(String[] args) { + for (String iban : new String[]{"GB82 WEST 1234 5698 7654 32", + "GB82 TEST 1234 5698 7654 32", + "GB81 WEST 1234 5698 7654 32", + "SA03 8000 0000 6080 1016 7519", + "CH93 0076 2011 6238 5295 7"}) + System.out.printf("%s is valid: %s%n%n", iban, validateIBAN(iban)); + } + + static boolean validateIBAN(String iban) { + iban = iban.replaceAll("\\s", "").toUpperCase(); + + int len = iban.length(); + + if (len < 4 || isoPairs.get(iban.substring(0, 2)) != len) + return false; + + iban = iban.substring(4) + iban.substring(0, 4); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < len; i++) + sb.append(Character.digit(iban.charAt(i), 36)); + + BigInteger bigInt = new BigInteger(sb.toString()); + + return bigInt.mod(new BigInteger("97")).intValue() == 1; + } +} diff --git a/Task/IBAN/MATLAB/iban-1.m b/Task/IBAN/MATLAB/iban-1.m new file mode 100644 index 0000000000..6b7fc09041 --- /dev/null +++ b/Task/IBAN/MATLAB/iban-1.m @@ -0,0 +1,30 @@ +function valid = validateIBAN(iban) +% Determine if International Bank Account Number is valid IAW ISO 13616 +% iban - string containing account number + if length(iban) < 5 + valid = false; + else + iban(iban == ' ') = ''; % Remove spaces + iban = lower([iban(5:end) iban(1:4)])+0; % Rearrange and convert + iban(iban > 96 & iban < 123) = iban(iban > 96 & iban < 123)-87; % Letters + iban(iban > 47 & iban < 58) = iban(iban > 47 & iban < 58)-48; % Numbers + valid = piecewiseMod97(iban) == 1; + end +end + +function result = piecewiseMod97(x) +% Conduct a piecewise version of mod(x, 97) to support large integers +% x is a vector of integers + x = sprintf('%d', x); % Get to single-digits per index + nDig = length(x); + i1 = 1; + i2 = min(9, nDig); + prefix = ''; + while i1 <= nDig + y = str2double([prefix x(i1:i2)]); + result = mod(y, 97); + prefix = sprintf('%d', result); + i1 = i2+1; + i2 = min(i1+8, nDig); + end +end diff --git a/Task/IBAN/MATLAB/iban-2.m b/Task/IBAN/MATLAB/iban-2.m new file mode 100644 index 0000000000..c074972d18 --- /dev/null +++ b/Task/IBAN/MATLAB/iban-2.m @@ -0,0 +1,11 @@ +tests = {'GB82 WEST 1234 5698 7654 32' ; +'GB82 TEST 1234 5698 7654 32' ; +'CH93 0076 2011 6238 5295 7' ; +'SA03 8000 0000 6080 1016 7519' ; +'SA03 1234 5678 9101 1121 3141' ; +'GB29 NWBK 6016 1331 9268 19' ; +'GB29' ; +'GR16 0110 1250 0000 0001 2300 695'}; +for k = 1:length(tests) +fprintf('%s -> %svalid\n', tests{k}, char(~validateIBAN(tests{k}).*'in')) +end diff --git a/Task/IBAN/Mathematica/iban-1.math b/Task/IBAN/Mathematica/iban-1.math new file mode 100644 index 0000000000..58fa04aef6 --- /dev/null +++ b/Task/IBAN/Mathematica/iban-1.math @@ -0,0 +1,29 @@ +CountryCodes={{"AL",28},{"AD",24},{"AT",20},{"AZ",28},{"BE",16},{"BH",22},{"BA",20},{"BR",29},{"BG",22},{"CR",21},{"HR",21},{"CY",28},{"CZ",24},{"DK",18},{"DO",28},{"EE",20},{"FO",18},{"FI",18},{"FR",27},{"GE",22},{"DE",22},{"GI",23},{"GR",27},{"GL",18},{"GT",28},{"HU",28},{"IS",26},{"IE",22},{"IL",23},{"IT",27},{"KZ",20},{"KW",30},{"LV",21},{"LB",28},{"LI",21},{"LT",20},{"LU",20},{"MK",19},{"MT",31},{"MR",27},{"MU",30},{"MC",27},{"MD",24},{"ME",22},{"NL",18},{"NO",15},{"PK",24},{"PS",29},{"PL",28},{"PT",25},{"RO",24},{"SM",27},{"SA",24},{"RS",22},{"SK",24},{"SI",19},{"ES",24},{"SE",24},{"CH",21},{"TN",24},{"TR",26},{"AE",23},{"GB",22},{"VG",24}}; +ClearAll[IBANVerify] +IBANVerify[input_String]:=Module[{i,cc,rules}, + i=StringReplace[StringTrim[input],{" "->"","\t"->""}]; + cc=StringTake[i,2]; + If[MemberQ[CountryCodes[[All,1]],cc] + , + cc=Select[CountryCodes,First[#]==cc&][[1,2]]; + If[cc==StringLength[i] + , + i=StringRotateLeft[i,4]; + i=Characters[ToUpperCase[i]]; + rules=Rule@@@({CharacterRange["A","Z"],Range[10,35]}\[Transpose]); + i=i/.rules; + i=ToExpression/@i; + i=FromDigits[Flatten[IntegerDigits/@i]]; + If[Mod[i,97]===1 + , + True + , + False + ] + , + False + ] + , + False + ] +] diff --git a/Task/IBAN/Mathematica/iban-2.math b/Task/IBAN/Mathematica/iban-2.math new file mode 100644 index 0000000000..09444cfed2 --- /dev/null +++ b/Task/IBAN/Mathematica/iban-2.math @@ -0,0 +1,4 @@ +IBANVerify["GB82 WEST 1234 5698 7654 32"] +IBANVerify["GB82 WEST 1234 5698 7654 323"] +IBANVerify["GB82 WEST 1234 5698 7654 31"] +IBANVerify["XX82 WEST 1234 5698 7654 323"] diff --git a/Task/IBAN/Oberon-2/iban.oberon-2 b/Task/IBAN/Oberon-2/iban.oberon-2 new file mode 100644 index 0000000000..7529b905e8 --- /dev/null +++ b/Task/IBAN/Oberon-2/iban.oberon-2 @@ -0,0 +1,161 @@ +MODULE IBAN; +IMPORT + Out, + Err, + ADT:Dictionary, + Object:Boxed, + Object:BigInt, + Object, + Strings, + IntStr; +TYPE + IBANLen = Boxed.LongInt; +VAR + nations: Dictionary.Dictionary(STRING,IBANLen); + + PROCEDURE Check*(iban: ARRAY OF CHAR): BOOLEAN; + VAR + country,ibanStr: Object.String; + nLetter: ARRAY 3 OF CHAR; + block: ARRAY 5 OF CHAR; + numIban: ARRAY 256 OF CHAR; + num,den,res: BigInt.BigInt; + ibanLen: IBANLen; + i: LONGINT; + BEGIN + ibanStr := Object.NewLatin1(iban); + country := ibanStr.Substring(0,2); + IF ~nations.HasKey(country) THEN + Err.Object("Country " + country + " has not IBAN codes. "); + RETURN FALSE; + END; + ibanLen := nations.Get(country); + + IF SHORT(ibanLen.value) # Strings.Length(iban) THEN + Err.Object("IBAN length incorrect for " + country +". "); + RETURN FALSE + END; + + block[0] := 0X; + Strings.Extract(iban,0,4,block); + Strings.Delete(iban,0,4);Strings.Append(block,iban); + + numIban[0] := 0X; + FOR i := 0 TO LEN(iban) - 1 DO + nLetter[0] := 0X; + IF (iban[i] >= 'A') & (iban[i] <= 'Z') THEN + IntStr.IntToStr(ORD(iban[i]) - ORD('A') + 10,nLetter); + ELSE + nLetter[0] := iban[i]; + nLetter[1] := 0X + END; + Strings.Append(nLetter,numIban); + END; + Strings.Append(0X,numIban); + + num := BigInt.New(Object.NewLatin1(numIban),10); + den := BigInt.New("97",10); + res := num.Mod(den); + IF res.Equals(BigInt.one) THEN + RETURN TRUE + ELSE + Err.String("IBAN code check failed. "); + RETURN FALSE + END + END Check; + + PROCEDURE CodeLengthFor*(country: ARRAY OF CHAR): LONGINT; + VAR + countryStr: Object.String; + ibanLen: IBANLen; + BEGIN + countryStr := Object.NewLatin1(country); + ibanLen := Boxed.zeroLongInt; + IF nations.HasKey(countryStr) THEN + ibanLen := nations.Get(countryStr) + END; + RETURN ibanLen.value + END CodeLengthFor; + + PROCEDURE Test*; + PROCEDURE DoCheck(iban: ARRAY OF CHAR); + BEGIN + Out.String("IBAN[");Out.String(iban);Out.String("]=");Out.Bool(Check(iban)); + Out.Ln + END DoCheck; + BEGIN + DoCheck("CH9300762011623852957"); + DoCheck("GB82WEST12345698765432"); + DoCheck("SA0380000000608010167519"); + DoCheck("XX0380000000608010167519"); + END Test; + +BEGIN + nations := NEW(Dictionary.Dictionary(STRING,Boxed.LongInt)); + nations.Set("AL",NEW(IBANLen,28)); + nations.Set("AD",NEW(IBANLen,24)); + nations.Set("AT",NEW(IBANLen,20)); + nations.Set("AZ",NEW(IBANLen,28)); + nations.Set("BE",NEW(IBANLen,16)); + nations.Set("BH",NEW(IBANLen,22)); + nations.Set("BA",NEW(IBANLen,20)); + nations.Set("BR",NEW(IBANLen,29)); + nations.Set("BG",NEW(IBANLen,22)); + nations.Set("CR",NEW(IBANLen,21)); + nations.Set("HR",NEW(IBANLen,21)); + nations.Set("CY",NEW(IBANLen,28)); + nations.Set("CZ",NEW(IBANLen,24)); + nations.Set("DK",NEW(IBANLen,18)); + nations.Set("DO",NEW(IBANLen,28)); + nations.Set("EE",NEW(IBANLen,20)); + nations.Set("FO",NEW(IBANLen,18)); + nations.Set("FI",NEW(IBANLen,18)); + nations.Set("FR",NEW(IBANLen,27)); + nations.Set("GE",NEW(IBANLen,22)); + nations.Set("DE",NEW(IBANLen,22)); + nations.Set("GI",NEW(IBANLen,23)); + nations.Set("GR",NEW(IBANLen,27)); + nations.Set("GL",NEW(IBANLen,18)); + nations.Set("GT",NEW(IBANLen,28)); + nations.Set("HU",NEW(IBANLen,28)); + nations.Set("IS",NEW(IBANLen,26)); + nations.Set("IE",NEW(IBANLen,22)); + nations.Set("IL",NEW(IBANLen,23)); + nations.Set("IT",NEW(IBANLen,27)); + nations.Set("KZ",NEW(IBANLen,20)); + nations.Set("KW",NEW(IBANLen,30)); + nations.Set("LV",NEW(IBANLen,21)); + nations.Set("LB",NEW(IBANLen,28)); + nations.Set("LI",NEW(IBANLen,21)); + nations.Set("LT",NEW(IBANLen,20)); + nations.Set("LU",NEW(IBANLen,20)); + nations.Set("MK",NEW(IBANLen,19)); + nations.Set("MT",NEW(IBANLen,31)); + nations.Set("MR",NEW(IBANLen,27)); + nations.Set("MU",NEW(IBANLen,30)); + nations.Set("MC",NEW(IBANLen,27)); + nations.Set("MD",NEW(IBANLen,24)); + nations.Set("ME",NEW(IBANLen,22)); + nations.Set("NL",NEW(IBANLen,18)); + nations.Set("NO",NEW(IBANLen,15)); + nations.Set("PK",NEW(IBANLen,24)); + nations.Set("PS",NEW(IBANLen,29)); + nations.Set("PL",NEW(IBANLen,28)); + nations.Set("PT",NEW(IBANLen,25)); + nations.Set("RO",NEW(IBANLen,24)); + nations.Set("SM",NEW(IBANLen,27)); + nations.Set("SA",NEW(IBANLen,24)); + nations.Set("RS",NEW(IBANLen,22)); + nations.Set("SK",NEW(IBANLen,24)); + nations.Set("SI",NEW(IBANLen,19)); + nations.Set("ES",NEW(IBANLen,24)); + nations.Set("SE",NEW(IBANLen,24)); + nations.Set("CH",NEW(IBANLen,21)); + nations.Set("TN",NEW(IBANLen,24)); + nations.Set("TR",NEW(IBANLen,26)); + nations.Set("AE",NEW(IBANLen,23)); + nations.Set("GB",NEW(IBANLen,22)); + nations.Set("VG",NEW(IBANLen,24)); + + Test; +END IBAN. diff --git a/Task/IBAN/Perl-6/iban.pl6 b/Task/IBAN/Perl-6/iban.pl6 new file mode 100644 index 0000000000..a301b60ab5 --- /dev/null +++ b/Task/IBAN/Perl-6/iban.pl6 @@ -0,0 +1,19 @@ +subset IBAN of Str where sub ($_ is copy) { + s:g/\s//; + return False if m/<-[ 0..9 A..Z a..z ]>/ or .chars != < + AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21 + CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27 + GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26 + IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22 + MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24 + RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24 + >.hash{.substr(0,2).uc}; + + s/(.**4)(.+)/$1$0/; + return .subst(:g, /\D/, { :36(~$_) }) % 97 == 1; +} + +say "$_ is {$_ ~~ IBAN ?? 'valid' !! 'invalid' }" for +'GB82 WEST 1234 5698 7654 32', +'gb82 west 1234 5698 7654 32', +'GB82 TEST 1234 5698 7654 32'; diff --git a/Task/IBAN/Perl/iban.pl b/Task/IBAN/Perl/iban.pl new file mode 100644 index 0000000000..eb85927f85 --- /dev/null +++ b/Task/IBAN/Perl/iban.pl @@ -0,0 +1,48 @@ +#!/usr/bin/perl +use strict ; +use warnings ; +use Math::BigInt ; + +my %countrycodelengths = ( "AL" => 28, "AD" => 24, "AT" => 20, "AZ" => 28, + "BE" => 16, "BH" => 22, "BA" => 20, "BR" => 29, + "BG" => 22, "CR" => 21, "HR" => 21, "CY" => 28, + "CZ" => 24, "DK" => 18, "DO" => 28, "EE" => 20, + "FO" => 18, "FI" => 18, "FR" => 27, "GE" => 22, + "DE" => 22, "GI" => 23, "GR" => 27, "GL" => 18, + "GT" => 28, "HU" => 28, "IS" => 26, "IE" => 22, + "IL" => 23, "IT" => 27, "KZ" => 20, "KW" => 30, + "LV" => 21, "LB" => 28, "LI" => 21, "LT" => 20, + "LU" => 20, "MK" => 19, "MT" => 31, "MR" => 27, + "MU" => 30, "MC" => 27, "MD" => 24, "ME" => 22, + "NL" => 18, "NO" => 15, "PK" => 24, "PS" => 29, + "PL" => 28, "PT" => 25, "RO" => 24, "SM" => 27, + "SA" => 24, "RS" => 22, "SK" => 24, "SI" => 19, + "ES" => 24, "SE" => 24, "CH" => 21, "TN" => 24, + "TR" => 26, "AE" => 23, "GB" => 22, "VG" => 24 ) ; +sub validate_iban { + my $ibanstring = shift ; + $ibanstring =~ s/\s+//g ; + return 0 unless $ibanstring =~ /[0-9a-zA-Z]+/ ; + $ibanstring = uc $ibanstring ; + return 0 if ( not exists $countrycodelengths{ substr( $ibanstring , 0 , 2 ) } ); + return 0 if length ( $ibanstring ) != $countrycodelengths{ substr( $ibanstring , 0 , 2 ) } ; + $ibanstring =~ s/(.{4})(.+)/$2$1/ ; + $ibanstring =~ s/([A-Z])/ord( $1 ) - 55/eg ; + my $number = Math::BigInt->new( $ibanstring ) ; + if ( $number->bmod( 97 ) == 1 ) { + return 1 ; + } + else { + return 0 ; + } +} + +if ( validate_iban( "GB82 WEST 1234 5698 7654 32" ) ) { + print "GB82 WEST 1234 5698 7654 32 is a valid IBAN number!\n" ; +} +else { + print "Sorry! GB82 WEST 1234 5698 7654 32 is not valid!\n" ; +} +if ( validate_iban( "GB82TEST12345698765432" ) ) { + print "GB82TEST12345698765432 is valid!\n" ; +} diff --git a/Task/IBAN/PicoLisp/iban.l b/Task/IBAN/PicoLisp/iban.l new file mode 100644 index 0000000000..b7fabbed32 --- /dev/null +++ b/Task/IBAN/PicoLisp/iban.l @@ -0,0 +1,30 @@ +(setq *Sizes '((GB . 22) (CH . 21) (SA . 24))) + +(de iban (Str) + (let Lst + (filter + '((X) (not (sp? X))) + (chop (uppc Str)) ) + (when + (= + (cdr (assoc (pack (head 2 Lst)) *Sizes)) + (length Lst) ) + (% + (format + (mapcar + '((X) + (if (upp? X) + (- (char X) 55) + X ) ) + (append (nth Lst 5) (head 4 Lst)) ) ) + 97 ) ) ) ) + +(for I '("sa03 8000 0000 6080 1016 7519" + "CH9300762011623852957" + "gb82west1234 56987654 32" + "GB82WEST000") + (if (= 1 (iban I)) + (println 'Valid) + (println 'Invalid) ) ) + +(bye) diff --git a/Task/IBAN/Python/iban.py b/Task/IBAN/Python/iban.py new file mode 100644 index 0000000000..77aadab1f9 --- /dev/null +++ b/Task/IBAN/Python/iban.py @@ -0,0 +1,28 @@ +import re + +_country2length = dict( + AL=28, AD=24, AT=20, AZ=28, BE=16, BH=22, BA=20, BR=29, + BG=22, CR=21, HR=21, CY=28, CZ=24, DK=18, DO=28, EE=20, + FO=18, FI=18, FR=27, GE=22, DE=22, GI=23, GR=27, GL=18, + GT=28, HU=28, IS=26, IE=22, IL=23, IT=27, KZ=20, KW=30, + LV=21, LB=28, LI=21, LT=20, LU=20, MK=19, MT=31, MR=27, + MU=30, MC=27, MD=24, ME=22, NL=18, NO=15, PK=24, PS=29, + PL=28, PT=25, RO=24, SM=27, SA=24, RS=22, SK=24, SI=19, + ES=24, SE=24, CH=21, TN=24, TR=26, AE=23, GB=22, VG=24 ) + +def valid_iban(iban): + # Ensure upper alphanumeric input. + iban = iban.replace(' ','').replace('\t','') + if not re.match(r'^[\dA-Z]+$', iban): + return False + # Validate country code against expected length. + if len(iban) != _country2length[iban[:2]]: + return False + # Shift and convert. + iban = iban[4:] + iban[:4] + digits = int(''.join(str(int(ch, 36)) for ch in iban)) #BASE 36: 0..9,A..Z -> 0..35 + return digits % 97 == 1 + +if __name__ == '__main__': + for account in ["GB82 WEST 1234 5698 7654 32", "GB82 TEST 1234 5698 7654 32"]: + print('%s validation is: %s' % (account, valid_iban(account))) diff --git a/Task/IBAN/README b/Task/IBAN/README new file mode 100644 index 0000000000..32458539fd --- /dev/null +++ b/Task/IBAN/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/IBAN diff --git a/Task/IBAN/REXX/iban-1.rexx b/Task/IBAN/REXX/iban-1.rexx new file mode 100644 index 0000000000..ebd1274bb9 --- /dev/null +++ b/Task/IBAN/REXX/iban-1.rexx @@ -0,0 +1,47 @@ +/*REXX program validates an IBAN (International Bank Account Number). */ + @. = + @.1 = 'GB82 WEST 1234 5698 7654 32 ' + @.2 = 'Gb82 West 1234 5698 7654 32 ' + @.3 = 'GB82 TEST 1234 5698 7654 32 ' + @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' + @.5 = 'GB29 NWBK 6016 1331 9268 19 ' + @.6 = 'SA03 8000 0000 6080 1016 7519 ' + @.7 = 'CH93 0076 2011 6238 5295 7 ' + @.8 = 'IL62 0108 0000 0009 9999 999 ' + @.9 = 'IL62-0108-0000-0009-9999-999 ' + @.10 = 'US12 3456 7890 0987 6543 210 ' + @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' +parse arg @.0 /*get optional first argument.*/ + do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1──►n*/ + r = validateIBAN(@.k) + if r==0 then say ' valid IBAN:' @.k + else say 'invalid IBAN:' @.k " " r + if k==0 then leave /*if user specified IBAN, we done*/ + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────────────────*/ +valIdateIBAN: procedure; arg x; numeric digits 200 /*allow big #s*/ +x=space(x,0); L=length(x) /*elide blanks, determine length.*/ +cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', + 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', + 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', + 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', + 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', + 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country,L*/ +@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet & decimal digs*/ +cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code, checkDig*/ +c#=wordpos(cc_,cc) /*find the country code index. */ +if c#==0 then return '***error!*** invalid country code:' cc_ +if \datatype(x,'A') then return '***error!*** invalid character:', + substr(x,verify(x,@abc#),1) +cL=word(cc,c#+1) /*get length of country's IBAN. */ +if cL\==L then return '***error!*** invalid IBAN length:' L ' (should be' cL")" +y=substr(x,5)left(x,4) /*put 4 in front ───► the back. */ +z= /*translate characters──►digits. */ + do j=1 for L; _=substr(y,j,1) + if datatype(_,'U') then z=z || pos(_,@abc#)+9 + else z=z || _ + end /*j*/ + +if z//97==1 then return 0 /*check to see if correct modulus*/ + return '***error!*** invalid check digits.' diff --git a/Task/IBAN/REXX/iban-2.rexx b/Task/IBAN/REXX/iban-2.rexx new file mode 100644 index 0000000000..4fc4508596 --- /dev/null +++ b/Task/IBAN/REXX/iban-2.rexx @@ -0,0 +1,56 @@ +/*REXX program validates an IBAN (International Bank Account Number). */ + @. = + @.1 = 'GB82 WEST 1234 5698 7654 32 ' + @.2 = 'Gb82 West 1234 5698 7654 32 ' + @.3 = 'GB82 TEST 1234 5698 7654 32 ' + @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' + @.5 = 'GB29 NWBK 6016 1331 9268 19 ' + @.6 = 'SA03 8000 0000 6080 1016 7519 ' + @.7 = 'CH93 0076 2011 6238 5295 7 ' + @.8 = 'IL62 0108 0000 0009 9999 999 ' + @.9 = 'IL62-0108-0000-0009-9999-999 ' + @.10 = 'US12 3456 7890 0987 6543 210 ' + @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' + @.12 = 'GT11 2222 3333 4444 5555 6666 7777 ' + @.13 = 'MK11 2222 3333 4444 555 ' +parse arg @.0 /*get optional first argument.*/ + do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1──►n*/ + r = validateIBAN(@.k) + if r==0 then say ' valid IBAN:' @.k + else say 'invalid IBAN:' @.k " " r + if k==0 then leave /*if user specified IBAN, we done*/ + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────────────────────────────────────────────────*/ +valIdateIBAN: procedure; arg x; numeric digits 200 /*allow big #s*/ +x=space(x,0); L=length(x) /*elide blanks, determine length.*/ +cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', + 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', + 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', + 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', + 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', + 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country,L*/ +@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet & decimal digs*/ +cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code, checkDig*/ +c#=wordpos(cc_,cc) /*find the country code index. */ +if c#==0 then return '***error!*** invalid country code:' cc_ +if \datatype(x,'A') then return '***error!*** invalid character:', + substr(x,verify(x,@abc#),1) +cL=word(cc,c#+1) /*get length of country's IBAN. */ +if cL\==L then return '***error!*** invalid IBAN length:' L ' (should be' cL")" +if cc_=='BR' & date("S")<20130701 then return "***error!*** invalid IBAN country, Brazil isn't valid until 1-July-2013." +if cc_=='GT' & date("S")<20140701 then return "***error!*** invalid IBAN country, Guatemala isn't valid until 1-July-2014." +if cc_=='BA' & kk\==39 then return "***error!*** invalid check digits for Bosnia and Herzegovina:" kk +if cc_=='MK' & kk\==07 then return "***error!*** invalid check digits for Macedonia:" kk +if cc_=='ME' & kk\==25 then return "***error!*** invalid check digits for Montenegro:" kk +if cc_=='PT' & kk\==50 then return "***error!*** invalid check digits for Portugal:" kk +if cc_=='SI' & kk\==56 then return "***error!*** invalid check digits for Slovenia:" kk +y=substr(x,5)left(x,4) /*put 4 in front ───► the back. */ +z= /*translate characters──►digits. */ + do j=1 for L; _=substr(y,j,1) + if datatype(_,'U') then z=z || pos(_,@abc#)+9 + else z=z || _ + end /*j*/ + +if z//97==1 then return 0 /*check to see if correct modulus*/ + return '***error!*** invalid check digits.' diff --git a/Task/IBAN/Racket/iban.rkt b/Task/IBAN/Racket/iban.rkt new file mode 100644 index 0000000000..de60e05a67 --- /dev/null +++ b/Task/IBAN/Racket/iban.rkt @@ -0,0 +1,25 @@ +#lang racket +(define lens + '([AL 28] [AD 24] [AT 20] [AZ 28] [BH 22] [BE 16] [BA 20] [BR 29] [BG 22] + [CR 21] [HR 21] [CY 28] [CZ 24] [DK 18] [DO 28] [EE 20] [FO 18] [FI 18] + [FR 27] [GE 22] [DE 22] [GI 23] [GR 27] [GL 18] [GT 28] [HU 28] [IS 26] + [IE 22] [IL 23] [IT 27] [KZ 20] [KW 30] [LV 21] [LB 28] [LI 21] [LT 20] + [LU 20] [MK 19] [MT 31] [MR 27] [MU 30] [MC 27] [MD 24] [ME 22] [NL 18] + [NO 15] [PK 24] [PS 29] [PL 28] [PT 25] [RO 24] [SM 27] [SA 24] [RS 22] + [SK 24] [SI 19] [ES 24] [SE 24] [CH 21] [TN 24] [TR 26] [AE 23] [GB 22] + [VG 24])) +(define (valid-iban? str) + (define str* (regexp-replace* #px"\\s+" str "")) + (define c (cond [(regexp-match #rx"^[A-Z][A-Z]" str*) + => (λ(x) (assq (string->symbol (car x)) lens))] + [else #f])) + (define (letter c) + (number->string (+ (char->integer (string-ref c 0)) -65 10))) + (and c (= (cadr c) (string-length str*)) + (regexp-match? #rx"[A-Z0-9]" str*) + (let* ([x (string-append (substring str* 4) (substring str* 0 4))] + [x (string->number (regexp-replace* #rx"[A-Z]" x letter))]) + (= 1 (modulo x 97))))) + +(valid-iban? "GB82 WEST 1234 5698 7654 32") ; => #t +(valid-iban? "GB82 TEST 1234 5698 7654 32") ; => #f diff --git a/Task/IBAN/Ruby/iban.rb b/Task/IBAN/Ruby/iban.rb new file mode 100644 index 0000000000..347971e47c --- /dev/null +++ b/Task/IBAN/Ruby/iban.rb @@ -0,0 +1,29 @@ +def valid_iban? iban + len = { + AL: 28, AD: 24, AT: 20, AZ: 28, BE: 16, BH: 22, BA: 20, BR: 29, + BG: 22, CR: 21, HR: 21, CY: 28, CZ: 24, DK: 18, DO: 28, EE: 20, + FO: 18, FI: 18, FR: 27, GE: 22, DE: 22, GI: 23, GR: 27, GL: 18, + GT: 28, HU: 28, IS: 26, IE: 22, IL: 23, IT: 27, KZ: 20, KW: 30, + LV: 21, LB: 28, LI: 21, LT: 20, LU: 20, MK: 19, MT: 31, MR: 27, + MU: 30, MC: 27, MD: 24, ME: 22, NL: 18, NO: 15, PK: 24, PS: 29, + PL: 28, PT: 25, RO: 24, SM: 27, SA: 24, RS: 22, SK: 24, SI: 19, + ES: 24, SE: 24, CH: 21, TN: 24, TR: 26, AE: 23, GB: 22, VG: 24 + } + + # Ensure upper alphanumeric input. + iban.delete! " \t" + return false unless iban =~ /^[\dA-Z]+$/ + + # Validate country code against expected length. + cc = iban[0, 2].to_sym + return false unless iban.size == len[cc] + + # Shift and convert. + iban = iban[4..-1] + iban[0, 4] + iban.gsub!(/./) { |c| c.to_i(36) } + + iban.to_i % 97 == 1 +end + +p valid_iban? "GB82 WEST 1234 5698 7654 32" #=> true +p valid_iban? "GB82 TEST 1234 5698 7654 32" #=> false diff --git a/Task/IBAN/Scala/iban-1.scala b/Task/IBAN/Scala/iban-1.scala new file mode 100644 index 0000000000..d2f590ebe6 --- /dev/null +++ b/Task/IBAN/Scala/iban-1.scala @@ -0,0 +1,45 @@ +import scala.collection.immutable.SortedMap + +class Iban(val iban: String) { + // Isolated tests + def isAllUpperCase = iban.toUpperCase == iban + + def isValidpattern = (Iban.pattern findFirstIn iban).nonEmpty + + def isNationalSize = { + Iban.ccVsLength.getOrElse(iban.take(2), 0) == iban.size + } + + def isCheckNumberOK = { + def rearrange = (iban.drop(4) + iban.take(4)). // Move left country code part to end + // continue with each char converted to Int + map(ch => if (ch.isDigit) ch.toInt - '0' else ch - 'A' + 10).mkString + + (BigInt(rearrange) mod 97) == 1 + } + + def isValidIban = { + isAllUpperCase && + isValidpattern && + isNationalSize && + isCheckNumberOK + } +} + +object Iban { + // IBAN length database + lazy val ccVsLength: SortedMap[String, Int] = SortedMap[String, Int]() ++ + """AD24 AE23 AL28 AO25 AT20 AZ28 BA20 BE16 BF27 BG22 BH22 BI16 + |BJ28 BR29 CG27 CH21 CI28 CM27 CR21 CV25 CY28 CZ24 DE22 DK18 + |DO28 DZ24 EE20 EG27 ES24 FI18 FO18 FR27 GA27 GB22 GE22 GI23 + |GL18 GR27 GT28 HR21 HU28 IE22 IL23 IR26 IS26 IT27 JO30 KW30 + |KZ20 LB28 LI21 LT20 LU20 LV21 MC27 MD24 ME22 MG27 MK19 ML28 + |MR27 MT31 MU30 MZ25 NL18 NO15 PK24 PL28 PS29 PT25 QA29 RO24 + |RS22 SA24 SE24 SI19 SK24 SM27 SN28 TN24 TR26 UA29 VG24""". + stripMargin.replaceAll( """\s""", " ").split(' '). + map(v => (v.take(2), if (v.isEmpty) 0 else v.slice(2, 4).toInt)) + + lazy val pattern = "([A-Z]{2})([0-9]{2})([A-Z0-9]{4})([A-Z0-9]{0,2})([0-9]{7})(([A-Z0-9]?){0,16})".r + + def apply(s: String) = new Iban(s.replaceAll( """\s""", "")) +} diff --git a/Task/IBAN/Scala/iban-2.scala b/Task/IBAN/Scala/iban-2.scala new file mode 100644 index 0000000000..4820fc21f3 --- /dev/null +++ b/Task/IBAN/Scala/iban-2.scala @@ -0,0 +1,98 @@ +object IbanTest extends App { + def blackCases = """AT611904300235473201 + |GB82TEST12345698765432 + |GB81WEST12345698765432""".stripMargin + + def whiteCases = """AD1200012030200359100100 + |AE26 0211 0000 0023 0064 016 + |AL47 2121 1009 0000 0002 3569 8741 + |AO06000600000100037131174 + |AZ21NABZ00000000137010001944 + |BA391290079401028494 + |BE68539007547034 + |BF1030134020015400945000643 + |BG80BNBG96611020345678 + |BH29BMAG1299123456BH00 + |BI43201011067444 + |BJ11B00610100400271101192591 + |BR9700360305000010009795493P1 + |CG5230011000202151234567890 + |CH9300762011623852957 + |CI05A00060174100178530011852 + |CM2110003001000500000605306 + |CR0515202001026284066 + |CV64000300004547069110176 + |CY17002001280000001200527600 + |CZ6508000000192000145399 + |DE89370400440532013000 + |DK5000400440116243 + |DO28BAGR00000001212453611324 + |DZ4000400174401001050486 + |EE382200221020145685 + |EG1100006001880800100014553 + |ES9121000418450200051332 + |FI2112345600000785 + |FO1464600009692713 + |FR1420041010050500013M02606 + |FR7630007000110009970004942 + |GA2140002000055602673300064 + |GB29NWBK60161331926819 + |GE29NB0000000101904917 + |GI75NWBK000000007099453 + |GL8964710001000206 + |GR1601101250000000012300695 + |GT82TRAJ01020000001210029690 + |HR1210010051863000160 + |HU42117730161111101800000000 + |IE29AIBK93115212345678 + |IL620108000000099999999 + |IR580540105180021273113007 + |IS140159260076545510730339 + |IT60X0542811101000000123456 + |JO94CBJO0010000000000131000302 + |KW74NBOK0000000000001000372151 + |KZ176010251000042993 + |LB30099900000001001925579115 + |LI21088100002324013AA + |LT121000011101001000 + |LU280019400644750000 + |LV80BANK0000435195001 + |MC5813488000010051108001292 + |MD24AG000225100013104168 + |ME25505000012345678951 + |MG4600005030010101914016056 + |MK07300000000042425 + |ML03D00890170001002120000447 + |MR1300012000010000002037372 + |MT84MALT011000012345MTLCAST001S + |MU17BOMM0101101030300200000MUR + |MZ59000100000011834194157 + |NL91ABNA0417164300 + |NL81 TRIO 0212 4710 66 + |NO9386011117947 + |PK24SCBL0000001171495101 + |PL27114020040000300201355387 + |PS92PALS000000000400123456702 + |PT50000200000163099310355 + |PT50000201231234567890154 + |QA58 DOHB 0000 1234 5678 90AB CDEF G + |RO49 AAAA 1B31 0075 9384 0000 + |RS35260005601001611379 + |SA0380000000608010167519 + |SE3550000000054910000003 + |SI56191000000123438 + |SK3112000000198742637541 + |SM86U0322509800000000270100 + |SN12K00100152000025690007542 + |TN5914207207100707129648 + |TR330006100519786457841326 + |UA57 3543 4700 0676 2462 0549 2502 6 + |VG96 VPVG 0000 0123 4567 8901 + |GB82 WEST 1234 5698 7654 32 + |SA03 8000 0000 6080 1016 7519 + |CH93 0076 2011 6238 5295 7""".stripMargin + + whiteCases.lines.foreach(l => assert(Iban(l).isValidIban)) + blackCases.lines.foreach(l => assert(!Iban(l).isValidIban)) + println(s"Successfully completed; ${whiteCases.lines.size + blackCases.lines.size} cases tested, no errors.") +} diff --git a/Task/IBAN/Seed7/iban.seed7 b/Task/IBAN/Seed7/iban.seed7 new file mode 100644 index 0000000000..1299aa3ead --- /dev/null +++ b/Task/IBAN/Seed7/iban.seed7 @@ -0,0 +1,57 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const type: countryHash is hash [string] integer; + +const func countryHash: initCountryCode is func + result + var countryHash: cc is countryHash.value; + begin + cc @:= ["AL"] 28; cc @:= ["AD"] 24; cc @:= ["AT"] 20; cc @:= ["AZ"] 28; cc @:= ["BE"] 16; cc @:= ["BH"] 22; + cc @:= ["BA"] 20; cc @:= ["BR"] 29; cc @:= ["BG"] 22; cc @:= ["CR"] 21; cc @:= ["HR"] 21; cc @:= ["CY"] 28; + cc @:= ["CZ"] 24; cc @:= ["DK"] 18; cc @:= ["DO"] 28; cc @:= ["EE"] 20; cc @:= ["FO"] 18; cc @:= ["FI"] 18; + cc @:= ["FR"] 27; cc @:= ["GE"] 22; cc @:= ["DE"] 22; cc @:= ["GI"] 23; cc @:= ["GR"] 27; cc @:= ["GL"] 18; + cc @:= ["GT"] 28; cc @:= ["HU"] 28; cc @:= ["IS"] 26; cc @:= ["IE"] 22; cc @:= ["IL"] 23; cc @:= ["IT"] 27; + cc @:= ["KZ"] 20; cc @:= ["KW"] 30; cc @:= ["LV"] 21; cc @:= ["LB"] 28; cc @:= ["LI"] 21; cc @:= ["LT"] 20; + cc @:= ["LU"] 20; cc @:= ["MK"] 19; cc @:= ["MT"] 31; cc @:= ["MR"] 27; cc @:= ["MU"] 30; cc @:= ["MC"] 27; + cc @:= ["MD"] 24; cc @:= ["ME"] 22; cc @:= ["NL"] 18; cc @:= ["NO"] 15; cc @:= ["PK"] 24; cc @:= ["PS"] 29; + cc @:= ["PL"] 28; cc @:= ["PT"] 25; cc @:= ["RO"] 24; cc @:= ["SM"] 27; cc @:= ["SA"] 24; cc @:= ["RS"] 22; + cc @:= ["SK"] 24; cc @:= ["SI"] 19; cc @:= ["ES"] 24; cc @:= ["SE"] 24; cc @:= ["CH"] 21; cc @:= ["TN"] 24; + cc @:= ["TR"] 26; cc @:= ["AE"] 23; cc @:= ["GB"] 22; cc @:= ["VG"] 24; + end func; + +const countryHash: countryCode is initCountryCode; + +const func boolean: isLegal (in var string: iban) is func + result + var boolean: legal is FALSE; + local + var char: ch is ' '; + var string: converted is ""; + begin + iban := upper(replace(iban, " ", "")); + legal := iban[.. 2] in countryCode and countryCode[iban[.. 2]] = length(iban); + iban := iban[5 ..] & iban[.. 4]; + for ch range iban do + case ch of + when {'0' .. '9'}: converted &:= ch; + when {'A' .. 'Z'}: converted &:= str(ord(ch) - ord('A') + 10); + otherwise: legal := FALSE; + end case; + end for; + legal := legal and (bigInteger parse converted) rem 97_ = 1_; + end func; + +const proc: check (in string: iban) is func + begin + writeln("Valid " <& iban <& ": " <& isLegal(iban)); + end func; + +const proc: main is func + begin + check("GB82 WEST 1234 5698 7654 32"); + check("GB82WEST12345698765432"); + check("gb82 west 1234 5698 7654 32"); + check("GB82 TEST 1234 5698 7654 32"); + check("GB82 WEST 1243 5698 7654 32"); + end func; diff --git a/Task/IBAN/Tcl/iban-1.tcl b/Task/IBAN/Tcl/iban-1.tcl new file mode 100644 index 0000000000..1630f3c1e7 --- /dev/null +++ b/Task/IBAN/Tcl/iban-1.tcl @@ -0,0 +1,34 @@ +proc verifyIBAN {iban} { + # Normalize by up-casing and stripping illegal chars (e.g., space) + set iban [regsub -all {[^A-Z0-9]+} [string toupper $iban] ""] + # Get the expected length from the country-code part + switch [string range $iban 0 1] { + NO { set len 15 } + BE { set len 16 } + DK - FI - FO - GL - NL { set len 18} + MK - SI { set len 19 } + AT - BA - EE - KZ - LT - LU { set len 20 } + CH - CR - HR - LI - LV { set len 21 } + BG - BH - DE - GB - GE - IE - ME - RS { set len 22 } + AE - GI - IL { set len 23 } + AD - CZ - ES - MD - PK - RO - SA - SE - SK - TN - VG { set len 24 } + PT { set len 25 } + IS - TR { set len 26 } + FR - GR - IT - MC - MR - SM { set len 27 } + AL - AZ - CY - DO - GT - HU - LB - PL { set len 28 } + BR - PS { set len 29 } + KW - MU { set len 30 } + MT { set len 31 } + default { + # unsupported country code + return false + } + } + # Convert to number + set num [string map { + A 10 B 11 C 12 D 13 E 14 F 15 G 16 H 17 I 18 J 19 K 20 L 21 M 22 + N 23 O 24 P 25 Q 26 R 27 S 28 T 29 U 30 V 31 W 32 X 33 Y 34 Z 35 + } [string range $iban 4 end][string range $iban 0 3]] + # Verify length and modulus + return [expr {[string length $iban] == $len && $num % 97 == 1}] +} diff --git a/Task/IBAN/Tcl/iban-2.tcl b/Task/IBAN/Tcl/iban-2.tcl new file mode 100644 index 0000000000..b769001c30 --- /dev/null +++ b/Task/IBAN/Tcl/iban-2.tcl @@ -0,0 +1,4 @@ +set iban "GB82 WEST 1234 5698 7654 32" +puts "$iban is [expr {[verifyIBAN $iban] ? {verified} : {unverified}}]" +set not "GB42 WEST 1234 5698 7654 32" +puts "$not is [expr {[verifyIBAN $not] ? {verified} : {unverified}}]" diff --git a/Task/IBAN/UNIX-Shell/iban.sh b/Task/IBAN/UNIX-Shell/iban.sh new file mode 100644 index 0000000000..8a2c450573 --- /dev/null +++ b/Task/IBAN/UNIX-Shell/iban.sh @@ -0,0 +1,34 @@ +declare -A base36=( + [A]=10 [B]=11 [C]=12 [D]=13 [E]=14 [F]=15 [G]=16 [H]=17 [I]=18 + [J]=19 [K]=20 [L]=21 [M]=22 [N]=23 [O]=24 [P]=25 [Q]=26 [R]=27 + [S]=28 [T]=29 [U]=30 [V]=31 [W]=32 [X]=33 [Y]=34 [Z]=35 +) + +function is_iban { + local -u acct=${1//[^[:alnum:]]/} + acct=${acct:4}${acct:0:4} + local i char digits="" + for ((i=0; i<${#acct}; i++)); do + char=${acct:i:1} + digits+=${base36[$char]:-$char} + done + local mod=$(mod97 $digits) + (( mod == 1 )) +} + +function mod97 { + local D=$1 + N=${D:0:9} + D=${D:9} + while [[ -n $D ]]; do + mod=$(( N % 97 )) + N=$(printf "%02d%s" $mod ${D:0:7}) + D=${D:7} + done + echo $(( N % 97 )) +} + +for test in "GB82 WEST 1234 5698 7654 32" "GB42 WEST 1234 5698 7654 32"; do + printf "%s : " "$test" + is_iban "$test" && echo yes || echo no +done diff --git a/Task/Integer-overflow/00DESCRIPTION b/Task/Integer-overflow/00DESCRIPTION new file mode 100644 index 0000000000..62e7b53f97 --- /dev/null +++ b/Task/Integer-overflow/00DESCRIPTION @@ -0,0 +1,95 @@ +Some languages support one or more integer types of the underlying processor. +This integer types have fixed size. Usually 8-bit, 16-bit, 32-bit or 64-bit. +The integers supported by such a type can be signed or unsigned. +Arithmetic for machine level integers can often be done by single CPU instructions. +This allows high performance and is the main reason to support machine level integers. + +An integer overflow happens when the result of a computation does not fit into the fixed size integer. +The result can be too small or too big to be representable in the fixed size integer. + +When a language has fixed size integer types, the task is to write a program that +does arithmetic computations for the fixed size integers of the language. +These computations must be done such that the result would overflow. +The program should demonstrate what the following expressions do. +For 32-bit signed integers: +{|class="wikitable" +!Expression +!Result that does not fit into a 32-bit signed integer +|- +| -(-2147483647-1) +| 2147483648 +|- +| 2000000000 + 2000000000 +| 4000000000 +|- +| -2147483647 - 2147483647 +| -4294967294 +|- +| 46341 * 46341 +| 2147488281 +|- +| (-2147483647-1) / -1 +| 2147483648 +|} +For 64-bit signed integers: +{|class="wikitable" +!Expression +!Result that does not fit into a 64-bit signed integer +|- +| -(-9223372036854775807-1) +| 9223372036854775808 +|- +| 5000000000000000000+5000000000000000000 +| 10000000000000000000 +|- +| -9223372036854775807 - 9223372036854775807 +| -18446744073709551614 +|- +| 3037000500 * 3037000500 +| 9223372037000250000 +|- +| (-9223372036854775807-1) / -1 +| 9223372036854775808 +|} +For 32-bit unsigned integers: +{|class="wikitable" +!Expression +!Result that does not fit into a 32-bit unsigned integer +|- +| -4294967295 +| -4294967295 +|- +| 3000000000 + 3000000000 +| 6000000000 +|- +| 2147483647 - 4294967295 +| -2147483648 +|- +| 65537 * 65537 +| 4295098369 +|} +For 64-bit unsigned integers: +{|class="wikitable" +!Expression +!Result that does not fit into a 64-bit unsigned integer +|- +| -18446744073709551615 +| -18446744073709551615 +|- +| 10000000000000000000 + 10000000000000000000 +| 20000000000000000000 +|- +| 9223372036854775807 - 18446744073709551615 +| -9223372036854775808 +|- +| 4294967296 * 4294967296 +| 18446744073709551616 +|} +When the integer overflow does trigger an exception show how the exception is catched. +When the integer overflow produces some value print it. +It should be explicitly noted when an integer overflow is not recognized and the program continues with wrong results. +This should be done for signed and unsigned integers of various sizes supported by the language. +When a language has no fixed size integer type or when no integer overflow can occur +for other reasons this should be noted. +It is okay to mention, when a language supports unlimited precision integers, but +this task is NOT the place to demonstrate the capabilities of unlimited precision integers. diff --git a/Task/Integer-overflow/Ada/integer-overflow.ada b/Task/Integer-overflow/Ada/integer-overflow.ada new file mode 100644 index 0000000000..37122cca83 --- /dev/null +++ b/Task/Integer-overflow/Ada/integer-overflow.ada @@ -0,0 +1,51 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Overflow is + + generic + type T is Range <>; + Name_Of_T: String; + procedure Print_Bounds; -- first instantiate this with T, Name + -- then call the instantiation + procedure Print_Bounds is + begin + Put_Line(" " & Name_Of_T & " " & T'Image(T'First) + & " .." & T'Image(T'Last)); + end Print_Bounds; + + procedure P_Int is new Print_Bounds(Integer, "Integer "); + procedure P_Nat is new Print_Bounds(Natural, "Natural "); + procedure P_Pos is new Print_Bounds(Positive, "Positive"); + procedure P_Long is new Print_Bounds(Long_Integer, "Long "); + + type Unsigned_Byte is range 0 .. 255; + type Signed_Byte is range -128 .. 127; + type Unsigned_Word is range 0 .. 2**32-1; + type Thousand is range 0 .. 999; + type Signed_Double is range - 2**63 .. 2**63-1; + type Crazy is range -11 .. -3; + + procedure P_UB is new Print_Bounds(Unsigned_Byte, "U 8 "); + procedure P_SB is new Print_Bounds(Signed_Byte, "S 8 "); + procedure P_UW is new Print_Bounds(Unsigned_Word, "U 32 "); + procedure P_Th is new Print_Bounds(Thousand, "Thous"); + procedure P_SD is new Print_Bounds(Signed_Double, "S 64 "); + procedure P_Cr is new Print_Bounds(Crazy, "Crazy"); + + A: Crazy := Crazy'First; + +begin + Put_Line("Predefined Types:"); + P_Int; P_Nat; P_Pos; P_Long; + New_Line; + + Put_Line("Types defined by the user:"); + P_UB; P_SB; P_UW; P_Th; P_SD; P_Cr; + New_Line; + + Put_Line("Forcing a variable to overflow:"); + loop -- endless loop + Put(" " & Crazy'Image(A) & "+1"); + A := A + 1; + end loop; +end Overflow; diff --git a/Task/Integer-overflow/AutoHotkey/integer-overflow.ahk b/Task/Integer-overflow/AutoHotkey/integer-overflow.ahk new file mode 100644 index 0000000000..ffb70c1fc6 --- /dev/null +++ b/Task/Integer-overflow/AutoHotkey/integer-overflow.ahk @@ -0,0 +1 @@ +Msgbox, % "Testing signed 64-bit integer overflow with AutoHotkey:`n" -(-9223372036854775807-1) "`n" 5000000000000000000+5000000000000000000 "`n" -9223372036854775807-9223372036854775807 "`n" 3037000500*3037000500 "`n" (-9223372036854775807-1)//-1 diff --git a/Task/Integer-overflow/C/integer-overflow.c b/Task/Integer-overflow/C/integer-overflow.c new file mode 100644 index 0000000000..e8429e44dc --- /dev/null +++ b/Task/Integer-overflow/C/integer-overflow.c @@ -0,0 +1,28 @@ +#include + +int main (int argc, char *argv[]) +{ + printf("Signed 32-bit:\n"); + printf("%d\n", -(-2147483647-1)); + printf("%d\n", 2000000000 + 2000000000); + printf("%d\n", -2147483647 - 2147483647); + printf("%d\n", 46341 * 46341); + printf("%d\n", (-2147483647-1) / -1); + printf("Signed 64-bit:\n"); + printf("%ld\n", -(-9223372036854775807-1)); + printf("%ld\n", 5000000000000000000+5000000000000000000); + printf("%ld\n", -9223372036854775807 - 9223372036854775807); + printf("%ld\n", 3037000500 * 3037000500); + printf("%ld\n", (-9223372036854775807-1) / -1); + printf("Unsigned 32-bit:\n"); + printf("%u\n", -4294967295U); + printf("%u\n", 3000000000U + 3000000000U); + printf("%u\n", 2147483647U - 4294967295U); + printf("%u\n", 65537U * 65537U); + printf("Unsigned 64-bit:\n"); + printf("%lu\n", -18446744073709551615LU); + printf("%lu\n", 10000000000000000000LU + 10000000000000000000LU); + printf("%lu\n", 9223372036854775807LU - 18446744073709551615LU); + printf("%lu\n", 4294967296LU * 4294967296LU); + return 0; +} diff --git a/Task/Integer-overflow/Clojure/integer-overflow-1.clj b/Task/Integer-overflow/Clojure/integer-overflow-1.clj new file mode 100644 index 0000000000..9f62f8fb02 --- /dev/null +++ b/Task/Integer-overflow/Clojure/integer-overflow-1.clj @@ -0,0 +1,4 @@ +(* -1 (dec -9223372036854775807)) +(+ 5000000000000000000 5000000000000000000) +(- -9223372036854775807 9223372036854775807) +(* 3037000500 3037000500) diff --git a/Task/Integer-overflow/Clojure/integer-overflow-2.clj b/Task/Integer-overflow/Clojure/integer-overflow-2.clj new file mode 100644 index 0000000000..1ef959676d --- /dev/null +++ b/Task/Integer-overflow/Clojure/integer-overflow-2.clj @@ -0,0 +1,8 @@ +(set! *unchecked-math* true) +(* -1 (dec -9223372036854775807)) ;=> -9223372036854775808 +(+ 5000000000000000000 5000000000000000000) ;=> -8446744073709551616 +(- -9223372036854775807 9223372036854775807) ;=> 2 +(* 3037000500 3037000500) ;=> -9223372036709301616 +; Note: The following division will currently silently overflow regardless of *unchecked-math* +; See: http://dev.clojure.org/jira/browse/CLJ-1253 +(/ (dec -9223372036854775807) -1) ;=> -9223372036854775808 diff --git a/Task/Integer-overflow/D/integer-overflow.d b/Task/Integer-overflow/D/integer-overflow.d new file mode 100644 index 0000000000..b0e0dffae1 --- /dev/null +++ b/Task/Integer-overflow/D/integer-overflow.d @@ -0,0 +1,37 @@ +void main() @safe { + import std.stdio; + + writeln("Signed 32-bit:"); + writeln(-(-2_147_483_647 - 1)); + writeln(2_000_000_000 + 2_000_000_000); + writeln(-2147483647 - 2147483647); + writeln(46_341 * 46_341); + writeln((-2_147_483_647 - 1) / -1); + + writeln("\nSigned 64-bit:"); + writeln(-(-9_223_372_036_854_775_807 - 1)); + writeln(5_000_000_000_000_000_000 + 5_000_000_000_000_000_000); + writeln(-9_223_372_036_854_775_807 - 9_223_372_036_854_775_807); + writeln(3_037_000_500 * 3_037_000_500); + writeln((-9_223_372_036_854_775_807 - 1) / -1); + + writeln("\nUnsigned 32-bit:"); + writeln(-4_294_967_295U); + writeln(3_000_000_000U + 3_000_000_000U); + writeln(2_147_483_647U - 4_294_967_295U); + writeln(65_537U * 65_537U); + + writeln("\nUnsigned 64-bit:"); + writeln(-18_446_744_073_709_551_615UL); + writeln(10_000_000_000_000_000_000UL + 10_000_000_000_000_000_000UL); + writeln(9_223_372_036_854_775_807UL - 18_446_744_073_709_551_615UL); + writeln(4_294_967_296UL * 4_294_967_296UL); + + import core.checkedint; + bool overflow = false; + // Checked signed multiplication. + // Eventually such functions will be recognized by D compilers + // and they will be implemented with efficient intrinsics. + immutable r = muls(46_341, 46_341, overflow); + writeln("\n", r, " ", overflow); +} diff --git a/Task/Integer-overflow/Go/integer-overflow.go b/Task/Integer-overflow/Go/integer-overflow.go new file mode 100644 index 0000000000..0beb5da9a1 --- /dev/null +++ b/Task/Integer-overflow/Go/integer-overflow.go @@ -0,0 +1,108 @@ +package main + +import "fmt" + +func main() { + // Go's builtin integer types are: + // int, int8, int16, int32, int64 + // uint, uint8, uint16, uint32, uint64 + // byte, rune, uintptr + // + // int is either 32 or 64 bit, depending on the system + // uintptr is large enough to hold the bit pattern of any pointer + // byte is 8 bits like int8 + // rune is 32 bits like int32 + // + // Overflow and underflow is silent. The math package defines a number + // of constants that can be helpfull, e.g.: + // math.MaxInt64 = 1<<63 - 1 + // math.MinInt64 = -1 << 63 + // math.MaxUint64 = 1<<64 - 1 + // + // The math/big package implements multi-precision + // arithmetic (big numbers). + // + // In all cases assignment from one type to another requires + // an explicit cast, even if the types are otherwise identical + // (e.g. rune and int32 or int and either int32 or int64). + // Casts silently truncate if required. + // + // Invalid: + // var i int = int32(0) + // var r rune = int32(0) + // var b byte = int8(0) + // + // Valid: + var i64 int64 = 42 + var i32 int32 = int32(i64) + var i16 int16 = int16(i64) + var i8 int8 = int8(i16) + var i int = int(i8) + var r rune = rune(i) + var b byte = byte(r) + var u64 uint64 = uint64(b) + var u32 uint32 + + //const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit + const c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped + i64 = c + //i32 = c // Compiler error + //i32 = -(-2147483647 - 1) // Compiler error + i32 = -2147483647 + i32 = -(-i32 - 1) + fmt.Println("32 bit signed integers") + fmt.Printf(" -(-2147483647 - 1) = %d, got %d\n", i64, i32) + + i64 = 2000000000 + 2000000000 + //i32 = 2000000000 + 2000000000 // Compiler error + i32 = 2000000000 + i32 = i32 + i32 + fmt.Printf(" 2000000000 + 2000000000 = %d, got %d\n", i64, i32) + i64 = -2147483647 - 2147483647 + i32 = 2147483647 + i32 = -i32 - i32 + fmt.Printf(" -2147483647 - 2147483647 = %d, got %d\n", i64, i32) + i64 = 46341 * 46341 + i32 = 46341 + i32 = i32 * i32 + fmt.Printf(" 46341 * 46341 = %d, got %d\n", i64, i32) + i64 = (-2147483647 - 1) / -1 + i32 = -2147483647 + i32 = (i32 - 1) / -1 + fmt.Printf(" (-2147483647-1) / -1 = %d, got %d\n", i64, i32) + + fmt.Println("\n64 bit signed integers") + i64 = -9223372036854775807 + fmt.Printf(" -(%d - 1): %d\n", i64, -(i64 - 1)) + i64 = 5000000000000000000 + fmt.Printf(" %d + %d: %d\n", i64, i64, i64+i64) + i64 = 9223372036854775807 + fmt.Printf(" -%d - %d: %d\n", i64, i64, -i64-i64) + i64 = 3037000500 + fmt.Printf(" %d * %d: %d\n", i64, i64, i64*i64) + i64 = -9223372036854775807 + fmt.Printf(" (%d - 1) / -1: %d\n", i64, (i64-1)/-1) + + fmt.Println("\n32 bit unsigned integers:") + //u32 = -4294967295 // Compiler error + u32 = 4294967295 + fmt.Printf(" -%d: %d\n", u32, -u32) + u32 = 3000000000 + fmt.Printf(" %d + %d: %d\n", u32, u32, u32+u32) + a := uint32(2147483647) + u32 = 4294967295 + fmt.Printf(" %d - %d: %d\n", a, u32, a-u32) + u32 = 65537 + fmt.Printf(" %d * %d: %d\n", u32, u32, u32*u32) + + fmt.Println("\n64 bit unsigned integers:") + u64 = 18446744073709551615 + fmt.Printf(" -%d: %d\n", u64, -u64) + u64 = 10000000000000000000 + fmt.Printf(" %d + %d: %d\n", u64, u64, u64+u64) + aa := uint64(9223372036854775807) + u64 = 18446744073709551615 + fmt.Printf(" %d - %d: %d\n", aa, u64, aa-u64) + u64 = 4294967296 + fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64) +} diff --git a/Task/Integer-overflow/Haskell/integer-overflow.hs b/Task/Integer-overflow/Haskell/integer-overflow.hs new file mode 100644 index 0000000000..f8b2c4d32d --- /dev/null +++ b/Task/Integer-overflow/Haskell/integer-overflow.hs @@ -0,0 +1,26 @@ +import Data.Int +import Data.Word +import Control.Exception + +f x = do + catch (print x) (\e -> print (e :: ArithException)) + +main = do + f ((- (-2147483647 - 1)) :: Int32) + f ((2000000000 + 2000000000) :: Int32) + f (((-2147483647) - 2147483647) :: Int32) + f ((46341 * 46341) :: Int32) + f ((((-2147483647) - 1) `div` (-1)) :: Int32) + f ((- ((-9223372036854775807) - 1)) :: Int64) + f ((5000000000000000000 + 5000000000000000000) :: Int64) + f (((-9223372036854775807) - 9223372036854775807) :: Int64) + f ((3037000500 * 3037000500) :: Int64) + f ((((-9223372036854775807) - 1) `div` (-1)) :: Int64) + f ((-4294967295) :: Word32) + f ((3000000000 + 3000000000) :: Word32) + f ((2147483647 - 4294967295) :: Word32) + f ((65537 * 65537) :: Word32) + f ((-18446744073709551615) :: Word64) + f ((10000000000000000000 + 10000000000000000000) :: Word64) + f ((9223372036854775807 - 18446744073709551615) :: Word64) + f ((4294967296 * 4294967296) :: Word64) diff --git a/Task/Integer-overflow/J/integer-overflow-1.j b/Task/Integer-overflow/J/integer-overflow-1.j new file mode 100644 index 0000000000..f1924d60ad --- /dev/null +++ b/Task/Integer-overflow/J/integer-overflow-1.j @@ -0,0 +1,39 @@ + -(_2147483647-1) +2.14748e9 + 2000000000 + 2000000000 +4e9 + _2147483647 - 2147483647 +_4.29497e9 + 46341 * 46341 +2.14749e9 + (_2147483647-1) % -1 +2.14748e9 + + -(_9223372036854775807-1) +9.22337e18 + 5000000000000000000+5000000000000000000 +1e19 + _9223372036854775807 - 9223372036854775807 +_1.84467e19 + 3037000500 * 3037000500 +9.22337e18 + (_9223372036854775807-1) % -1 +9.22337e18 + + _4294967295 +_4.29497e9 + 3000000000 + 3000000000 +6e9 + 2147483647 - 4294967295 +_2.14748e9 + 65537 * 65537 +4.2951e9 + + _18446744073709551615 +_1.84467e19 + 10000000000000000000 + 10000000000000000000 +2e19 + 9223372036854775807 - 18446744073709551615 +_9.22337e18 + 4294967296 * 4294967296 +1.84467e19 diff --git a/Task/Integer-overflow/J/integer-overflow-2.j b/Task/Integer-overflow/J/integer-overflow-2.j new file mode 100644 index 0000000000..7e4106b45a --- /dev/null +++ b/Task/Integer-overflow/J/integer-overflow-2.j @@ -0,0 +1,39 @@ + -(_2147483647-1) +2147483648 + 2000000000 + 2000000000 +4000000000 + _2147483647 - 2147483647 +_4294967294 + 46341 * 46341 +2147488281 + (_2147483647-1) % -1 +2.14748e9 + + -(_9223372036854775807-1) +9.22337e18 + 5000000000000000000+5000000000000000000 +1e19 + _9223372036854775807 - 9223372036854775807 +_1.84467e19 + 3037000500 * 3037000500 +9.22337e18 + (_9223372036854775807-1) % -1 +9.22337e18 + + _4294967295 +_4294967295 + 3000000000 + 3000000000 +6000000000 + 2147483647 - 4294967295 +_2147483648 + 65537 * 65537 +4295098369 + + _18446744073709551615 +_1.84467e19 + 10000000000000000000 + 10000000000000000000 +2e19 + 9223372036854775807 - 18446744073709551615 +_9.22337e18 + 4294967296 * 4294967296 +1.84467e19 diff --git a/Task/Integer-overflow/J/integer-overflow-3.j b/Task/Integer-overflow/J/integer-overflow-3.j new file mode 100644 index 0000000000..8b2cf6c63b --- /dev/null +++ b/Task/Integer-overflow/J/integer-overflow-3.j @@ -0,0 +1,39 @@ + -(_2147483647-1) +2147483648 + 2000000000 + 2000000000 +4000000000 + _2147483647 - 2147483647 +_4294967294 + 46341 * 46341 +2147488281 + (_2147483647-1) % -1 +2147483648 + + -(_9223372036854775807-1) +9223372036854775800 + 5000000000000000000+5000000000000000000 +10000000000000000000 + _9223372036854775807 - 9223372036854775807 +_18446744073709552000 + 3037000500 * 3037000500 +9223372037000249300 + (_9223372036854775807-1) % -1 +9223372036854775800 + + _4294967295 +_4294967295 + 3000000000 + 3000000000 +6000000000 + 2147483647 - 4294967295 +_2147483648 + 65537 * 65537 +4295098369 + + _18446744073709551615 +_18446744073709552000 + 10000000000000000000 + 10000000000000000000 +20000000000000000000 + 9223372036854775807 - 18446744073709551615 +_9223372036854775800 + 4294967296 * 4294967296 +18446744073709552000 diff --git a/Task/Integer-overflow/J/integer-overflow-4.j b/Task/Integer-overflow/J/integer-overflow-4.j new file mode 100644 index 0000000000..8b2cf6c63b --- /dev/null +++ b/Task/Integer-overflow/J/integer-overflow-4.j @@ -0,0 +1,39 @@ + -(_2147483647-1) +2147483648 + 2000000000 + 2000000000 +4000000000 + _2147483647 - 2147483647 +_4294967294 + 46341 * 46341 +2147488281 + (_2147483647-1) % -1 +2147483648 + + -(_9223372036854775807-1) +9223372036854775800 + 5000000000000000000+5000000000000000000 +10000000000000000000 + _9223372036854775807 - 9223372036854775807 +_18446744073709552000 + 3037000500 * 3037000500 +9223372037000249300 + (_9223372036854775807-1) % -1 +9223372036854775800 + + _4294967295 +_4294967295 + 3000000000 + 3000000000 +6000000000 + 2147483647 - 4294967295 +_2147483648 + 65537 * 65537 +4295098369 + + _18446744073709551615 +_18446744073709552000 + 10000000000000000000 + 10000000000000000000 +20000000000000000000 + 9223372036854775807 - 18446744073709551615 +_9223372036854775800 + 4294967296 * 4294967296 +18446744073709552000 diff --git a/Task/Integer-overflow/Java/integer-overflow.java b/Task/Integer-overflow/Java/integer-overflow.java new file mode 100644 index 0000000000..b89c0096d8 --- /dev/null +++ b/Task/Integer-overflow/Java/integer-overflow.java @@ -0,0 +1,18 @@ +public class integerOverflow { + + public static void main(String[] args) { + System.out.println("Signed 32-bit:"); + System.out.println(-(-2147483647-1)); + System.out.println(2000000000 + 2000000000); + System.out.println(-2147483647 - 2147483647); + System.out.println(46341 * 46341); + System.out.println((-2147483647-1) / -1); + System.out.println("Signed 64-bit:"); + System.out.println(-(-9223372036854775807L-1)); + System.out.println(5000000000000000000L+5000000000000000000L); + System.out.println(-9223372036854775807L - 9223372036854775807L); + System.out.println(3037000500L * 3037000500L); + System.out.println((-9223372036854775807L-1) / -1); + } + +} diff --git a/Task/Integer-overflow/Perl/integer-overflow.pl b/Task/Integer-overflow/Perl/integer-overflow.pl new file mode 100644 index 0000000000..5e21ebdf82 --- /dev/null +++ b/Task/Integer-overflow/Perl/integer-overflow.pl @@ -0,0 +1,11 @@ +use strict; +use warnings; +use integer; +use feature 'say'; + +say("Testing 64-bit signed overflow:"); +say(-(-9223372036854775807-1)); +say(5000000000000000000+5000000000000000000); +say(-9223372036854775807 - 9223372036854775807); +say(3037000500 * 3037000500); +say((-9223372036854775807-1) / -1); diff --git a/Task/Integer-overflow/Python/integer-overflow-1.py b/Task/Integer-overflow/Python/integer-overflow-1.py new file mode 100644 index 0000000000..b31607a136 --- /dev/null +++ b/Task/Integer-overflow/Python/integer-overflow-1.py @@ -0,0 +1,18 @@ +Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 +Type "copyright", "credits" or "license()" for more information. +>>> for calc in ''' -(-2147483647-1) + 2000000000 + 2000000000 + -2147483647 - 2147483647 + 46341 * 46341 + (-2147483647-1) / -1'''.split('\n'): + ans = eval(calc) + print('Expression: %r evaluates to %s of type %s' + % (calc.strip(), ans, type(ans))) + + +Expression: '-(-2147483647-1)' evaluates to 2147483648 of type +Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type +Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type +Expression: '46341 * 46341' evaluates to 2147488281 of type +Expression: '(-2147483647-1) / -1' evaluates to 2147483648 of type +>>> diff --git a/Task/Integer-overflow/Python/integer-overflow-2.py b/Task/Integer-overflow/Python/integer-overflow-2.py new file mode 100644 index 0000000000..ce1671d160 --- /dev/null +++ b/Task/Integer-overflow/Python/integer-overflow-2.py @@ -0,0 +1,18 @@ +Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32 +Type "copyright", "credits" or "license()" for more information. +>>> for calc in ''' -(-2147483647-1) + 2000000000 + 2000000000 + -2147483647 - 2147483647 + 46341 * 46341 + (-2147483647-1) / -1'''.split('\n'): + ans = eval(calc) + print('Expression: %r evaluates to %s of type %s' + % (calc.strip(), ans, type(ans))) + + +Expression: '-(-2147483647-1)' evaluates to 2147483648 of type +Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type +Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type +Expression: '46341 * 46341' evaluates to 2147488281 of type +Expression: '(-2147483647-1) / -1' evaluates to 2147483648.0 of type +>>> diff --git a/Task/Integer-overflow/README b/Task/Integer-overflow/README new file mode 100644 index 0000000000..b17c9bc040 --- /dev/null +++ b/Task/Integer-overflow/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Integer_overflow diff --git a/Task/Integer-overflow/REXX/integer-overflow.rexx b/Task/Integer-overflow/REXX/integer-overflow.rexx new file mode 100644 index 0000000000..32d26f9868 --- /dev/null +++ b/Task/Integer-overflow/REXX/integer-overflow.rexx @@ -0,0 +1,16 @@ +/*REXX pgm displays values when integers have an overflow or underflow.*/ +numeric digits 9 /*default is nine decimal digits.*/ +call showResult( 999999997 + 1 ) +call showResult( 999999998 + 1 ) +call showResult( 999999999 + 1 ) +call showResult( -999999998 - 2 ) +call showResult( 40000 * 25000 ) +call showResult( -50000 * 20000 ) +call showResult( 50000 *-30000 ) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOWRESULT subroutine───────────────*/ +showResult: procedure; parse arg x,,_; x=x/1 /*normalize X. */ +if pos('E',x)\==0 then if x>0 then _=' [overflow]' /*did it ↑flow?*/ + else _=' [underflow]' /*did it ↓flow?*/ +say right(x,20) _ /*show result. */ +return x /*return value.*/ diff --git a/Task/Integer-overflow/Ruby/integer-overflow.rb b/Task/Integer-overflow/Ruby/integer-overflow.rb new file mode 100644 index 0000000000..3671f19ded --- /dev/null +++ b/Task/Integer-overflow/Ruby/integer-overflow.rb @@ -0,0 +1,8 @@ +2.1.1 :001 > a = 2**62 -1 + => 4611686018427387903 +2.1.1 :002 > a.class + => Fixnum +2.1.1 :003 > (b = a + 1).class + => Bignum +2.1.1 :004 > (b-1).class + => Fixnum diff --git a/Task/Integer-overflow/Scala/integer-overflow.scala b/Task/Integer-overflow/Scala/integer-overflow.scala new file mode 100644 index 0000000000..e1db2ed216 --- /dev/null +++ b/Task/Integer-overflow/Scala/integer-overflow.scala @@ -0,0 +1,14 @@ +import Math.{addExact => ++, multiplyExact => **, negateExact => ~~, subtractExact => --} + +def requireOverflow(f: => Unit) = + try {f; println("Undetected overflow")} catch{case e: Exception => /* caught */} + +println("Testing overflow detection for 32-bit unsigned integers") +requireOverflow(~~(--(~~(2147483647), 1))) // -(-2147483647-1) +requireOverflow(++(2000000000, 2000000000)) // 2000000000 + 2000000000 +requireOverflow(--(~~(2147483647), 2147483647)) // -2147483647 + 2147483647 +requireOverflow(**(46341, 46341)) // 46341 * 46341 +requireOverflow(**(--(~~(2147483647),1), -1)) // same as (-2147483647-1) / -1 + +println("Test - Expect Undetected overflow:") +requireOverflow(++(1,1)) // Undetected overflow diff --git a/Task/Integer-overflow/Seed7/integer-overflow.seed7 b/Task/Integer-overflow/Seed7/integer-overflow.seed7 new file mode 100644 index 0000000000..244647dca9 --- /dev/null +++ b/Task/Integer-overflow/Seed7/integer-overflow.seed7 @@ -0,0 +1,19 @@ +$ include "seed7_05.s7i"; + +const proc: writeResult (ref func integer: expression) is func + begin + block + writeln(expression); + exception + catch OVERFLOW_ERROR: writeln("OVERFLOW_ERROR"); + end block; + end func; + +const proc: main is func + begin + writeResult(-(-9223372036854775807-1)); + writeResult(5000000000000000000+5000000000000000000); + writeResult(-9223372036854775807 - 9223372036854775807); + writeResult(3037000500 * 3037000500); + writeResult((-9223372036854775807-1) div -1); + end func; diff --git a/Task/Integer-overflow/Tcl/integer-overflow.tcl b/Task/Integer-overflow/Tcl/integer-overflow.tcl new file mode 100644 index 0000000000..4efcc2ccfb --- /dev/null +++ b/Task/Integer-overflow/Tcl/integer-overflow.tcl @@ -0,0 +1,4 @@ +proc tcl::mathfunc::clamp32 {x} { + expr {$x<0 ? -((-$x) & 0x7fffffff) : $x & 0x7fffffff} +} +puts [expr { clamp32(2000000000 + 2000000000) }]; # ==> 1852516352 diff --git a/Task/Iterated-digits-squaring/00DESCRIPTION b/Task/Iterated-digits-squaring/00DESCRIPTION new file mode 100644 index 0000000000..0d4a18fa35 --- /dev/null +++ b/Task/Iterated-digits-squaring/00DESCRIPTION @@ -0,0 +1,23 @@ +If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: +
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
+7 -> 49 -> 97 -> 130 -> 10 -> 1
+An example in Python: + +>>> step = lambda x: sum(int(d) ** 2 for d in str(x)) +>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) +>>> [iterate(x) for x in xrange(1, 20)] +[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] + +;Task: +: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. +Or, for much less credit - (showing that your algorithm and/or language is slow): +: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. + +This problem derives from the [https://projecteuler.net/problem=92 Project Euler problem 92]. + +For a quick algorithm for this task see [[Talk:Iterated_digits_squaring|the talk page]] + +;Cf: +*[[Combinations with repetitions]] +*[[Digital root]] +*[[Digital root/Multiplicative digital root]] diff --git a/Task/Iterated-digits-squaring/C++/iterated-digits-squaring.cpp b/Task/Iterated-digits-squaring/C++/iterated-digits-squaring.cpp new file mode 100644 index 0000000000..fc38556ae4 --- /dev/null +++ b/Task/Iterated-digits-squaring/C++/iterated-digits-squaring.cpp @@ -0,0 +1,37 @@ +#include + +// returns sum of squares of digits of n +unsigned int sum_square_digits(unsigned int n) { + int i,num=n,sum=0; + // process digits one at a time until there are none left + while (num > 0) { + // peal off the last digit from the number + int digit=num % 10; + num=(num - digit)/10; + // add it's square to the sum + sum+=digit*digit; + } + return sum; +} +int main(void) { + unsigned int i=0,result=0, count=0; + for (i=1; i<=100000000; i++) { + // if not 1 or 89, start the iteration + if ((i != 1) || (i != 89)) { + result = sum_square_digits(i); + } + // otherwise we're done already + else { + result = i; + } + // while we haven't reached 1 or 89, keep iterating + while ((result != 1) && (result != 89)) { + result = sum_square_digits(result); + } + if (result == 89) { + count++; + } + } + std::cout << count << std::endl; + return 0; +} diff --git a/Task/Iterated-digits-squaring/C/iterated-digits-squaring.c b/Task/Iterated-digits-squaring/C/iterated-digits-squaring.c new file mode 100644 index 0000000000..da09ccda42 --- /dev/null +++ b/Task/Iterated-digits-squaring/C/iterated-digits-squaring.c @@ -0,0 +1,82 @@ +#include + +const int digits[] = { 0,1,2,3,4,5,6,7,8,9 }; + +// calculates factorial of a number +int factorial(int n) { + return n == 0 ? 1 : n * factorial(n - 1); +} + +// returns sum of squares of digits of n +unsigned int sum_square_digits(unsigned int n) { + int i,num=n,sum=0; + // process digits one at a time until there are none left + while (num > 0) { + // peal off the last digit from the number + int digit=num % 10; + num=(num - digit)/10; + // add it's square to the sum + sum=sum+digit*digit; + } + return sum; +} + +// builds all combinations digits 0-9 of length len +// for each of these it will perform iterated digit squaring +// and for those which result in 89 add to a counter which is +// passed by pointer. +long choose_sum_and_count_89(int * got, int n_chosen, int len, int at, int max_types, int *count89) +{ + int i; + long count = 0; + int digitcounts[10]; + for (i=0; i < 10; i++) { + digitcounts[i]=0; + } + if (n_chosen == len) { + if (!got) return 1; + + int sum=0; + for (i = 0; i < len; i++) { + int digit=digits[got[i]]; + digitcounts[digit]++; + sum=sum + digit * digit; + } + if (sum == 0) { + return 1; + } + if ((sum != 1) && (sum != 89)) { + while ((sum != 1) && (sum != 89)) { + sum=sum_square_digits(sum); + } + } + if (sum == 89) { + int count_this_comb=factorial(len); + for (i=0; i<10; i++) { + count_this_comb/=factorial(digitcounts[i]); + } + (*count89)+=count_this_comb; + } + + return 1; + } + + for (i = at; i < max_types; i++) { + if (got) got[n_chosen] = i; + count += choose_sum_and_count_89(got, n_chosen + 1, len, i, max_types, count89); + } + return count; +} + +int main(void) +{ + int chosen[10]; + int count=0; + // build all unique 8 digit combinations which represent + // numbers 0-99,999,999 and count those + // whose iterated digit squaring sum to 89 + // case 0, 100,000,000 are ignored since they don't sum to 89 + choose_sum_and_count_89(chosen, 0, 8, 0, 10, &count); + printf("%d\n",count); + return 0; +} diff --git a/Task/Iterated-digits-squaring/D/iterated-digits-squaring-1.d b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-1.d new file mode 100644 index 0000000000..036fac513c --- /dev/null +++ b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-1.d @@ -0,0 +1,18 @@ +import std.stdio, std.algorithm, std.range, std.functional; + +uint step(uint x) pure nothrow @safe @nogc { + uint total = 0; + while (x) { + total += (x % 10) ^^ 2; + x /= 10; + } + return total; +} + +uint iterate(in uint x) nothrow @safe { + return (x == 89 || x == 1) ? x : x.step.memoize!iterate; +} + +void main() { + iota(1, 100_000_000).filter!(x => x.iterate == 89).count.writeln; +} diff --git a/Task/Iterated-digits-squaring/D/iterated-digits-squaring-2.d b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-2.d new file mode 100644 index 0000000000..b796c5459c --- /dev/null +++ b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-2.d @@ -0,0 +1,41 @@ +void main() nothrow @nogc { + import core.stdc.stdio: printf; + + enum uint magic = 89; + enum uint limit = 100_000_000; + uint[(9 ^^ 2) * 8 + 1] lookup = void; + + uint[10] squares; + foreach (immutable i, ref x; squares) + x = i ^^ 2; + + foreach (immutable uint i; 1 .. lookup.length) { + uint x = i; + + while (x != magic && x != 1) { + uint total = 0; + while (x) { + total += squares[(x % 10)]; + x /= 10; + } + x = total; + } + + lookup[i] = x == magic; + } + + uint magicCount = 0; + foreach (immutable uint i; 1 .. limit) { + uint x = i; + uint total = 0; + + while (x) { + total += squares[(x % 10)]; + x /= 10; + } + + magicCount += lookup[total]; + } + + printf("%u\n", magicCount); +} diff --git a/Task/Iterated-digits-squaring/D/iterated-digits-squaring-3.d b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-3.d new file mode 100644 index 0000000000..a5a76f6727 --- /dev/null +++ b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-3.d @@ -0,0 +1,74 @@ +import core.stdc.stdio, std.algorithm, std.range; + +enum factorial = (in uint n) pure nothrow @safe @nogc + => reduce!q{a * b}(1u, iota(1u, n + 1)); + +uint iLog10(in uint x) pure nothrow @safe @nogc +in { + assert(x > 0); +} body { + return (x >= 1_000_000_000) ? 9 : + (x >= 100_000_000) ? 8 : + (x >= 10_000_000) ? 7 : + (x >= 1_000_000) ? 6 : + (x >= 100_000) ? 5 : + (x >= 10_000) ? 4 : + (x >= 1_000) ? 3 : + (x >= 100) ? 2 : + (x >= 10) ? 1 : 0; +} + +uint nextStep(uint x) pure nothrow @safe @nogc { + typeof(return) result = 0; + + while (x > 0) { + result += (x % 10) ^^ 2; + x /= 10; + } + return result; +} + +uint check(in uint[] number) pure nothrow @safe @nogc { + uint candidate = reduce!((tot, n) => tot * 10 + n)(0, number); + + while (candidate != 89 && candidate != 1) + candidate = candidate.nextStep; + + if (candidate == 89) { + uint[10] digitsCount; + foreach (immutable d; number) + digitsCount[d]++; + + return reduce!((r, c) => r / c.factorial) + (number.length.factorial, digitsCount); + } + + return 0; +} + +void main() nothrow @nogc { + enum uint limit = 100_000_000; + immutable uint cacheSize = limit.iLog10; + + uint[cacheSize] number; + uint result = 0; + uint i = cacheSize - 1; + + while (true) { + if (i == 0 && number[i] == 9) + break; + if (i == cacheSize - 1 && number[i] < 9) { + number[i]++; + result += number.check; + } else if (number[i] == 9) { + i--; + } else { + number[i]++; + number[i + 1 .. $] = number[i]; + i = cacheSize - 1; + result += number.check; + } + } + + printf("%u\n", result); +} diff --git a/Task/Iterated-digits-squaring/D/iterated-digits-squaring-4.d b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-4.d new file mode 100644 index 0000000000..5afac8e06c --- /dev/null +++ b/Task/Iterated-digits-squaring/D/iterated-digits-squaring-4.d @@ -0,0 +1,60 @@ +import std.stdio, std.typecons, std.traits, std.typetuple, std.range, std.algorithm; + +auto divMod(T)(T x, T y) pure nothrow @safe @nogc { + return tuple(x / y, x % y); +} + +auto expand(alias F, B)(B x) pure nothrow @safe @nogc +if (isCallable!F && + is(ParameterTypeTuple!F == TypeTuple!B) + && __traits(isSame, TemplateOf!(ReturnType!F), Nullable) + && isTuple!(TemplateArgsOf!(ReturnType!F)[0]) + && is(TemplateArgsOf!(TemplateArgsOf!(ReturnType!F)[0])[1] == B)) { + + alias NAB = ReturnType!F; + alias AB = TemplateArgsOf!NAB[0]; + alias A = AB.Types[0]; + + struct Expand { + bool first; + NAB last; + + @property bool empty() pure nothrow @safe @nogc { + if (first) { + first = false; + popFront; + } + return last.isNull; + } + + @property A front() pure nothrow @safe @nogc { + if (first) { + first = false; + popFront; + } + return last.get[0]; + } + + void popFront() pure nothrow @safe @nogc { last = F(last.get[1]); } + } + + return Expand(true, NAB(AB(A.init, x))); +} + +//------------------------------------------------ + +uint step(uint x) pure nothrow @safe @nogc { + Nullable!(Tuple!(uint, uint)) f(uint n) pure nothrow @safe @nogc { + return (n == 0) ? typeof(return)() : typeof(return)(divMod(n, 10u).reverse); + } + + return expand!f(x).map!(x => x ^^ 2).sum; +} + +uint iter(uint x) pure nothrow @nogc { + return x.recurrence!((a, n) => step(a[n - 1])).filter!(y => y.among!(1, 89)).front; +} + +void main() { + iota(1u, 100_000u).filter!(n => n.iter == 89).count.writeln; +} diff --git a/Task/Iterated-digits-squaring/Go/iterated-digits-squaring.go b/Task/Iterated-digits-squaring/Go/iterated-digits-squaring.go new file mode 100644 index 0000000000..d54f30a339 --- /dev/null +++ b/Task/Iterated-digits-squaring/Go/iterated-digits-squaring.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" +) + +func main() { + var d, n, o, u, u89 int64 + + for n = 1; n < 100000000; n++ { + o = n + for { + u = 0 + for { + d = o%10 + o = (o - d) / 10 + u += d*d + if o == 0 { + break + } + } + if u == 89 || u == 1 { + if u == 89 { u89++ } + break + } + o = u + } + } + fmt.Println(u89) +} diff --git a/Task/Iterated-digits-squaring/Haskell/iterated-digits-squaring.hs b/Task/Iterated-digits-squaring/Haskell/iterated-digits-squaring.hs new file mode 100644 index 0000000000..78d2321ba4 --- /dev/null +++ b/Task/Iterated-digits-squaring/Haskell/iterated-digits-squaring.hs @@ -0,0 +1,13 @@ +import Data.List (unfoldr) +import Data.Tuple (swap) + +step :: Int -> Int +step = sum . map (^ 2) . unfoldr f where + f 0 = Nothing + f n = Just . swap $ n `divMod` 10 + +iter :: Int -> Int +iter = head . filter (`elem` [1, 89]) . iterate step + +main = do + print $ length $ filter ((== 89) . iter) [1 .. 99999999] diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-1.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-1.j new file mode 100644 index 0000000000..ca8215cefa --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-1.j @@ -0,0 +1 @@ +digits=: 10&#.inv diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-2.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-2.j new file mode 100644 index 0000000000..5c015b81b2 --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-2.j @@ -0,0 +1 @@ +sumdigsq=: +/"1@:*:@digits diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-3.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-3.j new file mode 100644 index 0000000000..39ebbe8328 --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-3.j @@ -0,0 +1,2 @@ + sumdigsq^:(i.16) 15 +15 26 40 16 37 58 89 145 42 20 4 16 37 58 89 145 diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-4.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-4.j new file mode 100644 index 0000000000..1a98f8bb48 --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-4.j @@ -0,0 +1 @@ +itdigsq4=:4 = sumdigsq^:(0=e.&4)^:_"0 diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-5.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-5.j new file mode 100644 index 0000000000..d672a830ec --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-5.j @@ -0,0 +1,2 @@ + sumdigsq 99999999 +648 diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j new file mode 100644 index 0000000000..4738c94f6c --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j @@ -0,0 +1 @@ +digsq1e8=:(I.itdigsq1 i.649) e.~ sumdigsq diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-7.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-7.j new file mode 100644 index 0000000000..c65e414209 --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-7.j @@ -0,0 +1,2 @@ + +/+/@:-.@digsq1e8"1(1+i.100 1e6) +85744333 diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-8.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-8.j new file mode 100644 index 0000000000..96b4609f11 --- /dev/null +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-8.j @@ -0,0 +1,2 @@ + 85744333 +85744333 diff --git a/Task/Iterated-digits-squaring/Java/iterated-digits-squaring.java b/Task/Iterated-digits-squaring/Java/iterated-digits-squaring.java new file mode 100644 index 0000000000..2cd54fc93e --- /dev/null +++ b/Task/Iterated-digits-squaring/Java/iterated-digits-squaring.java @@ -0,0 +1,24 @@ +import java.util.stream.IntStream; + +public class IteratedDigitsSquaring { + + public static void main(String[] args) { + long r = IntStream.range(1, 100_000_000) + .parallel() + .filter(n -> calc(n) == 89) + .count(); + System.out.println(r); + } + + private static int calc(int n) { + while (n != 89 && n != 1) { + int total = 0; + while (n > 0) { + total += Math.pow(n % 10, 2); + n /= 10; + } + n = total; + } + return n; + } +} diff --git a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia new file mode 100644 index 0000000000..127a46df06 --- /dev/null +++ b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia @@ -0,0 +1,18 @@ +function iterate(m) + while m != 1 && m != 89 + s = 0 + while m > 0 # compute sum of squares of digits + m, d = divrem(m, 10) + s += d*d + end + m = s + end + return m +end +function itercount(N) + count = 0 + for n in 1:N + count += iterate(n) == 89 + end + return count +end diff --git a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia new file mode 100644 index 0000000000..c2846f90bc --- /dev/null +++ b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia @@ -0,0 +1,27 @@ +function itercount_combinations(ndigits) + count = 0 + f = factorial(ndigits) + # loop over all combinations of ndigits decimal digits: + for c in combinations([1:(10+ndigits-1)],ndigits) + s = 0 + perms = 1 + prevdigit = -1 + repeat = 1 + for k = 1:length(c) # sum digits^2 and count permutations + digit = c[k]-k + s += digit*digit + # accumulate number of permutations of repeated digits + if digit == prevdigit + repeat += 1 + perms *= repeat + else + prevdigit = digit + repeat = 1 + end + end + if s > 0 && iterate(s) == 89 + count += div(f, perms) # numbers we can get from digits + end + end + return count +end diff --git a/Task/Iterated-digits-squaring/Lua/iterated-digits-squaring.lua b/Task/Iterated-digits-squaring/Lua/iterated-digits-squaring.lua new file mode 100644 index 0000000000..e0fb0cfac9 --- /dev/null +++ b/Task/Iterated-digits-squaring/Lua/iterated-digits-squaring.lua @@ -0,0 +1,47 @@ +squares = {} + +for i = 0, 9 do + for j = 0, 9 do + squares[i * 10 + j] = i * i + j * j + end +end + +for i = 1, 99 do + for j = 0, 99 do + squares[i * 100 + j] = squares[i] + squares[j] + end +end + +function sum_squares(n) + if n < 9999.5 then + return squares[n] + else + local m = math.floor(n / 10000) + return squares[n - 10000 * m] + sum_squares(m) + end +end + +memory = {} + +function calc_1_or_89(n) + local m = {} + n = memory[n] or n + while n ~= 1 and n ~= 89 do + n = memory[n] or sum_squares(n) + table.insert(m, n) + end + for _, i in pairs(m) do + memory[i] = n + end + return n +end + +counter = 0 + +for i = 1, 100000000 do + if calc_1_or_89(i) == 89 then + counter = counter + 1 + end +end + +print(counter) diff --git a/Task/Iterated-digits-squaring/Mathematica/iterated-digits-squaring.math b/Task/Iterated-digits-squaring/Mathematica/iterated-digits-squaring.math new file mode 100644 index 0000000000..2f38585b32 --- /dev/null +++ b/Task/Iterated-digits-squaring/Mathematica/iterated-digits-squaring.math @@ -0,0 +1,37 @@ +sumDigitsSquared[n_Integer] := Total[IntegerDigits[n]^2] +stopValues = Join[{1}, NestList[sumDigitsSquared, 89, 7]]; +iterate[n_Integer] := + NestWhile[sumDigitsSquared, n, Intersection[stopValues, {#}] == {} &] + +numberOfDigits = 8; +maxSum = numberOfDigits 9^2; +loopVariables = + ToExpression@Table["i" <> ToString[n], {n, numberOfDigits}]; +iteratesToOne = Cases[Range@maxSum, _?(iterate[#] == 1 &)]; +allIterators = + Flatten[{Reverse@#, 9}] & /@ Partition[loopVariables, 2, 1]; +maxCombinations = numberOfDigits!; + +ssd = + SparseArray[Table[n^2 -> numberOfDigits, {n, 9}], {maxSum}]; + +Do[ + variables = loopVariables[[;; digitCount]]; + iterators = allIterators[[;; digitCount - 1]]; + + Do[ssd += + SparseArray[ + Total[variables^2] -> + maxCombinations/ + Times @@ (Tally[PadRight[variables, numberOfDigits]][[All, + 2]]!), {maxSum}], {i, 9}, Evaluate[Sequence @@ iterators]], + + {digitCount, 2, numberOfDigits}]; + +onesCount = + Total[Cases[ + ArrayRules[ssd] /. + HoldPattern[{a_} -> b_] :> {a, + b}, {_?(MemberQ[iteratesToOne, #] &), _}][[All, 2]]]; + +(10^numberOfDigits - 1) - onesCount diff --git a/Task/Iterated-digits-squaring/Oberon-2/iterated-digits-squaring.oberon-2 b/Task/Iterated-digits-squaring/Oberon-2/iterated-digits-squaring.oberon-2 new file mode 100644 index 0000000000..e031008242 --- /dev/null +++ b/Task/Iterated-digits-squaring/Oberon-2/iterated-digits-squaring.oberon-2 @@ -0,0 +1,32 @@ +MODULE DigitsSquaring; +IMPORT + Out; + +VAR + i,hits89: LONGINT; + + PROCEDURE Squaring(n: LONGINT): LONGINT; + VAR + d, sum: LONGINT; + BEGIN + LOOP + sum := 0; + WHILE n > 0 DO + d := n MOD 10; + INC(sum,d * d); + n := n DIV 10 + END; + IF (sum = 1) OR (sum = 89) THEN EXIT END; + n := sum; + END; + + RETURN sum + END Squaring; + +BEGIN + hits89 := 0; + FOR i := 1 TO 100000000 DO + IF Squaring(i) = 89 THEN INC(hits89) END + END; + Out.LongInt(hits89,0);Out.Ln +END DigitsSquaring. diff --git a/Task/Iterated-digits-squaring/Pascal/iterated-digits-squaring.pascal b/Task/Iterated-digits-squaring/Pascal/iterated-digits-squaring.pascal new file mode 100644 index 0000000000..0f59fda2dc --- /dev/null +++ b/Task/Iterated-digits-squaring/Pascal/iterated-digits-squaring.pascal @@ -0,0 +1,136 @@ +program Euler92; +const + maxdigCnt = 14; + //2* to use the sum of two square-sums without access violation + maxPoss = 2* 9*9*maxdigCnt;// every digit is 9 + cM = 10*1000*1000;// 10^(maxdigCnt div 2) + IdxSqrSum = cM;//MaxPoss;//max(cM,MaxPoss); +type + tSqrSum = array[0..IdxSqrSum] of Word; + tEndsIn = array[0..maxPoss]of Byte; + tresCache = array[0..maxPoss]of Uint64; + +var + aSqrDigSum : tSqrSum; + aEndsIn: tEndsIn; + aresCache : tresCache; + +procedure CreateSpuareDigitSum; +var + i,j,k,l : integer; +begin + For i := 0 to 9 do + aSqrDigSum[i] := sqr(i); + k := 10; + l := k; + while k < cM do + begin + For i := 1 to 9 do + For j := 0 to k-1 do + begin + aSqrDigSum[l]:=aSqrDigSum[i]+aSqrDigSum[j]; + inc(l); + end; + k := l; + end; + aSqrDigSum[l] := 1; +end; + +function InitEndsIn(n:LongWord):longWord; +{fill aEndsIN recursive} +var + d,s:LongWord; +begin + IF n in [0..1] then + begin + InitEndsIn := n; + EXIT; + end; + s := aSqrDigSum[n]; + {if unknown} + IF aEndsIN[s] = byte(-1) then + begin + d := InitEndsIn(s); + aEndsIN[s]:= d; + InitEndsIn := d; + end + else + InitEndsIn := aEndsIN[s]; +end; + +function CntSmallOnes(s:longWord; + n:longWord=cM-1):NativeUint; +var + i: longword; +begin + result := 0; + For i := cM-1 downto 0 do + result := result+aEndsIN[aSqrDigSum[i]+s]; +end; + +procedure Init; +var + i,j,cnt : integer; +begin + CreateSpuareDigitSum; + fillchar(aEndsIN,Sizeof(aEndsIN) ,#255); + aEndsIN[0] := 0; + aEndsIN[1]:= 1; + aEndsIN[89]:= 0;// no need to use 89 + For i := 1 to maxPoss do + aEndsIN[i]:= InitEndsIN(i); + + cnt := 0; + fillchar(aresCache,SizeOf(aresCache),#0); + For i := Low(tSqrSum) to high(tSqrSum) do + begin + j := aSqrDigSum[i]; + If aresCache[j] = 0 then + begin +// write(i,','); + aresCache[j] := CntSmallOnes(j); + inc(cnt); + end; + end; +// writeln; writeln(cnt,' small counts out of ',cM); +end; +{ +function EndsIn(n:LongWord):Word; +var + d,s:LongWord; +begin + d := n; + s := 0; + while d > High(tSqrSum) do + begin + s := s+aSqrDigSum[d Mod cM]; + d := d Div cM + end; + s :=s+aSqrDigSum[d]; + EndsIn := aEndsIN[s]; +end; +} + +function CntOnes(s: longWord;n:Int64):Int64; +var + i : Int64; +begin +writeln; + result := 0; + i := n div cM; + repeat + result := result+aresCache[s+aSqrDigSum[i]]; + dec(i) + until i < 0 +end; + +const + upperlimit = cM*cM ; +var + Res : Int64; +begin + Init; + Res := CntOnes(0,upperlimit-1)+1; + writeln('there are ',res,' 1s '); + writeln('there are ',upperlimit-res,' 89s '); +end. diff --git a/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-1.pl6 b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-1.pl6 new file mode 100644 index 0000000000..61c6af2035 --- /dev/null +++ b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-1.pl6 @@ -0,0 +1,16 @@ +constant @sq = ^10 X** 2; +my $cnt = 0; +my %cache; + +sub Euler92($n) { + %cache{$n} //= + $n == any(1,89) ?? $n !! + Euler92( [+] @sq[$n.comb] ) +} + +for 1 .. 1_000_000 -> $n { + my $i = +$n.comb.sort.join; + ++$cnt if Euler92($i) == 89; +} + +say $cnt; diff --git a/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-2.pl6 b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-2.pl6 new file mode 100644 index 0000000000..06f65bbcab --- /dev/null +++ b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-2.pl6 @@ -0,0 +1,33 @@ +my @cache; +@cache[1] = 1; +@cache[89] = 89; + +sub Euler92(int $n) { + $n < 649 # 99,999,999 sums to 648, so no point remembering more + ?? (@cache.at_pos($n) //= ids($n)) + !! ids($n) +} + +sub ids(int $num --> int) { + my int $n = $num; + my int $ten = 10; + my int $sum = 0; + my int $t; + my int $c; + repeat until $n == 89 or $n == 1 { + $sum = 0; + repeat { + $t = $n div $ten; + $c = $n - $t * $ten; + $sum = $sum + $c * $c; + } while $n = $t; + $n = @cache.at_pos($sum) // $sum; + } + $n; +} + +my int $cnt = 0; +for 1 .. 100_000_000 -> int $n { + $cnt = $cnt + 1 if Euler92($n) == 89; +} +say $cnt; diff --git a/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 new file mode 100644 index 0000000000..f880000bf3 --- /dev/null +++ b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 @@ -0,0 +1,34 @@ +my $cache := nqp::list_i(); +nqp::bindpos_i($cache, 650, 0); +nqp::bindpos_i($cache, 1, 1); +nqp::bindpos_i($cache, 89, 89); + +sub Euler92(int $n) { + $n < 650 + ?? nqp::bindpos_i($cache,$n,ids($n)) + !! ids($n) +} + +sub ids(int $num --> int) { + my int $n = $num; + my int $ten = 10; + my int $sum = 0; + my int $t; + my int $c; + repeat until $n == 89 or $n == 1 { + $sum = 0; + repeat { + $t = nqp::div_i($n, $ten); + $c = $n - $t * $ten; + $sum = $sum + $c * $c; + } while $n = $t; + $n = nqp::atpos_i($cache,$sum) || $sum; + } + $n; +} + +my int $cnt = 0; +for 1 .. 100_000_000 -> int $n { + $cnt = $cnt + 1 if Euler92($n) == 89; +} +say $cnt; diff --git a/Task/Iterated-digits-squaring/Perl/iterated-digits-squaring.pl b/Task/Iterated-digits-squaring/Perl/iterated-digits-squaring.pl new file mode 100644 index 0000000000..44fd079d2b --- /dev/null +++ b/Task/Iterated-digits-squaring/Perl/iterated-digits-squaring.pl @@ -0,0 +1,24 @@ +use warnings; +use strict; + +my @sq = map { $_ ** 2 } 0 .. 9; +my %cache; +my $cnt = 0; + +sub Euler92 { + my $n = 0 + join( '', sort split( '', shift ) ); + $cache{$n} //= ($n == 1 || $n == 89) ? $n : + Euler92( sum( @sq[ split '', $n ] ) ) +} + +sub sum { + my $sum; + $sum += shift while @_; + $sum; +} + +for (1 .. 100_000_000) { + ++$cnt if Euler92( $_ ) == 89; +} + +print $cnt; diff --git a/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-1.py b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-1.py new file mode 100644 index 0000000000..d32b3544ae --- /dev/null +++ b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-1.py @@ -0,0 +1,56 @@ +from math import ceil, log10, factorial + +def next_step(x): + result = 0 + while x > 0: + result += (x % 10) ** 2 + x /= 10 + return result + +def check(number): + candidate = 0 + for n in number: + candidate = candidate * 10 + n + + while candidate != 89 and candidate != 1: + candidate = next_step(candidate) + + if candidate == 89: + digits_count = [0] * 10 + for d in number: + digits_count[d] += 1 + + result = factorial(len(number)) + for c in digits_count: + result /= factorial(c) + return result + + return 0 + +def main(): + limit = 100000000 + cache_size = int(ceil(log10(limit))) + assert 10 ** cache_size == limit + + number = [0] * cache_size + result = 0 + i = cache_size - 1 + + while True: + if i == 0 and number[i] == 9: + break + if i == cache_size - 1 and number[i] < 9: + number[i] += 1 + result += check(number) + elif number[i] == 9: + i -= 1 + else: + number[i] += 1 + for j in xrange(i + 1, cache_size): + number[j] = number[i] + i = cache_size - 1 + result += check(number) + + print result + +main() diff --git a/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-2.py b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-2.py new file mode 100644 index 0000000000..395aca7288 --- /dev/null +++ b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-2.py @@ -0,0 +1,42 @@ +from itertools import combinations_with_replacement +from array import array +from time import clock +D = 8 +F = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000] +def b(n): + yield 1 + for g in range(1,n+1): + gn = g + res = 0 + while gn > 0: + gn,rem = divmod(gn,10) + res += rem**2 + if res==89: + yield 0 + else: + yield res +N = array('I',b(81*D)) +for n in range(2,len(N)): + q = N[n] + while q>1: + q = N[q] + N[n] = q + +es = clock() +z = 0 +for n in combinations_with_replacement(range(10),D): + t = 0 + for g in n: + t += g*g + if N[t] == 0: + continue + t = [0,0,0,0,0,0,0,0,0,0] + for g in n: + t[g] += 1 + t1 = F[D] + for g in t: + t1 /= F[g] + z += t1 +ee = clock() - es +print "\nD==" + str(D) + "\n " + str(z) + " numbers produce 1 and " + str(10**D-z) + " numbers produce 89" +print "Time ~= " + str(ee) + " secs" diff --git a/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-3.py b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-3.py new file mode 100644 index 0000000000..3b41827f07 --- /dev/null +++ b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-3.py @@ -0,0 +1,14 @@ +>>> from functools import lru_cache +>>> @lru_cache(maxsize=1024) +def ids(n): + if n in {1, 89}: return n + else: return ids(sum(int(d) ** 2 for d in str(n))) + + +>>> ids(15) +89 +>>> [ids(x) for x in range(1, 21)] +[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1, 89] +>>> sum(ids(x) == 89 for x in range(1, 100000000)) +85744333 +>>> diff --git a/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-4.py b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-4.py new file mode 100644 index 0000000000..5f49d23d61 --- /dev/null +++ b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-4.py @@ -0,0 +1,19 @@ +>>> from functools import lru_cache +>>> @lru_cache(maxsize=1024) +def _ids(nt): + if nt in {('1',), ('8', '9')}: return nt + else: return _ids(tuple(sorted(str(sum(int(d) ** 2 for d in nt))))) + + +>>> def ids(n): + return int(''.join(_ids(tuple(sorted(str(n)))))) + +>>> ids(1), ids(15) +(1, 89) +>>> [ids(x) for x in range(1, 21)] +[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1, 89] +>>> sum(ids(x) == 89 for x in range(1, 100000000)) +85744333 +>>> _ids.cache_info() +CacheInfo(hits=99991418, misses=5867462, maxsize=1024, currsize=1024) +>>> diff --git a/Task/Iterated-digits-squaring/README b/Task/Iterated-digits-squaring/README new file mode 100644 index 0000000000..6ad15948d2 --- /dev/null +++ b/Task/Iterated-digits-squaring/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Iterated_digits_squaring diff --git a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx new file mode 100644 index 0000000000..79c080f101 --- /dev/null +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx @@ -0,0 +1,22 @@ +/*REXX program to perform iterated digits squaring ('til sum=1 | sum=89)*/ +parse arg n . /*get optional N from the C.L. */ +if n=='' then n=1000000 /*Was N given? No, use default.*/ +!.=0; do m=1 to 9; !.m=m**2; end /*build a short-cut for squares. */ +#.=0 /*count of 1 & 89 results so far.*/ + do j=1 for n /* [↓] process each num in range*/ + x=j /*use X for a proxy for the J var*/ + do until s==1 | s==89 /*add the squared digits of X.*/ + s=0 /*set the sum to zero initially. */ + do k=1 for length(x) /*process each of the digits in X*/ + _=substr(x,k,1) /*pick off a particular X digit*/ + s=s+!._ /*do a fast squaring of it & sum.*/ + end /*k*/ /* [↑] S≡is sum of squared digs.*/ + x=s /*subsitute the sum for "new" X. */ + end /*until*/ /* [↑] keep looping 'til S=1|89.*/ + #.s=#.s+1 /*bump the counter for 1's | 89's*/ + end /*j*/ + + do i=1 by 89-1 for 2; c=' 'right('"'i'"',4)' chains ' + say 'count of' c 'for all natural numbers up to ' n " is " #.i + end /*i*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx new file mode 100644 index 0000000000..bbd2ffe460 --- /dev/null +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx @@ -0,0 +1,43 @@ +/*REXX program to perform iterated digits squaring ('til sum=1 | sum=89)*/ +parse arg n . /*get optional N from the C.L. */ +if n=='' then n=100000000 /*Was N given? No, use default.*/ +!.=0; do m=1 to 9; !.m=m**2; end /*build a short-cut for squares. */ +$.=.; $.0=0; $.00=0; $.000=0; $.0000=0; @.=. /*short-cuts for some sums*/ +@.=. /*placeholder for computed sums. */ +#.=0 /*count of 1 & 89 results so far.*/ + do j=1 for n /* [↓] process each num in range*/ + s=sumds(j) /*get the sum of squared digits. */ + #.s=#.s+1 /*bump the counter for 1's | 89's*/ + end /*j*/ + + do i=1 by 89-1 for 2; c=' 'right('"'i'"',4)' chains ' + say 'count of' c 'for all natural numbers up to ' n " is " #.i + end /*i*/ + +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SUMDS subroutine────────────────────*/ +sumds: parse arg z; p=0 + do m=1 by 4 to length(z) + p=p + summer(substr(z,m,4)) + end /*m*/ +if $.p\==. then return $.p /*if computed before, use the val*/ +y=p + do until s==1 | s==89 /*add the squared digits of P.*/ + s=0 /*set the sum to zero initially. */ + do k=1 for length(y) /*process each of the digits in X*/ + _=substr(y,k,1) /*pick off a particular X digit*/ + s=s+!._ /*do a fast squaring of it & sum.*/ + end /*k*/ /* [↑] S≡is sum of squared digs.*/ + y=s /*subsitute the sum for "new" X. */ + end /*until*/ /* [↑] keep looping 'til S=1|89.*/ +$.p=s +return s +/*──────────────────────────────────SUMMER subroutine───────────────────*/ +summer: parse arg y . 1 oy .; if @.y\==. then return @.y /*use old val*/ +a=0 + do k=1 for length(y) /*process each of the digits in X*/ + _=substr(y,k,1) /*pick off a particular X digit*/ + a=a+!._ /*do a fast squaring of it & sum.*/ + end /*k*/ /* [↑] S≡is sum of squared digs.*/ +@.oy=a +return a diff --git a/Task/Iterated-digits-squaring/Racket/iterated-digits-squaring.rkt b/Task/Iterated-digits-squaring/Racket/iterated-digits-squaring.rkt new file mode 100644 index 0000000000..319c06f306 --- /dev/null +++ b/Task/Iterated-digits-squaring/Racket/iterated-digits-squaring.rkt @@ -0,0 +1,96 @@ +#lang racket +;; Tim-brown 2014-09-11 + +;; The basic definition. +;; It is possible to memoise this or use fixnum (native) arithmetic, but frankly iterating over a +;; hundred million, billion, trillion numbers will be slow. No matter how you do it. +(define (digit^2-sum n) + (let loop ((n n) (s 0)) + (if (= 0 n) s (let-values ([(q r) (quotient/remainder n 10)]) (loop q (+ s (sqr r))))))) + +(define (iterated-digit^2-sum n) + (match (digit^2-sum n) [0 0] [1 1] [89 89] [(app iterated-digit^2-sum rv) rv])) + +;; Note that: ids(345) = ids(354) = ids(435) = ids(453) = ids(534) = ids(543) = 50 --> 89 +;; One calculation does for 6 candidates. +;; The plan: +;; - get all the ordered combinations of digits including 0's which can be used both as digits and +;; "padding" digits in the most significant digits. (n.b. all-zeros is not in the range to be +;; tested and should be dropped) +;; - find the digit sets that have an IDS of 89 +;; - find out how many combinations there are of these digits + +;; output: a list of n-digits long lists containing all of the digit combinations. +;; a smart bunny would figure out the sums of the digits as they're generated but I'll plod +;; along step-by-step. a truly smart bunny would also count the combinations. that said, I +;; don't think I do much unnecessary computation here. +(define (all-digit-lists n-digits) + (define (inner remain acc least-digit) + (cond + [(zero? remain) (list (list))] + [(= least-digit 10) null] + [else + (for*/list + ((ld+ (in-range least-digit 10)) + (rgt (in-list (inner (sub1 remain) empty ld+)))) + (append acc (cons ld+ rgt)))])) + (inner n-digits '() 0)) + +;; We calculate IDS differently since we're presented with a list of digits rather than a number +(define (digit-list-IDS c) + (define (digit-combo-IDS c) + (apply + (map sqr c))) + (iterated-digit^2-sum (digit-combo-IDS c))) + +;; ! (factiorial) -- everyone's favourite combinatorial function! (that's just an exclamation mark) +;; there's one in (require math/number-theory) for any heavy lifting, but we're not or I could import +;; it from math/number-theory -- but this is about all I need. A lookup table is going to be faster +;; than a more general function. +(define (! n) + (case n [(0 1) 1] [(2) 2] [(3) 6] [(4) 24] [(5) 120] [(6) 720] [(7) 5040] [(8) 40320] [(9) 362880] + [else (* n (! (sub1 n)))] ; I expect this clause'll never be called + )) + +;; We need to count the permutations -- digits are in order so we can use the tail (cdr) function for +;; determining my various k's. See: https://en.wikipedia.org/wiki/Combination +(define (count-digit-list-permutations c #:length (l (length c)) #:length! (l! (! l))) + (let loop ((c c) (i 0) (prev -1 #;"never a digit") (p l!)) + (match c + [(list) (/ p (! i))] + [(cons (== prev) d) (loop d (+ i 1) prev p)] + [(cons a d) (loop d 1 a (/ p (! i)))]))) + +;; Wrap it all up in a neat function +(define (count-89s-in-100... n) + (define n-digits (order-of-magnitude n)) + (define combos (drop (all-digit-lists n-digits) 1)) ; don't want first one which is "all-zeros" + (for/sum ((c (in-list combos)) #:when (= 89 (digit-list-IDS c))) + (count-digit-list-permutations c #:length n-digits))) + +(displayln "Testing permutations:") +(time (printf "1000000:\t~a~%" (count-89s-in-100... 1000000))) +(time (printf "100000000:\t~a~%" (count-89s-in-100... 100000000))) +(time (printf "1000000000:\t~a~%" (count-89s-in-100... 1000000000))) +(time (printf "1000000000000:\t~a~%" (count-89s-in-100... 1000000000000))) +(newline) +;; Do these last, since the 10^8 takes longer than my ADHD can cope with +(displayln "Testing one number at a time (somewhat slower):") +(time (printf "1000000:\t~a~%" (for/sum ((n (in-range 1 1000000)) + #:when (= 89 (iterated-digit^2-sum n))) 1))) +(time (printf "100000000:\t~a~%" (for/sum ((n (in-range 1 100000000)) + #:when (= 89 (iterated-digit^2-sum n))) 1))) + +{module+ test + (require tests/eli-tester) + [test + (iterated-digit^2-sum 15) => 89 + (iterated-digit^2-sum 7) => 1 + (digit-combo-perms '()) => 1 + (digit-combo-perms '(1 2 3)) => 6 + (digit-combo-perms '(1 1 3)) => 3 + (for/sum ((n (in-range 1 1000000)) #:when (= 89 (iterated-digit^2-sum n))) 1) => 856929 + (all-digit-lists 1) => '((0) (1) (2) (3) (4) (5) (6) (7) (8) (9)) + (length (all-digit-lists 2)) => 55 + (length (all-digit-lists 3)) => 220 + (count-89s-in-100... 1000000) => 856929] + } diff --git a/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb b/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb new file mode 100644 index 0000000000..b491cd8b8d --- /dev/null +++ b/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb @@ -0,0 +1,28 @@ +# Count how many number chains for Natural Numbers <= 100,000,000 end with a value 89. +# +# Nigel_Galloway +# August 26th., 2014. +require 'benchmark' +D = 8 #Calculate from 1 to 10**D (8 for task) +F = Array.new(D+1){|n| (1..n).inject(1,:*)} #Some small factorials +g = -> n, gn=[n,0], res=0 { while gn[0]>0 + gn = gn[0].divmod(10) + res += gn[1]**2 + end + res==89 ? 0 : res + } +#An array: N[n]==0 means that n translates to 89 and 1 means that n translates to 1 +G = Array.new(D*81+1){|n| n==0 ? 1 : (i=g.call(n))==89 ? 0 : i} +N = G.collect{|n| n = G[n] while n>1; n } + +z = 0 #Running count of numbers translating to 1 +t = Benchmark.measure do + [*0..9].repeated_combination(D) do |rc| #Iterate over unique digit combinations + next if N[rc.inject(0){|g,n| g+n*n}] == 0 #Count only ones + nn = [0,0,0,0,0,0,0,0,0,0] #Determine how many numbers this digit combination corresponds to + rc.each{|n| nn[n] += 1} + z += nn.inject(F[D]){|gn,n| gn/F[n]} #Add to the count of numbers terminating in 1 + end +end +puts "#{z} numbers produce 1 and #{10**D-z} numbers produce 89" +puts "\nTiming\n#{t}" diff --git a/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-1.tcl b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-1.tcl new file mode 100644 index 0000000000..d06c9326bc --- /dev/null +++ b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-1.tcl @@ -0,0 +1,10 @@ +proc ids n { + while {$n != 1 && $n != 89} { + set n [tcl::mathop::+ {*}[lmap x [split $n ""] {expr {$x**2}}]] + } + return $n +} +for {set i 1} {$i <= 100000000} {incr i} { + incr count [expr {[ids $i] == 89}] +} +puts $count diff --git a/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-2.tcl b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-2.tcl new file mode 100644 index 0000000000..da021216f0 --- /dev/null +++ b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-2.tcl @@ -0,0 +1,13 @@ +proc ids n { + while {$n != 1 && $n != 89} { + for {set m 0} {$n} {set n [expr {$n / 10}]} { + incr m [expr {($n%10)**2}] + } + set n $m + } + return $n +} +for {set i 1} {$i <= 100000000} {incr i} { + incr count [expr {[ids $i] == 89}] +} +puts $count diff --git a/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-3.tcl b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-3.tcl new file mode 100644 index 0000000000..603fc41e8d --- /dev/null +++ b/Task/Iterated-digits-squaring/Tcl/iterated-digits-squaring-3.tcl @@ -0,0 +1,32 @@ +# Basic implementation +proc ids n { + while {$n != 1 && $n != 89} { + for {set m 0} {$n} {set n [expr {$n / 10}]} { + incr m [expr {($n%10)**2}] + } + set n $m + } + return $n +} + +# Build the optimised version +set body { + # Microoptimisation to avoid an unnecessary alloc in the loop + for {set m 0} {$n} {set n [expr {"$n[unset n]" / 10}]} { + incr m [expr {($n%10)**2}] + } +} +set map 0 +for {set i 1} {$i <= 729} {incr i} { + lappend map [ids $i] +} +proc ids2 n [append body "return \[lindex [list $map] \$m\]"] + +# Put this in a lambda context for a little extra speed. +apply {{} { + set count 0 + for {set i 1} {$i <= 100000000} {incr i} { + incr count [expr {[ids2 $i] == 89}] + } + puts $count +}} diff --git a/Task/K-d-tree/00DESCRIPTION b/Task/K-d-tree/00DESCRIPTION new file mode 100644 index 0000000000..77738751b8 --- /dev/null +++ b/Task/K-d-tree/00DESCRIPTION @@ -0,0 +1,28 @@ +{{wikipedia|K-d tree}} +[[Category:Data Structures]] +A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). +k-d trees are a special case of binary space partitioning trees. + +k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' ≫ 2''k''. +Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead. + +'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets: + +# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)]. +# 1000 3-d points uniformly distributed in a 3-d cube. + +For the Wikipedia example, find the nearest neighbor to point (9, 2) +For the random data, pick a random location and find the nearest neighbor. + +In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed. + +Output should show the point searched for, the point found, +the distance to the point, and the number of nodes visited. + +There are variant algorithms for constructing the tree. +You can use a simple median strategy or implement something more efficient. +Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. +You do not have to implement these. +The requirement for this task is specifically the nearest single neighbor. +Also there are algorithms for inserting, deleting, and balancing k-d trees. +These are also not required for the task. diff --git a/Task/K-d-tree/C/k-d-tree.c b/Task/K-d-tree/C/k-d-tree.c new file mode 100644 index 0000000000..628e58c361 --- /dev/null +++ b/Task/K-d-tree/C/k-d-tree.c @@ -0,0 +1,173 @@ +#include +#include +#include +#include +#include + +#define MAX_DIM 3 +struct kd_node_t{ + double x[MAX_DIM]; + struct kd_node_t *left, *right; +}; + +inline double +dist(struct kd_node_t *a, struct kd_node_t *b, int dim) +{ + double t, d = 0; + while (dim--) { + t = a->x[dim] - b->x[dim]; + d += t * t; + } + return d; +} + +/* see quickselect method */ +struct kd_node_t* +find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) +{ + if (end <= start) return NULL; + if (end == start + 1) + return start; + + inline void swap(struct kd_node_t *x, struct kd_node_t *y) { + double tmp[MAX_DIM]; + memcpy(tmp, x->x, sizeof(tmp)); + memcpy(x->x, y->x, sizeof(tmp)); + memcpy(y->x, tmp, sizeof(tmp)); + } + + struct kd_node_t *p, *store, *md = start + (end - start) / 2; + double pivot; + while (1) { + pivot = md->x[idx]; + + swap(md, end - 1); + for (store = p = start; p < end; p++) { + if (p->x[idx] < pivot) { + if (p != store) + swap(p, store); + store++; + } + } + swap(store, end - 1); + + /* median has duplicate values */ + if (store->x[idx] == md->x[idx]) + return md; + + if (store > md) end = store; + else start = store; + } +} + +struct kd_node_t* +make_tree(struct kd_node_t *t, int len, int i, int dim) +{ + struct kd_node_t *n; + + if (!len) return 0; + + if ((n = find_median(t, t + len, i))) { + i = (i + 1) % dim; + n->left = make_tree(t, n - t, i, dim); + n->right = make_tree(n + 1, t + len - (n + 1), i, dim); + } + return n; +} + +/* global variable, so sue me */ +int visited; + +void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, + struct kd_node_t **best, double *best_dist) +{ + double d, dx, dx2; + + if (!root) return; + d = dist(root, nd, dim); + dx = root->x[i] - nd->x[i]; + dx2 = dx * dx; + + visited ++; + + if (!*best || d < *best_dist) { + *best_dist = d; + *best = root; + } + + /* if chance of exact match is high */ + if (!*best_dist) return; + + if (++i >= dim) i = 0; + + nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); + if (dx2 >= *best_dist) return; + nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); +} + +#define N 1000000 +#define rand1() (rand() / (double)RAND_MAX) +#define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } +int main(void) +{ + int i; + struct kd_node_t wp[] = { + {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} + }; + struct kd_node_t this = {{9, 2}}; + struct kd_node_t *root, *found, *million; + double best_dist; + + root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); + + visited = 0; + found = 0; + nearest(root, &this, 0, 2, &found, &best_dist); + + printf(">> WP tree\nsearching for (%g, %g)\n" + "found (%g, %g) dist %g\nseen %d nodes\n\n", + this.x[0], this.x[1], + found->x[0], found->x[1], sqrt(best_dist), visited); + + million = calloc(N, sizeof(struct kd_node_t)); + srand(time(0)); + for (i = 0; i < N; i++) rand_pt(million[i]); + + root = make_tree(million, N, 0, 3); + rand_pt(this); + + visited = 0; + found = 0; + nearest(root, &this, 0, 3, &found, &best_dist); + + printf(">> Million tree\nsearching for (%g, %g, %g)\n" + "found (%g, %g, %g) dist %g\nseen %d nodes\n", + this.x[0], this.x[1], this.x[2], + found->x[0], found->x[1], found->x[2], + sqrt(best_dist), visited); + + /* search many random points in million tree to see average behavior. + tree size vs avg nodes visited: + 10 ~ 7 + 100 ~ 16.5 + 1000 ~ 25.5 + 10000 ~ 32.8 + 100000 ~ 38.3 + 1000000 ~ 42.6 + 10000000 ~ 46.7 */ + int sum = 0, test_runs = 100000; + for (i = 0; i < test_runs; i++) { + found = 0; + visited = 0; + rand_pt(this); + nearest(root, &this, 0, 3, &found, &best_dist); + sum += visited; + } + printf("\n>> Million tree\n" + "visited %d nodes for %d random findings (%f per lookup)\n", + sum, test_runs, sum/(double)test_runs); + + // free(million); + + return 0; +} diff --git a/Task/K-d-tree/D/k-d-tree-1.d b/Task/K-d-tree/D/k-d-tree-1.d new file mode 100644 index 0000000000..0fc415895e --- /dev/null +++ b/Task/K-d-tree/D/k-d-tree-1.d @@ -0,0 +1,209 @@ +// Implmentation following pseudocode from +// "An introductory tutorial on kd-trees" by Andrew W. Moore, +// Carnegie Mellon University, PDF accessed from: +// http://www.autonlab.org/autonweb/14665 + +import std.typecons, std.math, std.algorithm, std.random, std.range, + std.traits, core.memory; + +/// k-dimensional point. +struct Point(size_t k, F) if (isFloatingPoint!F) { + F[k] data; + alias data this; // Kills DMD std.algorithm.swap inlining. + // Define opIndexAssign and opIndex for dmd. + enum size_t length = k; + + /// Square of the euclidean distance. + double sqd(in ref Point!(k, F) q) const pure nothrow @nogc { + double sum = 0; + foreach (immutable dim, immutable pCoord; data) + sum += (pCoord - q[dim]) ^^ 2; + return sum; + } +} + +// Following field names in the paper. +// rangeElt would be whatever data is associated with the Point. +// We don't bother with it for this example. +struct KdNode(size_t k, F) { + Point!(k, F) domElt; + immutable int split; + typeof(this)* left, right; +} + +struct Orthotope(size_t k, F) { /// k-dimensional rectangle. + Point!(k, F) min, max; +} + +struct KdTree(size_t k, F) { + KdNode!(k, F)* n; + Orthotope!(k, F) bounds; + + // Constructs a KdTree from a list of points, also associating the + // bounds of the tree. The bounds could be computed of course, but + // in this example we know them already. The algorithm is table + // 6.3 in the paper. + this(Point!(k, F)[] pts, in Orthotope!(k, F) bounds_) pure { + static KdNode!(k, F)* nk2(size_t split)(Point!(k, F)[] exset) + pure { + if (exset.empty) + return null; + if (exset.length == 1) + return new KdNode!(k, F)(exset[0], split, null, null); + + // Pivot choosing procedure. We find median, then find + // largest index of points with median value. This + // satisfies the inequalities of steps 6 and 7 in the + // algorithm. + auto m = exset.length / 2; + topN!((p, q) => p[split] < q[split])(exset, m); + immutable d = exset[m]; + while (m+1 < exset.length && exset[m+1][split] == d[split]) + m++; + + enum nextSplit = (split + 1) % d.length;//cycle coordinates + return new KdNode!(k, F)(d, split, + nk2!nextSplit(exset[0 .. m]), + nk2!nextSplit(exset[m + 1 .. $])); + } + + this.n = nk2!0(pts); + this.bounds = bounds_; + } +} + +/** +Find nearest neighbor. Return values are: + nearest neighbor--the ooint within the tree that is nearest p. + square of the distance to that point. + a count of the nodes visited in the search. +*/ +auto findNearest(size_t k, F)(KdTree!(k, F) t, in Point!(k, F) p) +pure nothrow @nogc { + // Algorithm is table 6.4 from the paper, with the addition of + // counting the number nodes visited. + static Tuple!(Point!(k, F), "nearest", + F, "distSqd", + int, "nodesVisited") + nn(KdNode!(k, F)* kd, in Point!(k, F) target, + Orthotope!(k, F) hr, F maxDistSqd) pure nothrow @nogc { + if (kd == null) + return typeof(return)(Point!(k, F)(), F.infinity, 0); + + int nodesVisited = 1; + immutable s = kd.split; + auto pivot = kd.domElt; + auto leftHr = hr; + auto rightHr = hr; + leftHr.max[s] = pivot[s]; + rightHr.min[s] = pivot[s]; + + KdNode!(k, F)* nearerKd, furtherKd; + Orthotope!(k, F) nearerHr, furtherHr; + if (target[s] <= pivot[s]) { + //nearerKd, nearerHr = kd.left, leftHr; + //furtherKd, furtherHr = kd.right, rightHr; + nearerKd = kd.left; + nearerHr = leftHr; + furtherKd = kd.right; + furtherHr = rightHr; + } else { + //nearerKd, nearerHr = kd.right, rightHr; + //furtherKd, furtherHr = kd.left, leftHr; + nearerKd = kd.right; + nearerHr = rightHr; + furtherKd = kd.left; + furtherHr = leftHr; + } + + auto n1 = nn(nearerKd, target, nearerHr, maxDistSqd); + auto nearest = n1.nearest; + auto distSqd = n1.distSqd; + nodesVisited += n1.nodesVisited; + + if (distSqd < maxDistSqd) + maxDistSqd = distSqd; + auto d = (pivot[s] - target[s]) ^^ 2; + if (d > maxDistSqd) + return typeof(return)(nearest, distSqd, nodesVisited); + d = pivot.sqd(target); + if (d < distSqd) { + nearest = pivot; + distSqd = d; + maxDistSqd = distSqd; + } + + immutable n2 = nn(furtherKd, target, furtherHr, maxDistSqd); + nodesVisited += n2.nodesVisited; + if (n2.distSqd < distSqd) { + nearest = n2.nearest; + distSqd = n2.distSqd; + } + + return typeof(return)(nearest, distSqd, nodesVisited); + } + + return nn(t.n, p, t.bounds, F.infinity); +} + +void showNearest(size_t k, F)(in string heading, KdTree!(k, F) kd, + in Point!(k, F) p) { + import std.stdio: writeln; + writeln(heading, ":"); + writeln("Point: ", p); + immutable n = kd.findNearest(p); + writeln("Nearest neighbor: ", n.nearest); + writeln("Distance: ", sqrt(n.distSqd)); + writeln("Nodes visited: ", n.nodesVisited, "\n"); +} + +void main() { + static Point!(k, F) randomPoint(size_t k, F)() { + typeof(return) result; + foreach (immutable i; 0 .. k) + result[i] = uniform(F(0), F(1)); + return result; + } + + static Point!(k, F)[] randomPoints(size_t k, F)(in size_t n) { + return n.iota.map!(_ => randomPoint!(k, F)).array; + } + + import std.stdio, std.conv, std.datetime, std.typetuple; + rndGen.seed(1); // For repeatable outputs. + + alias D2 = TypeTuple!(2, double); + alias P = Point!D2; + auto kd1 = KdTree!D2([P([2, 3]), P([5, 4]), P([9, 6]), + P([4, 7]), P([8, 1]), P([7, 2])], + Orthotope!D2(P([0, 0]), P([10, 10]))); + showNearest("Wikipedia example data", kd1, P([9, 2])); + + enum int N = 400_000; + alias F3 = TypeTuple!(3, float); + alias Q = Point!F3; + StopWatch sw; + GC.disable; + sw.start; + auto kd2 = KdTree!F3(randomPoints!F3(N), + Orthotope!F3(Q([0, 0, 0]), Q([1, 1, 1]))); + sw.stop; + GC.enable; + showNearest(text("k-d tree with ", N, + " random 3D ", F3[1].stringof, + " points (construction time: ", + sw.peek.msecs, " ms)"), kd2, randomPoint!F3); + + sw.reset; + sw.start; + enum int M = 10_000; + size_t visited = 0; + foreach (immutable _; 0 .. M) { + immutable n = kd2.findNearest(randomPoint!F3); + visited += n.nodesVisited; + } + sw.stop; + + writefln("Visited an average of %0.2f nodes on %d searches " ~ + "in %d ms.", visited / double(M), M, sw.peek.msecs); +} diff --git a/Task/K-d-tree/D/k-d-tree-2.d b/Task/K-d-tree/D/k-d-tree-2.d new file mode 100644 index 0000000000..929debb90e --- /dev/null +++ b/Task/K-d-tree/D/k-d-tree-2.d @@ -0,0 +1,165 @@ +import std.stdio, std.algorithm, std.math, std.random, std.typecons; + +enum maxDim = 3; + +struct KdNode { + double[maxDim] x; + KdNode* left, right; +} + +// See QuickSelect method. +KdNode* findMedian(size_t idx)(KdNode[] nodes) pure nothrow @nogc { + auto start = nodes.ptr; + auto end = &nodes[$ - 1] + 1; + + if (end <= start) + return null; + if (end == start + 1) + return start; + + KdNode* md = start + (end - start) / 2; + + while (true) { + immutable double pivot = md.x[idx]; + + swap(md.x, (end - 1).x); // Swaps the whole arrays x. + auto store = start; + foreach (p; start .. end) { + if (p.x[idx] < pivot) { + if (p != store) + swap(p.x, store.x); + store++; + } + } + swap(store.x, (end - 1).x); + + // Median has duplicate values. + if (store.x[idx] == md.x[idx]) + return md; + + if (store > md) + end = store; + else + start = store; + } +} + +KdNode* makeTree(size_t dim, size_t i)(KdNode[] nodes) +pure nothrow @nogc { + if (!nodes.length) + return null; + + auto n = findMedian!i(nodes); + if (n != null) { + enum i2 = (i + 1) % dim; + immutable size_t nPos = n - nodes.ptr; + n.left = makeTree!(dim, i2)(nodes[0 .. nPos]); + n.right = makeTree!(dim, i2)(nodes[nPos + 1 .. $]); + } + + return n; +} + +void nearest(size_t dim)(in KdNode* root, + in ref KdNode nd, + in size_t i, + ref const(KdNode)* best, + ref double bestDist, + ref size_t nVisited) pure nothrow @safe @nogc { + static double dist(in ref KdNode a, in ref KdNode b) + pure nothrow @nogc { + typeof(KdNode.x[0]) result = 0; + foreach (immutable i; staticIota!(0, dim)) + result += (a.x[i] - b.x[i]) ^^ 2; + return result; + } + + if (root == null) + return; + + immutable double d = dist(*root, nd); + immutable double dx = root.x[i] - nd.x[i]; + immutable double dx2 = dx ^^ 2; + nVisited++; + + if (!best || d < bestDist) { + bestDist = d; + best = root; + } + + // If chance of exact match is high. + if (!bestDist) + return; + + immutable i2 = (i + 1 >= dim) ? 0 : i + 1; + + nearest!dim(dx > 0 ? root.left : root.right, + nd, i2, best, bestDist, nVisited); + if (dx2 >= bestDist) + return; + nearest!dim(dx > 0 ? root.right : root.left, + nd, i2, best, bestDist, nVisited); +} + +void randPt(size_t dim=3)(ref KdNode v, ref Xorshift rng) +pure nothrow @safe @nogc { + foreach (immutable i; staticIota!(0, dim)) + v.x[i] = rng.uniform01; +} + +void smallTest() { + KdNode[] wp = [{[2, 3]}, {[5, 4]}, {[9, 6]}, + {[4, 7]}, {[8, 1]}, {[7, 2]}]; + KdNode thisPt = {[9, 2]}; + + KdNode* root = makeTree!(2, 0)(wp); + + const(KdNode)* found = null; + double bestDist = 0; + size_t nVisited = 0; + nearest!2(root, thisPt, 0, found, bestDist, nVisited); + + writefln("WP tree:\n Searching for %s\n" ~ + " Found %s, dist = %g\n Seen %d nodes.\n", + thisPt.x[0..2], found.x[0..2], sqrt(bestDist), nVisited); +} + +void bigTest() { + enum N = 1_000_000; + enum testRuns = 100_000; + + auto bigTree = new KdNode[N]; + auto rng = 1.Xorshift; + foreach (ref node; bigTree) + randPt(node, rng); + + KdNode* root = makeTree!(3, 0)(bigTree); + KdNode thisPt; + randPt(thisPt, rng); + + const(KdNode)* found = null; + double bestDist = 0; + size_t nVisited = 0; + nearest!3(root, thisPt, 0, found, bestDist, nVisited); + + writefln("Big tree (%d nodes):\n Searching for %s\n"~ + " Found %s, dist = %g\n Seen %d nodes.", + N, thisPt.x, found.x, sqrt(bestDist), nVisited); + + size_t sum = 0; + foreach (immutable _; 0 .. testRuns) { + found = null; + nVisited = 0; + randPt(thisPt, rng); + nearest!3(root, thisPt, 0, found, bestDist, nVisited); + sum += nVisited; + } + writefln("\nBig tree:\n Visited %d nodes for %d random "~ + "searches (%.2f per lookup).", + sum, testRuns, sum / double(testRuns)); +} + +void main() { + smallTest; + bigTest; +} diff --git a/Task/K-d-tree/Go/k-d-tree.go b/Task/K-d-tree/Go/k-d-tree.go new file mode 100644 index 0000000000..85f5d8ec15 --- /dev/null +++ b/Task/K-d-tree/Go/k-d-tree.go @@ -0,0 +1,183 @@ +// Implmentation following pseudocode from "An intoductory tutorial on kd-trees" +// by Andrew W. Moore, Carnegie Mellon University, PDF accessed from +// http://www.autonlab.org/autonweb/14665 +package main + +import ( + "fmt" + "math" + "math/rand" + "sort" + "time" +) + +// point is a k-dimensional point. +type point []float64 + +// sqd returns the square of the euclidean distance. +func (p point) sqd(q point) float64 { + var sum float64 + for dim, pCoord := range p { + d := pCoord - q[dim] + sum += d * d + } + return sum +} + +// kdNode following field names in the paper. +// rangeElt would be whatever data is associated with the point. we don't +// bother with it for this example. +type kdNode struct { + domElt point + split int + left, right *kdNode +} + +type kdTree struct { + n *kdNode + bounds hyperRect +} + +type hyperRect struct { + min, max point +} + +// Go slices are reference objects. The data must be copied if you want +// to modify one without modifying the original. +func (hr hyperRect) copy() hyperRect { + return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} +} + +// newKd constructs a kdTree from a list of points, also associating the +// bounds of the tree. The bounds could be computed of course, but in this +// example we know them already. The algorithm is table 6.3 in the paper. +func newKd(pts []point, bounds hyperRect) kdTree { + var nk2 func([]point, int) *kdNode + nk2 = func(exset []point, split int) *kdNode { + if len(exset) == 0 { + return nil + } + // pivot choosing procedure. we find median, then find largest + // index of points with median value. this satisfies the + // inequalities of steps 6 and 7 in the algorithm. + sort.Sort(part{exset, split}) + m := len(exset) / 2 + d := exset[m] + for m+1 < len(exset) && exset[m+1][split] == d[split] { + m++ + } + // next split + s2 := split + 1 + if s2 == len(d) { + s2 = 0 + } + return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} + } + return kdTree{nk2(pts, 0), bounds} +} + +// a container type used for sorting. it holds the points to sort and +// the dimension to use for the sort key. +type part struct { + pts []point + dPart int +} + +// satisfy sort.Interface +func (p part) Len() int { return len(p.pts) } +func (p part) Less(i, j int) bool { + return p.pts[i][p.dPart] < p.pts[j][p.dPart] +} +func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } + +// nearest. find nearest neighbor. return values are: +// nearest neighbor--the point within the tree that is nearest p. +// square of the distance to that point. +// a count of the nodes visited in the search. +func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { + return nn(t.n, p, t.bounds, math.Inf(1)) +} + +// algorithm is table 6.4 from the paper, with the addition of counting +// the number nodes visited. +func nn(kd *kdNode, target point, hr hyperRect, + maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { + if kd == nil { + return nil, math.Inf(1), 0 + } + nodesVisited++ + s := kd.split + pivot := kd.domElt + leftHr := hr.copy() + rightHr := hr.copy() + leftHr.max[s] = pivot[s] + rightHr.min[s] = pivot[s] + targetInLeft := target[s] <= pivot[s] + var nearerKd, furtherKd *kdNode + var nearerHr, furtherHr hyperRect + if targetInLeft { + nearerKd, nearerHr = kd.left, leftHr + furtherKd, furtherHr = kd.right, rightHr + } else { + nearerKd, nearerHr = kd.right, rightHr + furtherKd, furtherHr = kd.left, leftHr + } + var nv int + nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) + nodesVisited += nv + if distSqd < maxDistSqd { + maxDistSqd = distSqd + } + d := pivot[s] - target[s] + d *= d + if d > maxDistSqd { + return + } + if d = pivot.sqd(target); d < distSqd { + nearest = pivot + distSqd = d + maxDistSqd = distSqd + } + tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) + nodesVisited += nv + if tempSqd < distSqd { + nearest = tempNearest + distSqd = tempSqd + } + return +} + +func main() { + rand.Seed(time.Now().Unix()) + kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, + hyperRect{point{0, 0}, point{10, 10}}) + showNearest("WP example data", kd, point{9, 2}) + kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) + showNearest("1000 random 3d points", kd, randomPt(3)) +} + +func randomPt(dim int) point { + p := make(point, dim) + for d := range p { + p[d] = rand.Float64() + } + return p +} + +func randomPts(dim, n int) []point { + p := make([]point, n) + for i := range p { + p[i] = randomPt(dim) + } + return p +} + +func showNearest(heading string, kd kdTree, p point) { + fmt.Println() + fmt.Println(heading) + fmt.Println("point: ", p) + nn, ssq, nv := kd.nearest(p) + fmt.Println("nearest neighbor:", nn) + fmt.Println("distance: ", math.Sqrt(ssq)) + fmt.Println("nodes visited: ", nv) +} diff --git a/Task/K-d-tree/Haskell/k-d-tree.hs b/Task/K-d-tree/Haskell/k-d-tree.hs new file mode 100644 index 0000000000..991e25957a --- /dev/null +++ b/Task/K-d-tree/Haskell/k-d-tree.hs @@ -0,0 +1,201 @@ +import System.Random +import Data.List (sortBy, genericLength, minimumBy) +import Data.Ord (comparing) + +-- A finite list of dimensional accessors tell a KDTree how to get a +-- Euclidean dimensional value 'b' out of an arbitrary datum 'a'. +type DimensionalAccessors a b = [a -> b] + +-- A binary tree structure of 'a'. +data Tree a = Node a (Tree a) (Tree a) + | Empty + +instance Show a => Show (Tree a) where + show Empty = "Empty" + show (Node value left right) = + "(" ++ show value ++ " " ++ show left ++ " " ++ show right ++ ")" + +-- A k-d tree structure of 'a' with Euclidean dimensions of 'b'. +data KDTree a b = KDTree (DimensionalAccessors a b) (Tree a) + +instance Show a => Show (KDTree a b) where + show (KDTree _ tree) = "KDTree " ++ show tree + +-- The squared Euclidean distance formula. +sqrDist :: Num b => DimensionalAccessors a b -> a -> a -> b +sqrDist dims a b = sum $ map square $ zipWith (-) a' b' + where + a' = map ($ a) dims + b' = map ($ b) dims + +square :: Num a => a -> a +square = (^ 2) + +-- Insert a value into a k-d tree. +insert :: Ord b => KDTree a b -> a -> KDTree a b +insert (KDTree dims tree) value = KDTree dims $ ins (cycle dims) tree + where + ins _ Empty = Node value Empty Empty + ins (d:ds) (Node split left right) = + if d value < d split + then Node split (ins ds left) right + else Node split left (ins ds right) + +-- Produce an empty k-d tree. +empty :: DimensionalAccessors a b -> KDTree a b +empty dims = KDTree dims Empty + +-- Produce a k-d tree with one value. +singleton :: Ord b => DimensionalAccessors a b -> a -> KDTree a b +singleton dims value = insert (empty dims) value + +-- Create a k-d tree from a list of values using the median-finding algorithm. +fromList :: Ord b => DimensionalAccessors a b -> [a] -> KDTree a b +fromList dims values = KDTree dims $ fList (cycle dims) values + where + fList _ [] = Empty + fList (d:ds) values = + let sorted = sortBy (comparing d) values + (lower, higher) = splitAt (genericLength sorted `div` 2) sorted + in case higher of + [] -> Empty + median:rest -> Node median (fList ds lower) (fList ds rest) + +-- Create a k-d tree from a list of values by repeatedly inserting the values +-- into a tree. Faster than median-finding, but can create unbalanced trees. +fromListLinear :: Ord b => DimensionalAccessors a b -> [a] -> KDTree a b +fromListLinear dims values = foldl insert (empty dims) values + +-- Given a k-d tree, find the nearest value to a given value. +-- Also report how many nodes were visited. +nearest :: (Ord b, Num b, Integral c) => KDTree a b -> a -> (Maybe a, c) +nearest (KDTree dims tree) value = near (cycle dims) tree + where + dist = sqrDist dims + -- If we have an empty tree, then return nothing. + near _ Empty = (Nothing, 1) + -- We hit a leaf node, so it is the current best. + near _ (Node split Empty Empty) = (Just split, 1) + near (d:ds) (Node split left right) = + -- Move down the tree in the fashion of insertion. + let dimdist x y = square (d x - d y) + splitDist = dist value split + hyperPlaneDist = dimdist value split + bestLeft = near ds left + bestRight = near ds right + -- maybeThisBest is the node of the side of the split where the value + -- resides, and maybeOtherBest is the node on the other side of the split. + ((maybeThisBest, thisCount), (maybeOtherBest, otherCount)) = + if d value < d split + then (bestLeft, bestRight) + else (bestRight, bestLeft) + in case maybeThisBest of + Nothing -> + -- From the search point (in this case), the hypersphere radius to + -- the split node is always >= the hyperplane distance, so we will + -- always check the other side. + let count = 1 + thisCount + otherCount + in case maybeOtherBest of + -- We are currently at a leaf node, so this is the only choice. + -- It is not strictly necessary to take care of this case + -- because of the above pattern matching in near. + Nothing -> (Just split, count) + -- We have a node on the other side, so compare + -- it to the split point to see which is closer. + Just otherBest -> + if dist value otherBest < splitDist + then (maybeOtherBest, count) + else (Just split, count) + + Just thisBest -> + let thisBestDist = dist value thisBest + best = + -- Determine which is the closer node of this side. + if splitDist < thisBestDist + then split + else thisBest + bestDist = dist value best + in + if bestDist < hyperPlaneDist + -- If the distance to the best node is less than the distance + -- to the splitting hyperplane, then the current best node is the + -- only choice. + then (Just best, 1 + thisCount) + -- There is a chance that a node on the other side is closer + -- than the current best. + else + let count = 1 + thisCount + otherCount + in case maybeOtherBest of + Nothing -> (Just best, count) + Just otherBest -> + if bestDist < dist value otherBest + then (Just best, count) + else (maybeOtherBest, count) + +-- Dimensional accessors for a 2-tuple +tuple2D :: [(a, a) -> a] +tuple2D = [fst, snd] + +-- Dimensional accessors for a 3-tuple +tuple3D :: [(a, a, a) -> a] +tuple3D = [d1, d2, d3] + where + d1 (a, _, _) = a + d2 (_, b, _) = b + d3 (_, _, c) = c + +-- Random 3-tuple generation +instance (Random a, Random b, Random c) => Random (a, b, c) where + random gen = + let (vA, genA) = random gen + (vB, genB) = random genA + (vC, genC) = random genB + in ((vA, vB, vC), genC) + + randomR ((lA, lB, lC), (hA, hB, hC)) gen = + let (vA, genA) = randomR (lA, hA) gen + (vB, genB) = randomR (lB, hB) genA + (vC, genC) = randomR (lC, hC) genB + in ((vA, vB, vC), genC) + +printResults :: (Show a, Show b, Show c, Floating c) => + a -> (Maybe a, b) -> DimensionalAccessors a c -> IO () +printResults point result dims = do + let (nearest, visited) = result + case nearest of + Nothing -> putStrLn "Could not find nearest." + Just value -> do + let dist = sqrt $ sqrDist dims point value + putStrLn $ "Point: " ++ show point + putStrLn $ "Nearest: " ++ show value + putStrLn $ "Distance: " ++ show dist + putStrLn $ "Visited: " ++ show visited + putStrLn "" + +-- Naive nearest search used to confirm results. +linearNearest :: (Ord b, Num b) => DimensionalAccessors a b -> a -> [a] -> Maybe a +linearNearest _ _ [] = Nothing +linearNearest dims value xs = Just $ minimumBy (comparing $ sqrDist dims value) xs + +main :: IO () +main = do + let wikiValues :: [(Double, Double)] + wikiValues = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)] + wikiTree = fromList tuple2D wikiValues + wikiSearch = (9, 2) + wikiNearest = nearest wikiTree wikiSearch + putStrLn "Wikipedia example:" + printResults wikiSearch wikiNearest tuple2D + + let stdGen = mkStdGen 0 + randRange :: ((Double, Double, Double), (Double, Double, Double)) + randRange = ((0, 0, 0), (1000, 1000, 1000)) + (randSearch, stdGenB) = randomR randRange stdGen + randValues = take 1000 $ randomRs randRange stdGenB + randTree = fromList tuple3D randValues + randNearest = nearest randTree randSearch + randNearestLinear = linearNearest tuple3D randSearch randValues + putStrLn "1000 random 3D points on the range of [0, 1000):" + printResults randSearch randNearest tuple3D + putStrLn "Confirm naive nearest:" + print randNearestLinear diff --git a/Task/K-d-tree/J/k-d-tree-1.j b/Task/K-d-tree/J/k-d-tree-1.j new file mode 100644 index 0000000000..497a0ed4de --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-1.j @@ -0,0 +1,69 @@ +coclass 'kdnode' + create=:3 :0 + Axis=: ({:$y)|<.2^.#y + Mask=: Axis~:i.{:$y + if. 3>#y do. + Leaf=:1 + Points=: y + else. + Leaf=:0 + data=. y /: Axis|."1 y + n=. <.-:#data + Points=: ,:n{data + Left=: conew&'kdnode' n{.data + Right=: conew&'kdnode' (1+n)}.data + end. + ) + + distance=: +/&.:*:@:-"1 + + nearest=:3 :0 + _ 0 nearest y + : + n=.' ',~":N_base_=:N_base_+1 + dists=. Points distance y + ndx=. (i. <./) dists + nearest=. ndx { Points + range=. ndx { dists + if. Leaf do. + range;nearest return. + else. + d0=. x <. range + p0=. nearest + if. d0=0 do. 0;y return. end. + if. 0={./:Axis|."1 y,Points do. + 'dist pnt'=.d0 nearest__Left y + if. dist > d0 do. + d0;p0 return. + end. + if. dist < d0 do. + if. dist > (Mask#pnt) distance Mask#,Points do. + 'dist2 pnt2'=. d0 nearest__Right y + if. dist2 < dist do. dist2;pnt2 return. end. + end. + end. + else. + 'dist pnt'=. d0 nearest__Right y + if. dist > d0 do. + d0;p0 return. + end. + if. dist < d0 do. + if. dist > (Mask#pnt) distance Mask#,Points do. + 'dist2 pnt2'=. d0 nearest__Left y + if. dist2 < dist do. dist2;pnt2 return. end. + end. + end. + end. + end. + dist;pnt return. + ) + +coclass 'kdtree' + create=:3 :0 + root=: conew&'kdnode' y + ) + nearest=:3 :0 + N_base_=:0 + 'dist point'=. nearest__root y + dist;N_base_;point + ) diff --git a/Task/K-d-tree/J/k-d-tree-2.j b/Task/K-d-tree/J/k-d-tree-2.j new file mode 100644 index 0000000000..eb7732fef1 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-2.j @@ -0,0 +1,5 @@ + tree=:conew&'kdtree' (2,3), (5,4), (9,6), (4,7), (8,1),: (7,2) + nearest__tree 9 2 +┌───────┬─┬───┐ +│1.41421│4│8 1│ +└───────┴─┴───┘ diff --git a/Task/K-d-tree/J/k-d-tree-3.j b/Task/K-d-tree/J/k-d-tree-3.j new file mode 100644 index 0000000000..c38992ca87 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-3.j @@ -0,0 +1,5 @@ + tree=:conew&'kdtree' dataset=:?1000 3$0 + nearest__tree pnt +┌─────────┬──┬──────────────────────────┐ +│0.0387914│12│0.978082 0.767632 0.392523│ +└─────────┴──┴──────────────────────────┘ diff --git a/Task/K-d-tree/J/k-d-tree-4.j b/Task/K-d-tree/J/k-d-tree-4.j new file mode 100644 index 0000000000..9f783cd6b0 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-4.j @@ -0,0 +1,10 @@ +build0=:3 :0 + data=: y +) + +distance=: +/&.:*:@:-"1 + +nearest0=:3 :0 + nearest=. data {~ (i. <./) |data distance y + (nearest distance y);(#data);nearest +) diff --git a/Task/K-d-tree/J/k-d-tree-5.j b/Task/K-d-tree/J/k-d-tree-5.j new file mode 100644 index 0000000000..1819bad258 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-5.j @@ -0,0 +1,10 @@ + build0 (2,3), (5,4), (9,6), (4,7), (8,1),: (7,2) + nearest0 9 2 +┌───────┬─┬───┐ +│1.41421│6│8 1│ +└───────┴─┴───┘ + build0 dataset + nearest0 pnt +┌─────────┬────┬──────────────────────────┐ +│0.0387914│1000│0.978082 0.767632 0.392523│ +└─────────┴────┴──────────────────────────┘ diff --git a/Task/K-d-tree/J/k-d-tree-6.j b/Task/K-d-tree/J/k-d-tree-6.j new file mode 100644 index 0000000000..04d285d667 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-6.j @@ -0,0 +1,6 @@ + tree=:conew&'kdtree' (2,3), (5,4), (9,6), (4,7), (8,1),: (7,2) + timespacex 'nearest__tree 9 2' +0.000487181 19328 + build0 (2,3), (5,4), (9,6), (4,7), (8,1),: (7,2) + timespacex 'nearest0 9 2' +3.62419e_5 6016 diff --git a/Task/K-d-tree/J/k-d-tree-7.j b/Task/K-d-tree/J/k-d-tree-7.j new file mode 100644 index 0000000000..7877df0c13 --- /dev/null +++ b/Task/K-d-tree/J/k-d-tree-7.j @@ -0,0 +1,6 @@ + tree=:conew&'kdtree' dataset + timespacex 'nearest__tree pnt' +0.00141408 45312 + build0 dataset + timespacex 'nearest0 pnt' +0.00140702 22144 diff --git a/Task/K-d-tree/Perl-6/k-d-tree.pl6 b/Task/K-d-tree/Perl-6/k-d-tree.pl6 new file mode 100644 index 0000000000..c739ca0153 --- /dev/null +++ b/Task/K-d-tree/Perl-6/k-d-tree.pl6 @@ -0,0 +1,126 @@ +class Kd_node { + has $.d; + has $.split; + has $.left; + has $.right; +} + +class Orthotope { + has $.min; + has $.max; +} + +class Kd_tree { + has $.n; + has $.bounds; + method new($pts, $bounds) { self.bless(n => nk2(0,$pts), bounds => $bounds) } + + sub nk2($split, @e) { + return () unless @e; + my @exset = @e.sort(*.[$split]); + my $m = +@exset div 2; + my @d = @exset[$m][]; + while $m+1 < @exset and @exset[$m+1][$split] eqv @d[$split] { + ++$m; + } + + my $s2 = ($split + 1) % @d; # cycle coordinates + Kd_node.new: :@d, :$split, + left => nk2($s2, @exset[0 ..^ $m]), + right => nk2($s2, @exset[$m ^.. *]); + } +} + +class T3 { + has $.nearest; + has $.dist_sqd = Inf; + has $.nodes_visited = 0; +} + +sub find_nearest($k, $t, @p) { + return nn($t.n, @p, $t.bounds, Inf); + + sub nn($kd, @target, $hr, $max_dist_sqd is copy) { + return T3.new(:nearest([0.0 xx $k])) unless $kd; + + my $nodes_visited = 1; + my $s = $kd.split; + my $pivot = $kd.d; + my $left_hr = $hr.clone; + my $right_hr = $hr.clone; + $left_hr.max[$s] = $pivot[$s]; + $right_hr.min[$s] = $pivot[$s]; + + my $nearer_kd; + my $further_kd; + my $nearer_hr; + my $further_hr; + if @target[$s] <= $pivot[$s] { + ($nearer_kd, $nearer_hr) = $kd.left, $left_hr; + ($further_kd, $further_hr) = $kd.right, $right_hr; + } + else { + ($nearer_kd, $nearer_hr) = $kd.right, $right_hr; + ($further_kd, $further_hr) = $kd.left, $left_hr; + } + + my $n1 = nn($nearer_kd, @target, $nearer_hr, $max_dist_sqd); + my $nearest = $n1.nearest; + my $dist_sqd = $n1.dist_sqd; + $nodes_visited += $n1.nodes_visited; + + if $dist_sqd < $max_dist_sqd { + $max_dist_sqd = $dist_sqd; + } + my $d = ($pivot[$s] - @target[$s]) ** 2; + if $d > $max_dist_sqd { + return T3.new(:$nearest, :$dist_sqd, :$nodes_visited); + } + $d = [+] (@$pivot Z- @target) X** 2; + if $d < $dist_sqd { + $nearest = $pivot; + $dist_sqd = $d; + $max_dist_sqd = $dist_sqd; + } + + my $n2 = nn($further_kd, @target, $further_hr, $max_dist_sqd); + $nodes_visited += $n2.nodes_visited; + if $n2.dist_sqd < $dist_sqd { + $nearest = $n2.nearest; + $dist_sqd = $n2.dist_sqd; + } + + T3.new(:$nearest, :$dist_sqd, :$nodes_visited); + } +} + +sub show_nearest($k, $heading, $kd, @p) { + print qq:to/END/; + $heading: + Point: [@p.join(',')] + END + my $n = find_nearest($k, $kd, @p); + print qq:to/END/; + Nearest neighbor: [$n.nearest.join(',')] + Distance: &sqrt($n.dist_sqd) + Nodes visited: $n.nodes_visited() + + END +} + +sub random_point($k) { [rand xx $k] } +sub random_points($k, $n) { [random_point($k) xx $n] } + +sub MAIN { + my $kd1 = Kd_tree.new([[2, 3],[5, 4],[9, 6],[4, 7],[8, 1],[7, 2]], + Orthotope.new(:min([0, 0]), :max([10, 10]))); + show_nearest(2, "Wikipedia example data", $kd1, [9, 2]); + + my $N = 1000; + my $t0 = now; + my $kd2 = Kd_tree.new(random_points(3, $N), Orthotope.new(:min([0,0,0]), :max([1,1,1]))); + my $t1 = now; + show_nearest(2, + "k-d tree with $N random 3D points (generation time: {$t1 - $t0}s)", + $kd2, random_point(3)); +} diff --git a/Task/K-d-tree/Python/k-d-tree.py b/Task/K-d-tree/Python/k-d-tree.py new file mode 100644 index 0000000000..5c2d03447b --- /dev/null +++ b/Task/K-d-tree/Python/k-d-tree.py @@ -0,0 +1,130 @@ +from random import seed, random +from time import clock +from operator import itemgetter +from collections import namedtuple +from math import sqrt +from copy import deepcopy + + +def sqd(p1, p2): + return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) + + +class KdNode(object): + __slots__ = ("dom_elt", "split", "left", "right") + + def __init__(self, dom_elt, split, left, right): + self.dom_elt = dom_elt + self.split = split + self.left = left + self.right = right + + +class Orthotope(object): + __slots__ = ("min", "max") + + def __init__(self, mi, ma): + self.min, self.max = mi, ma + + +class KdTree(object): + __slots__ = ("n", "bounds") + + def __init__(self, pts, bounds): + def nk2(split, exset): + if not exset: + return None + exset.sort(key=itemgetter(split)) + m = len(exset) // 2 + d = exset[m] + while m + 1 < len(exset) and exset[m + 1][split] == d[split]: + m += 1 + + s2 = (split + 1) % len(d) # cycle coordinates + return KdNode(d, split, nk2(s2, exset[:m]), + nk2(s2, exset[m + 1:])) + self.n = nk2(0, pts) + self.bounds = bounds + +T3 = namedtuple("T3", "nearest dist_sqd nodes_visited") + + +def find_nearest(k, t, p): + def nn(kd, target, hr, max_dist_sqd): + if kd is None: + return T3([0.0] * k, float("inf"), 0) + + nodes_visited = 1 + s = kd.split + pivot = kd.dom_elt + left_hr = deepcopy(hr) + right_hr = deepcopy(hr) + left_hr.max[s] = pivot[s] + right_hr.min[s] = pivot[s] + + if target[s] <= pivot[s]: + nearer_kd, nearer_hr = kd.left, left_hr + further_kd, further_hr = kd.right, right_hr + else: + nearer_kd, nearer_hr = kd.right, right_hr + further_kd, further_hr = kd.left, left_hr + + n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd) + nearest = n1.nearest + dist_sqd = n1.dist_sqd + nodes_visited += n1.nodes_visited + + if dist_sqd < max_dist_sqd: + max_dist_sqd = dist_sqd + d = (pivot[s] - target[s]) ** 2 + if d > max_dist_sqd: + return T3(nearest, dist_sqd, nodes_visited) + d = sqd(pivot, target) + if d < dist_sqd: + nearest = pivot + dist_sqd = d + max_dist_sqd = dist_sqd + + n2 = nn(further_kd, target, further_hr, max_dist_sqd) + nodes_visited += n2.nodes_visited + if n2.dist_sqd < dist_sqd: + nearest = n2.nearest + dist_sqd = n2.dist_sqd + + return T3(nearest, dist_sqd, nodes_visited) + + return nn(t.n, p, t.bounds, float("inf")) + + +def show_nearest(k, heading, kd, p): + print(heading + ":") + print("Point: ", p) + n = find_nearest(k, kd, p) + print("Nearest neighbor:", n.nearest) + print("Distance: ", sqrt(n.dist_sqd)) + print("Nodes visited: ", n.nodes_visited, "\n") + + +def random_point(k): + return [random() for _ in range(k)] + + +def random_points(k, n): + return [random_point(k) for _ in range(n)] + +if __name__ == "__main__": + seed(1) + P = lambda *coords: list(coords) + kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)], + Orthotope(P(0, 0), P(10, 10))) + show_nearest(2, "Wikipedia example data", kd1, P(9, 2)) + + N = 400000 + t0 = clock() + kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1))) + t1 = clock() + text = lambda *parts: "".join(map(str, parts)) + show_nearest(2, text("k-d tree with ", N, + " random 3D points (generation time: ", + t1-t0, "s)"), + kd2, random_point(3)) diff --git a/Task/K-d-tree/README b/Task/K-d-tree/README new file mode 100644 index 0000000000..416204303b --- /dev/null +++ b/Task/K-d-tree/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/K-d_tree diff --git a/Task/K-d-tree/Racket/k-d-tree-1.rkt b/Task/K-d-tree/Racket/k-d-tree-1.rkt new file mode 100644 index 0000000000..4e86913348 --- /dev/null +++ b/Task/K-d-tree/Racket/k-d-tree-1.rkt @@ -0,0 +1,68 @@ +#lang racket + +; A tree consists of a point, a left and a right subtree. +(struct tree (p l r) #:transparent) +; If the node is in depth d, then the points in l has +; the (d mod k)'th coordinate less than the same coordinate in p. + +(define (kdtree d k ps) + (cond [(empty? ps) #f] ; #f represents an empty subtree + [else (define-values (p l r) (split-points ps (modulo d k))) + (tree p (kdtree (+ d 1) k l) (kdtree (+ d 1) k r))])) + +(define (split-points ps d) + (define (ref p) (vector-ref p d)) + (define sorted-ps (sort ps < #:key ref)) + (define mid (quotient (+ (length ps)) 2)) + (define median (ref (list-ref sorted-ps mid))) + (define-values (l r) (partition(λ(x)(< (ref x) median))sorted-ps)) + (values (first r) l (rest r))) + +; The bounding box of a subtree: +(struct bb (mins maxs) #:transparent) + +(define (infinite-bb k) + (bb (make-vector k -inf.0) (make-vector k +inf.0))) + +(define/match (copy-bb h) + [((bb mins maxs)) + (bb (vector-copy mins) (vector-copy maxs))]) + +(define (dist v w) (for/sum ([x v] [y w]) (sqr (- x y)))) +(define (intersects? g r hr) (<= (dist (closest-in-hr g hr) g) r)) +(define (closest-in-hr g hr) + (for/vector ([gi g] [mini (bb-mins hr)] [maxi (bb-maxs hr)]) + (cond [(<= gi mini) mini] + [(< mini gi maxi) gi] + [else maxi]))) + +(define (split-bb hr d x) + (define left (copy-bb hr)) + (define right (copy-bb hr)) + (vector-set! (bb-maxs left) d x) + (vector-set! (bb-mins right) d x) + (values left right)) + +(define visits 0) ; for statistics only +(define (visit) (set! visits (+ visits 1))) +(define (reset-visits) (set! visits 0)) +(define (regret-visit) (set! visits (- visits 1))) + +(define (nearest-neighbor g t k) + (define (nearer? p q) (< (dist p g) (dist q g))) + (define (nearest p q) (if (nearer? p q) p q)) + (define (nn d t bb) (visit) + (define (ref p) (vector-ref p (modulo d k))) + (match t + [#f (regret-visit) #(+inf.0 +inf.0 +inf.0)] + [(tree p l r) + (define-values (lbb rbb) (split-bb bb (modulo d k) (ref p))) + (define-values (near near-bb far far-bb) + (if (< (ref g) (ref p)) + (values l lbb r rbb) + (values r rbb l lbb))) + (define n (nearest p (nn (+ d 1) near near-bb))) + (if (intersects? g (dist n g) far-bb) + (nearest n (nn (+ d 1) far far-bb)) + n)])) + (nn 0 t (infinite-bb k))) diff --git a/Task/K-d-tree/Racket/k-d-tree-2.rkt b/Task/K-d-tree/Racket/k-d-tree-2.rkt new file mode 100644 index 0000000000..8ee42d5105 --- /dev/null +++ b/Task/K-d-tree/Racket/k-d-tree-2.rkt @@ -0,0 +1,27 @@ +(define (wikipedia-test) + (define t (kdtree 0 2 '(#(2 3) #(5 4) #(9 6) #(4 7) #(8 1) #(7 2)))) + (reset-visits) + (define n (nearest-neighbor #(9 2) t 2)) + (displayln "Wikipedia Test") + (displayln (~a "Nearest neighbour to (9,2) is: " n)) + (displayln (~a "Distance: " (dist n #(9 2)))) + (displayln (~a "Visits: " visits "\n"))) + +(define (test k n) + (define (random!) (for/vector ([_ k]) (random))) + (define points (for/list ([_ n]) (random!))) + (define t (kdtree 0 k points)) + (reset-visits) + (define target (for/vector ([_ k]) 0.75)) + (define nb (nearest-neighbor target t k)) + (define nb-control (argmin (λ (p) (dist p target)) points)) + (displayln (~a n " points in R^3 test")) + (displayln (~a "Nearest neighbour to " target " is: \n\t\t" nb)) + (displayln (~a "Control: \t" nb-control)) + (displayln (~a "Distance: \t" (dist nb target))) + (displayln (~a "Control: \t" (dist nb-control target))) + (displayln (~a "Visits: \t" visits))) + +(wikipedia-test) +(test 3 1000) +(test 3 1000) diff --git a/Task/K-d-tree/Racket/k-d-tree-3.rkt b/Task/K-d-tree/Racket/k-d-tree-3.rkt new file mode 100644 index 0000000000..58320b417a --- /dev/null +++ b/Task/K-d-tree/Racket/k-d-tree-3.rkt @@ -0,0 +1,20 @@ +Wikipedia Test +Nearest neighbour to (9,2) is: #(8 1) +Distance: 2 +Visits: 3 + +1000 points in R^3 test +Nearest neighbour to #(0.75 0.75 0.75) is: + #(0.8092534479975508 0.7507095851813429 0.7706494651024903) +Control: #(0.8092534479975508 0.7507095851813429 0.7706494651024903) +Distance: 0.003937875019747008 +Control: 0.003937875019747008 +Visits: 83 + +1000 points in R^3 test +Nearest neighbour to #(0.75 0.75 0.75) is: + #(0.7775581478448806 0.7806612633582072 0.7396664367640902) +Control: #(0.7775581478448806 0.7806612633582072 0.7396664367640902) +Distance: 0.0018063471125121851 +Control: 0.0018063471125121851 +Visits: 39 diff --git a/Task/K-d-tree/Scala/k-d-tree-1.scala b/Task/K-d-tree/Scala/k-d-tree-1.scala new file mode 100644 index 0000000000..01169b7f8d --- /dev/null +++ b/Task/K-d-tree/Scala/k-d-tree-1.scala @@ -0,0 +1,51 @@ +object KDTree { + import Numeric._ + + // Task 1A. Build tree of KDNodes. Translated from Wikipedia. + def apply[T](points: Seq[Seq[T]], depth: Int = 0)(implicit num: Numeric[T]): Option[KDNode[T]] = { + val dim = points.headOption.map(_.size) getOrElse 0 + if (points.isEmpty || dim < 1) None + else { + val axis = depth % dim + val sorted = points.sortBy(_(axis)) + val median = sorted(sorted.size / 2)(axis) + val (left, right) = sorted.partition(v => num.lt(v(axis), median)) + Some(KDNode(right.head, apply(left, depth + 1), apply(right.tail, depth + 1), axis)) + } + } + + // Task 1B. Find the nearest node in this subtree. Translated from Wikipedia. + case class KDNode[T](value: Seq[T], left: Option[KDNode[T]], right: Option[KDNode[T]], axis: Int)(implicit num: Numeric[T]) { + def nearest(to: Seq[T]): Nearest[T] = { + val default = Nearest(value, to, Set(this)) + compare(to, value) match { + case 0 => default // exact match + case t => + lazy val bestL = left.map(_ nearest to).getOrElse(default) + lazy val bestR = right.map(_ nearest to).getOrElse(default) + val branch1 = if (t < 0) bestL else bestR + val best = if (num.lt(branch1.distsq, default.distsq)) branch1 else default + val splitDist = num.minus(to(axis), value(axis)) + if (num.lt(num.times(splitDist, splitDist), best.distsq)) { + val branch2 = if (t < 0) bestR else bestL + val visited = branch2.visited ++ best.visited + this + if (num.lt(branch2.distsq, best.distsq)) + branch2.copy(visited = visited) + else best.copy(visited = visited) + } else best.copy(visited = best.visited + this) + } + } + } + + // Keep track of nodes visited, as per task. Pretty-printable. + case class Nearest[T](value: Seq[T], to: Seq[T], visited: Set[KDNode[T]] = Set[KDNode[T]]())(implicit num: Numeric[T]) { + lazy val distsq = KDTree.distsq(value, to) + override def toString = f"Searched for=${to} found=${value} distance=${math.sqrt(num.toDouble(distsq))}%.4f visited=${visited.size}" + } + + // Numeric utilities + def distsq[T](a: Seq[T], b: Seq[T])(implicit num: Numeric[T]) = + a.zip(b).map(c => num.times(num.minus(c._1, c._2), num.minus(c._1, c._2))).sum + def compare[T](a: Seq[T], b: Seq[T])(implicit num: Numeric[T]): Int = + a.zip(b).find(c => num.compare(c._1, c._2) != 0).map(c => num.compare(c._1, c._2)).getOrElse(0) +} diff --git a/Task/K-d-tree/Scala/k-d-tree-2.scala b/Task/K-d-tree/Scala/k-d-tree-2.scala new file mode 100644 index 0000000000..515bac7de4 --- /dev/null +++ b/Task/K-d-tree/Scala/k-d-tree-2.scala @@ -0,0 +1,35 @@ +object KDTreeTest extends App { + def test[T](haystack: Seq[Seq[T]], needles: Seq[T]*)(implicit num: Numeric[T]) = { + println + val tree = KDTree(haystack) + if (haystack.size < 20) tree.foreach(println) + for (kd <- tree; needle <- needles; nearest = kd nearest needle) { + println(nearest) + // Brute force proof + val better = haystack + .map(KDTree.Nearest(_, needle)) + .filter(n => num.lt(n.distsq, nearest.distsq)) + .sortBy(_.distsq) + assert(better.isEmpty, s"Found ${better.size} closer than ${nearest.value} e.g. ${better.head}") + } + } + + // Results 1 + val wikitest = List(List(2,3), List(5,4), List(9,6), List(4,7), List(8,1), List(7,2)) + test(wikitest, List(9,2)) + + // Results 2 (1000 points uniformly distributed in 3-d cube coordinates, sides 2 to 20) + val uniform = for(x <- 1 to 10; y <- 1 to 10; z <- 1 to 10) yield List(x*2, y*2, z*2) + assume(uniform.size == 1000) + test(uniform, List(0, 0, 0), List(2, 2, 20), List(9, 10, 11)) + + // Results 3 (1000 points randomly distributed in 3-d cube coordinates, sides -1.0 to 1.0) + scala.util.Random.setSeed(0) + def random(n: Int) = (1 to n).map(_ => (scala.util.Random.nextDouble - 0.5)* 2) + test((1 to 1000).map(_ => random(3)), random(3)) + + // Results 4 (27 points uniformly distributed in 3-d cube coordinates, sides 3...9) + val small = for(x <- 1 to 3; y <- 1 to 3; z <- 1 to 3) yield List(x*3, y*3, z*3) + assume(small.size == 27) + test(small, List(0, 0, 0), List(4, 5, 6)) +} diff --git a/Task/K-d-tree/Tcl/k-d-tree-1.tcl b/Task/K-d-tree/Tcl/k-d-tree-1.tcl new file mode 100644 index 0000000000..c70c5d04d0 --- /dev/null +++ b/Task/K-d-tree/Tcl/k-d-tree-1.tcl @@ -0,0 +1,69 @@ +package require TclOO + +oo::class create KDTree { + variable t dim + constructor {points} { + set t [my Build 0 $points 0 end] + set dim [llength [lindex $points 0]] + } + method Build {split exset from to} { + set exset [lsort -index $split -real [lrange $exset $from $to]] + if {![llength $exset]} {return 0} + set m [expr {[llength $exset] / 2}] + set d [lindex $exset $m] + while {[set mm $m;incr mm] < [llength $exset] && \ + [lindex $exset $mm $split] == [lindex $d $split]} { + set m $mm + } + set s [expr {($split + 1) % [llength $d]}] + list 1 $d $split [my Build $s $exset 0 [expr {$m-1}]] \ + [my Build $s $exset [expr {$m+1}] end] + } + + method findNearest {p} { + lassign [my FN $t $p inf] p d2 count + return [list $p [expr {sqrt($d2)}] $count] + } + method FN {kd target maxDist2} { + if {[lindex $kd 0] == 0} { + return [list [lrepeat $dim 0.0] inf 0] + } + + set nodesVisited 1 + lassign $kd -> pivot s + + if {[lindex $target $s] <= [lindex $pivot $s]} { + set nearerKD [lindex $kd 3] + set furtherKD [lindex $kd 4] + } else { + set nearerKD [lindex $kd 4] + set furtherKD [lindex $kd 3] + } + + lassign [my FN $nearerKD $target $maxDist2] nearest dist2 count + incr nodesVisited $count + + if {$dist2 < $maxDist2} { + set maxDist2 $dist2 + } + set d2 [expr {([lindex $pivot $s]-[lindex $target $s])**2}] + if {$d2 > $maxDist2} { + return [list $nearest $dist2 $nodesVisited] + } + set d2 0.0 + foreach pp $pivot tp $target {set d2 [expr {$d2+($pp-$tp)**2}]} + if {$d2 < $dist2} { + set nearest $pivot + set maxDist2 [set dist2 $d2] + } + + lassign [my FN $furtherKD $target $maxDist2] fNearest fDist2 count + incr nodesVisited $count + if {$fDist2 < $dist2} { + set nearest $fNearest + set dist2 $fDist2 + } + + return [list $nearest $dist2 $nodesVisited] + } +} diff --git a/Task/K-d-tree/Tcl/k-d-tree-2.tcl b/Task/K-d-tree/Tcl/k-d-tree-2.tcl new file mode 100644 index 0000000000..d2bb625113 --- /dev/null +++ b/Task/K-d-tree/Tcl/k-d-tree-2.tcl @@ -0,0 +1,37 @@ +proc showNearest {heading tree point} { + puts ${heading}: + puts "Point: \[[join $point ,]\]" + lassign [$tree findNearest $point] nearest distance count + puts "Nearest neighbor: \[[join $nearest ,]\]" + puts "Distance: $distance" + puts "Nodes visited: $count" +} +proc randomPoint k { + for {set j 0} {$j < $k} {incr j} {lappend p [::tcl::mathfunc::rand]} + return $p +} +proc randomPoints {k n} { + for {set i 0} {$i < $n} {incr i} { + set p {} + for {set j 0} {$j < $k} {incr j} { + lappend p [::tcl::mathfunc::rand] + } + lappend ps $p + } + return $ps +} + +KDTree create kd1 {{2 3} {5 4} {9 6} {4 7} {8 1} {7 2}} +showNearest "Wikipedia example data" kd1 {9 2} +puts "" + +set N 1000 +set t [time {KDTree create kd2 [randomPoints 3 $N]}] +showNearest "k-d tree with $N random 3D points (generation time: [lindex $t 0] us)" kd2 [randomPoint 3] +kd2 destroy +puts "" + +set N 1000000 +set t [time {KDTree create kd2 [randomPoints 3 $N]}] +showNearest "k-d tree with $N random 3D points (generation time: [lindex $t 0] us)" kd2 [randomPoint 3] +puts "Search time: [time {kd2 findNearest [randomPoint 3]} 10000]" diff --git a/Task/Left-factorials/00DESCRIPTION b/Task/Left-factorials/00DESCRIPTION new file mode 100644 index 0000000000..b14535784b --- /dev/null +++ b/Task/Left-factorials/00DESCRIPTION @@ -0,0 +1,23 @@ +''Left factorials'', !n, may refer to either ''subfactorials'' or to ''factorial sums''; +the same notation can be confusingly seen used for the two different definitions. + +Sometimes, ''subfactorials'' (also known as ''derangements'') use any of the notations: +:::::::*   !''n''` +:::::::*   !n' +:::::::*   ''n''¡ + +
This Rosetta Code task will be using this formula for ''left factorial'': +: !n = \sum_{k=0}^{n-1} k! +where +:!0 = 0 +;Task +Display the left factorials for: +* zero through ten (inclusive) +* 20 through 110 (inclusive) by tens +Display the length (in decimal digits) of the left factorials for: +* 1,000,   2,000   through   10,000   (inclusive), by thousands. +;Also see +* The OEIS entry: [[http://oeis.org/A003422 A003422 left factorials]] +* The MathWorld entry: [[http://mathworld.wolfram.com/LeftFactorial.html left factorial]] +* The MathWorld entry: [[http://mathworld.wolfram.com/FactorialSums.html factorial sums]] +* The MathWorld entry: [[http://mathworld.wolfram.com/Subfactorial.html subfactorial]] diff --git a/Task/Left-factorials/00META.yaml b/Task/Left-factorials/00META.yaml new file mode 100644 index 0000000000..0b1db4d460 --- /dev/null +++ b/Task/Left-factorials/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Mathematics diff --git a/Task/Left-factorials/Bracmat/left-factorials.bracmat b/Task/Left-factorials/Bracmat/left-factorials.bracmat new file mode 100644 index 0000000000..ea0fd41c3e --- /dev/null +++ b/Task/Left-factorials/Bracmat/left-factorials.bracmat @@ -0,0 +1,37 @@ +( ( leftFact + = result factorial i + . 0:?result + & 1:?factorial + & 0:?i + & whl + ' ( !i+1:~>!arg:?i + & !factorial+!result:?result + & !factorial*!i:?factorial + ) + & !result + ) +& ( iterate + = from to step c fun + . !arg:(?from.?to.?step.?fun) + & !from+-1*!step:?from + & !step:?c + & whl + ' ( !step+!from:~>!to:?from + & !fun$(leftFact$!from) + ) + & + ) +& out$"First 11 left factorials:" +& iterate$(0.10.1.out) +& out$" +20 through 110 (inclusive) by tens:" +& iterate$(20.110.10.out) +& out$" +Digits in 1,000 through 10,000 by thousands:" +& iterate + $ ( 1000 + . 10000 + . 1000 + . (=L.@(!arg:? [?L)&out$!L) + ) +) diff --git a/Task/Left-factorials/C/left-factorials.c b/Task/Left-factorials/C/left-factorials.c new file mode 100644 index 0000000000..3e5ccc72bc --- /dev/null +++ b/Task/Left-factorials/C/left-factorials.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include + +void mpz_left_fac_ui(mpz_t rop, unsigned long op) +{ + mpz_t t1; + mpz_init_set_ui(t1, 1); + mpz_set_ui(rop, 0); + + size_t i; + for (i = 1; i <= op; ++i) { + mpz_add(rop, rop, t1); + mpz_mul_ui(t1, t1, i); + } + + mpz_clear(t1); +} + +size_t mpz_digitcount(mpz_t op) +{ + /* mpz_sizeinbase can not be trusted to give accurate base 10 length */ + char *t = mpz_get_str(NULL, 10, op); + size_t ret = strlen(t); + free(t); + return ret; +} + +int main(void) +{ + mpz_t t; + mpz_init(t); + size_t i; + + for (i = 0; i <= 110; ++i) { + if (i <= 10 || i % 10 == 0) { + mpz_left_fac_ui(t, i); + gmp_printf("!%u = %Zd\n", i, t); + } + } + + for (i = 1000; i <= 10000; i += 1000) { + mpz_left_fac_ui(t, i); + printf("!%u has %u digits\n", i, mpz_digitcount(t)); + } + + mpz_clear(t); + return 0; +} diff --git a/Task/Left-factorials/D/left-factorials.d b/Task/Left-factorials/D/left-factorials.d new file mode 100644 index 0000000000..abe0b84dd2 --- /dev/null +++ b/Task/Left-factorials/D/left-factorials.d @@ -0,0 +1,18 @@ +import std.stdio, std.bigint, std.range, std.algorithm, std.conv; + +BigInt leftFact(in uint n) pure nothrow /*@safe*/ { + BigInt result = 0, factorial = 1; + foreach (immutable i; 1 .. n + 1) { + result += factorial; + factorial *= i; + } + return result; +} + +void main() { + writeln("First 11 left factorials:\n", 11.iota.map!leftFact); + writefln("\n20 through 110 (inclusive) by tens:\n%(%s\n%)", + iota(20, 111, 10).map!leftFact); + writefln("\nDigits in 1,000 through 10,000 by thousands:\n%s", + iota(1_000, 10_001, 1_000).map!(i => i.leftFact.text.length)); +} diff --git a/Task/Left-factorials/Go/left-factorials.go b/Task/Left-factorials/Go/left-factorials.go new file mode 100644 index 0000000000..9f6517a8d1 --- /dev/null +++ b/Task/Left-factorials/Go/left-factorials.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + fmt.Print("!0 through !10: 0") + one := big.NewInt(1) + n := big.NewInt(1) + f := big.NewInt(1) + l := big.NewInt(1) + next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } + for ; ; next() { + fmt.Print(" ", l) + if n.Int64() == 10 { + break + } + } + fmt.Println() + for { + for i := 0; i < 10; i++ { + next() + } + fmt.Printf("!%d: %d\n", n, l) + if n.Int64() == 110 { + break + } + } + fmt.Println("Lengths of !1000 through !10000 by thousands:") + for i := 110; i < 1000; i++ { + next() + } + for { + fmt.Print(" ", len(l.String())) + if n.Int64() == 10000 { + break + } + for i := 0; i < 1000; i++ { + next() + } + } + fmt.Println() +} diff --git a/Task/Left-factorials/Haskell/left-factorials.hs b/Task/Left-factorials/Haskell/left-factorials.hs new file mode 100644 index 0000000000..b620176c8e --- /dev/null +++ b/Task/Left-factorials/Haskell/left-factorials.hs @@ -0,0 +1,18 @@ +fact :: [Integer] +fact = scanl (*) 1 [1..] + +leftFact :: [Integer] +leftFact = scanl (+) 0 fact + +main = do + putStrLn "0 ~ 10:" + putStrLn $ show $ map (\n -> leftFact !! n) [0..10] + putStrLn "" + + putStrLn "20 ~ 110 by tens:" + putStrLn $ unlines $ map show $ map (\n -> leftFact !! n) [20,30..110] + putStrLn "" + + putStrLn "length of 1,000 ~ 10,000 by thousands:" + putStrLn $ show $ map (\n -> length $ show $ leftFact !! n) [1000,2000..10000] + putStrLn "" diff --git a/Task/Left-factorials/Icon/left-factorials.icon b/Task/Left-factorials/Icon/left-factorials.icon new file mode 100644 index 0000000000..e047ef9550 --- /dev/null +++ b/Task/Left-factorials/Icon/left-factorials.icon @@ -0,0 +1,16 @@ +procedure main() + every writes(lfact(0 | !10)," ") + write() + write() + every write(lfact(20 to 110 by 10)) + write() + every writes(*lfact(1000 to 10000 by 1000)," ") + write() +end + +procedure lfact(n) + r := 0 + f := 1 + every (i := !n, r +:= .f, f *:= .i) + return r +end diff --git a/Task/Left-factorials/J/left-factorials-1.j b/Task/Left-factorials/J/left-factorials-1.j new file mode 100644 index 0000000000..67643bad54 --- /dev/null +++ b/Task/Left-factorials/J/left-factorials-1.j @@ -0,0 +1 @@ +leftFact=: +/@:!@i."0 diff --git a/Task/Left-factorials/J/left-factorials-2.j b/Task/Left-factorials/J/left-factorials-2.j new file mode 100644 index 0000000000..573683c887 --- /dev/null +++ b/Task/Left-factorials/J/left-factorials-2.j @@ -0,0 +1,34 @@ + (,. leftFact) i.11 + 0 0 + 1 1 + 2 2 + 3 4 + 4 10 + 5 34 + 6 154 + 7 874 + 8 5914 + 9 46234 +10 409114 + (,. leftFact) 10*2+i.10x + 20 128425485935180314 + 30 9157958657951075573395300940314 + 40 20935051082417771847631371547939998232420940314 + 50 620960027832821612639424806694551108812720525606160920420940314 + 60 141074930726669571000530822087000522211656242116439949000980378746128920420940314 + 70 173639511802987526699717162409282876065556519849603157850853034644815111221599509216528920420940314 + 80 906089587987695346534516804650290637694024830011956365184327674619752094289696314882008531991840922336528920420940314 + 90 16695570072624210767034167688394623360733515163575864136345910335924039962404869510225723072235842668787507993136908442336528920420940314 +100 942786239765826579160595268206839381354754349601050974345395410407078230249590414458830117442618180732911203520208889371641659121356556442336528920420940314 +110 145722981061585297004706728001906071948635199234860720988658042536179281328615541936083296163475394237524337422204397431927131629058103519228197429698252556442336528920420940314 + (,. #@":@leftFact) 1000*1+i.10x + 1000 2565 + 2000 5733 + 3000 9128 + 4000 12670 + 5000 16322 + 6000 20062 + 7000 23875 + 8000 27749 + 9000 31678 +10000 35656 diff --git a/Task/Left-factorials/Java/left-factorials.java b/Task/Left-factorials/Java/left-factorials.java new file mode 100644 index 0000000000..09ed00c2f8 --- /dev/null +++ b/Task/Left-factorials/Java/left-factorials.java @@ -0,0 +1,33 @@ +import java.math.BigInteger; + +public class LeftFac{ + public static BigInteger factorial(BigInteger n){ + BigInteger ans = BigInteger.ONE; + for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ + ans = ans.multiply(x); + } + return ans; + } + + public static BigInteger leftFact(BigInteger n){ + BigInteger ans = BigInteger.ZERO; + for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){ + ans = ans.add(factorial(k)); + } + return ans; + } + + public static void main(String[] args){ + for(int i = 0; i <= 10; i++){ + System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); + } + + for(int i = 20; i <= 110; i += 10){ + System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); + } + + for(int i = 1000; i <= 10000; i += 1000){ + System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits"); + } + } +} diff --git a/Task/Left-factorials/Julia/left-factorials.julia b/Task/Left-factorials/Julia/left-factorials.julia new file mode 100644 index 0000000000..d907f835ca --- /dev/null +++ b/Task/Left-factorials/Julia/left-factorials.julia @@ -0,0 +1,2 @@ +leftfactorial(n::Integer) = n <= 0 ? zero(n) : sum(factorial, 0:n-1) +@vectorize_1arg Integer leftfactorial diff --git a/Task/Left-factorials/Mathematica/left-factorials.math b/Task/Left-factorials/Mathematica/left-factorials.math new file mode 100644 index 0000000000..94db53d593 --- /dev/null +++ b/Task/Left-factorials/Mathematica/left-factorials.math @@ -0,0 +1,7 @@ +left[n_] := left[n] = Sum[k!, {k, 0, n - 1}] +Print["left factorials 0 through 10:"] +Print[left /@ Range[0, 10] // TableForm] +Print["left factorials 20 through 110, by tens:"] +Print[left /@ Range[20, 110, 10] // TableForm] +Print["Digits in left factorials 1,000 through 10,000, by thousands:"] +Print[Length[IntegerDigits[left[#]]] & /@ Range[1000, 10000, 1000] // TableForm] diff --git a/Task/Left-factorials/PARI-GP/left-factorials.pari b/Task/Left-factorials/PARI-GP/left-factorials.pari new file mode 100644 index 0000000000..26c5c82187 --- /dev/null +++ b/Task/Left-factorials/PARI-GP/left-factorials.pari @@ -0,0 +1,4 @@ +lf(n)=sum(k=0,n-1,k!); +apply(lf, [0..10]) +apply(lf, 10*[2..11]) +forstep(n=1000,1e4,1000,print1(#digits(lf(n))", ")) diff --git a/Task/Left-factorials/PL-I/left-factorials.pli b/Task/Left-factorials/PL-I/left-factorials.pli new file mode 100644 index 0000000000..ada379c0d6 --- /dev/null +++ b/Task/Left-factorials/PL-I/left-factorials.pli @@ -0,0 +1,23 @@ +lf: procedure (n) returns (fixed decimal (31) ); + declare n fixed binary; + declare (s, f) fixed (31); + declare (i, j) fixed; + + s = 0; + do i = n-1 to 0 by -1; + f = 1; + do j = i to 1 by -1; + f = f * j; + end; + s = s + f; + end; + return (s); +end lf; + + declare n fixed binary; + + do n = 0 to 10, 20 to 30; + put skip list ('Left factorial of ' || n || '=' || lf(n) ); + end; + +end left_factorials; diff --git a/Task/Left-factorials/Perl-6/left-factorials-1.pl6 b/Task/Left-factorials/Perl-6/left-factorials-1.pl6 new file mode 100644 index 0000000000..58ec27cdad --- /dev/null +++ b/Task/Left-factorials/Perl-6/left-factorials-1.pl6 @@ -0,0 +1,7 @@ +multi sub postfix: (0) { 1 }; +multi sub postfix: ($n) { [*] 1 .. $n }; +multi sub prefix: (0) { 0 }; +multi sub prefix: ($k) { [+] (^$k).map: { $_! } } + +printf "!%d = %s\n", $_, !$_ for ^11, 20, 30 ... 110; +printf "!%d has %d digits.\n", $_, (!$_).chars for 1000, 2000 ... 10000; diff --git a/Task/Left-factorials/Perl-6/left-factorials-2.pl6 b/Task/Left-factorials/Perl-6/left-factorials-2.pl6 new file mode 100644 index 0000000000..2da1ed35e8 --- /dev/null +++ b/Task/Left-factorials/Perl-6/left-factorials-2.pl6 @@ -0,0 +1,5 @@ +constant fact = 1, [\*] 1..*; +constant leftfact = 0, [\+] fact; + +printf "!%d = %s\n", $_, leftfact[$_] for 0 ... 10, 20 ... 110; +printf "!%d has %d digits.\n", $_, leftfact[$_].chars for 1000, 2000 ... 10000; diff --git a/Task/Left-factorials/Perl-6/left-factorials-3.pl6 b/Task/Left-factorials/Perl-6/left-factorials-3.pl6 new file mode 100644 index 0000000000..5ba09e939b --- /dev/null +++ b/Task/Left-factorials/Perl-6/left-factorials-3.pl6 @@ -0,0 +1 @@ +constant leftfact = 0, [\+] 1, [\*] 1..*; diff --git a/Task/Left-factorials/Perl/left-factorials.pl b/Task/Left-factorials/Perl/left-factorials.pl new file mode 100644 index 0000000000..afaab56e2c --- /dev/null +++ b/Task/Left-factorials/Perl/left-factorials.pl @@ -0,0 +1,23 @@ +#!perl +use 5.010; +use strict; +use warnings; +use bigint; + +sub leftfact { + my ($n) = @_; + state $cached = 0; + state $factorial = 1; + state $leftfact = 0; + if( $n < $cached ) { + ($cached, $factorial, $leftfact) = (0, 1, 0); + } + while( $n > $cached ) { + $leftfact += $factorial; + $factorial *= ++$cached; + } + return $leftfact; +} + +printf "!%d = %s\n", $_, leftfact($_) for 0 .. 10, map $_*10, 2..11; +printf "!%d has %d digits.\n", $_, length leftfact($_) for map $_*1000, 1..10; diff --git a/Task/Left-factorials/Python/left-factorials.py b/Task/Left-factorials/Python/left-factorials.py new file mode 100644 index 0000000000..3b36c04cc1 --- /dev/null +++ b/Task/Left-factorials/Python/left-factorials.py @@ -0,0 +1,15 @@ +from itertools import islice + +def lfact(): + yield 0 + fact, summ, n = 1, 0, 1 + while 1: + fact, summ, n = fact*n, summ + fact, n + 1 + yield summ + +print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())]) +print('20 through 110 (inclusive) by tens:') +for lf in islice(lfact(), 20, 111, 10): + print(lf) +print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r' + % [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] ) diff --git a/Task/Left-factorials/README b/Task/Left-factorials/README new file mode 100644 index 0000000000..c4f1d70b10 --- /dev/null +++ b/Task/Left-factorials/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Left_factorials diff --git a/Task/Left-factorials/REXX/left-factorials.rexx b/Task/Left-factorials/REXX/left-factorials.rexx new file mode 100644 index 0000000000..897ec66a71 --- /dev/null +++ b/Task/Left-factorials/REXX/left-factorials.rexx @@ -0,0 +1,22 @@ +/*REXX pgm computes/shows the left factorial (or width) of N (or range).*/ +parse arg bot top inc . /*obtain optional args from C.L. */ +if bot=='' then bot=1 /*BOT defined? Then use default.*/ +td= bot<0 /*if BOT < 0, only show # digs.*/ +bot=abs(bot) /*use the |bot| for the DO loop.*/ +if top=='' then top=bot /* " " top " " " " */ +if inc='' then inc=1 /* " " inc " " " " */ +@='left ! of ' /*a literal used in the display. */ +w=length(H) /*width of largest number request*/ + do j=bot to top by inc /*traipse through #'s requested.*/ + if td then say @ right(j,w) " ───► " length(L!(j)) ' digits' + else say @ right(j,w) " ───► " L!(j) + end /*j*/ /* [↑] show either L! or #digits*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────L! subroutine───────────────────────*/ +L!: procedure; parse arg x .; if x<3 then return x; s=4 /*shortcuts.*/ +!=2; do f=3 to x-1 /*compute L! for all numbers───►X*/ + !=!*f /*compute intermediate factorial.*/ + if pos(.,!)\==0 then numeric digits digits()*1.5%1 /*bump digs.*/ + s=s+! /*add the factorial ───► L! sum.*/ + end /*f*/ /* [↑] handles gi-hugeic numbers*/ +return s /*return the sum (L!) to invoker.*/ diff --git a/Task/Left-factorials/Racket/left-factorials.rkt b/Task/Left-factorials/Racket/left-factorials.rkt new file mode 100644 index 0000000000..5562d70bfe --- /dev/null +++ b/Task/Left-factorials/Racket/left-factorials.rkt @@ -0,0 +1,17 @@ +#lang racket +(define ! (let ((rv# (make-hash))) (λ (n) (hash-ref! rv# n (λ () (if (= n 0) 1 (* n (! (- n 1))))))))) + +(define (!n n) + ;; note that in-range n is from 0 to n-1 inclusive + (for/sum ((k (in-range n))) (! k))) + +(define (dnl. s) (for-each displayln s)) +(dnl + "Display the left factorials for:" + "zero through ten (inclusive)" + (pretty-format (for/list ((i (in-range 0 (add1 10)))) (!n i))) + "20 through 110 (inclusive) by tens" + (pretty-format (for/list ((i (in-range 20 (add1 110) 10))) (!n i))) + "Display the length (in decimal digits) of the left factorials for:" + "1,000, 2,000 through 10,000 (inclusive), by thousands." + (pretty-format (for/list ((i (in-range 1000 10001 1000))) (add1 (order-of-magnitude (!n i)))))) diff --git a/Task/Left-factorials/Ruby/left-factorials-1.rb b/Task/Left-factorials/Ruby/left-factorials-1.rb new file mode 100644 index 0000000000..68635d71a1 --- /dev/null +++ b/Task/Left-factorials/Ruby/left-factorials-1.rb @@ -0,0 +1,9 @@ +left_fact = Enumerator.new do |y| + n, f, lf = 0, 1, 0 + loop do + y << lf #yield left_factorial + n += 1 + lf += f + f *= n + end +end diff --git a/Task/Left-factorials/Ruby/left-factorials-2.rb b/Task/Left-factorials/Ruby/left-factorials-2.rb new file mode 100644 index 0000000000..954affba9e --- /dev/null +++ b/Task/Left-factorials/Ruby/left-factorials-2.rb @@ -0,0 +1,8 @@ +left_fact = Enumerator.new do |y| + f, lf = 1, 0 + 1.step do |n| + y << lf #yield left_factorial + lf += f + f *= n + end +end diff --git a/Task/Left-factorials/Ruby/left-factorials-3.rb b/Task/Left-factorials/Ruby/left-factorials-3.rb new file mode 100644 index 0000000000..06272f27cf --- /dev/null +++ b/Task/Left-factorials/Ruby/left-factorials-3.rb @@ -0,0 +1,12 @@ +tens = 20.step(110, 10) +thousands = 1000.step(10_000, 1000) + +10001.times do |n| + lf = left_fact.next + case n + when 0..10, *tens + puts "!#{n} = #{lf}" + when *thousands + puts "!#{n} has #{lf.to_s.size} digits" + end +end diff --git a/Task/Left-factorials/Seed7/left-factorials.seed7 b/Task/Left-factorials/Seed7/left-factorials.seed7 new file mode 100644 index 0000000000..d99531e2f7 --- /dev/null +++ b/Task/Left-factorials/Seed7/left-factorials.seed7 @@ -0,0 +1,36 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const func bigInteger: leftFact (in integer: n) is func + result + var bigInteger: leftFact is 0_; + local + var bigInteger: factorial is 1_; + var integer: i is 0; + begin + for i range 1 to n do + leftFact +:= factorial; + factorial *:= bigInteger conv i; + end for; + end func; + +const proc: main is func + local + var integer: n is 0; + begin + writeln("First 11 left factorials:"); + for n range 0 to 10 do + write(" " <& leftFact(n)); + end for; + writeln; + writeln("20 through 110 (inclusive) by tens:"); + for n range 20 to 110 step 10 do + writeln(leftFact(n)); + end for; + writeln; + writeln("Digits in 1,000 through 10,000 by thousands:"); + for n range 1000 to 10000 step 1000 do + writeln(length(str(leftFact(n)))); + end for; + writeln; + end func; diff --git a/Task/Left-factorials/Tcl/left-factorials.tcl b/Task/Left-factorials/Tcl/left-factorials.tcl new file mode 100644 index 0000000000..0b085a042b --- /dev/null +++ b/Task/Left-factorials/Tcl/left-factorials.tcl @@ -0,0 +1,15 @@ +proc leftfact {n} { + set s 0 + for {set i [set f 1]} {$i <= $n} {incr i} { + incr s $f + set f [expr {$f * $i}] + } + return $s +} + +for {set i 0} {$i <= 110} {incr i [expr {$i>9?10:1}]} { + puts "!$i = [leftfact $i]" +} +for {set i 1000} {$i <= 10000} {incr i 1000} { + puts "!$i has [string length [leftfact $i]] digits" +} diff --git a/Task/Longest-increasing-subsequence/00DESCRIPTION b/Task/Longest-increasing-subsequence/00DESCRIPTION new file mode 100644 index 0000000000..93e4f05c0c --- /dev/null +++ b/Task/Longest-increasing-subsequence/00DESCRIPTION @@ -0,0 +1,10 @@ +Calculate and show here a [[wp:Longest increasing subsequence|longest increasing subsequence]] of the list: +:\{3, 2, 6, 4, 5, 1\} +And of the list: +:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} + +Note that a list may have more than one subsequence that is of the maximum length. + +;Ref: +# [http://www.youtube.com/watch?v=4fQJGoeW5VE Dynamic Programming #1: Longest Increasing Subsequence] on Youtube +# An efficient solution can be based on [[wp:Patience sorting|Patience sorting]]. diff --git a/Task/Longest-increasing-subsequence/AutoHotkey/longest-increasing-subsequence.ahk b/Task/Longest-increasing-subsequence/AutoHotkey/longest-increasing-subsequence.ahk new file mode 100644 index 0000000000..485f0efaee --- /dev/null +++ b/Task/Longest-increasing-subsequence/AutoHotkey/longest-increasing-subsequence.ahk @@ -0,0 +1,22 @@ +Lists := [[3,2,6,4,5,1], [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]] + +for k, v in Lists { + D := LIS(v) + MsgBox, % D[D.I].seq +} + +LIS(L) { + D := [] + for i, v in L { + D[i, "Length"] := 1, D[i, "Seq"] := v, D[i, "Val"] := v + Loop, % i - 1 { + if(D[A_Index].Val < v && D[A_Index].Length + 1 > D[i].Length) { + D[i].Length := D[A_Index].Length + 1 + D[i].Seq := D[A_Index].Seq ", " v + if (D[i].Length > MaxLength) + MaxLength := D[i].Length, D.I := i + } + } + } + return, D +} diff --git a/Task/Longest-increasing-subsequence/C++/longest-increasing-subsequence.cpp b/Task/Longest-increasing-subsequence/C++/longest-increasing-subsequence.cpp new file mode 100644 index 0000000000..8ee373506c --- /dev/null +++ b/Task/Longest-increasing-subsequence/C++/longest-increasing-subsequence.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +template +struct Node { + E value; + std::tr1::shared_ptr > pointer; +}; + +template +struct node_ptr_less { + bool operator()(const std::tr1::shared_ptr > &node1, + const std::tr1::shared_ptr > &node2) const { + return node1->value < node2->value; + } +}; + + +template +std::vector lis(const std::vector &n) { + typedef std::tr1::shared_ptr > NodePtr; + + std::vector pileTops; + // sort into piles + for (typename std::vector::const_iterator it = n.begin(); it != n.end(); it++) { + NodePtr node(new Node()); + node->value = *it; + typename std::vector::iterator j = + std::lower_bound(pileTops.begin(), pileTops.end(), node, node_ptr_less()); + if (j != pileTops.begin()) + node->pointer = *(j-1); + if (j != pileTops.end()) + *j = node; + else + pileTops.push_back(node); + } + // extract LIS from piles + std::vector result; + for (NodePtr node = pileTops.back(); node != NULL; node = node->pointer) + result.push_back(node->value); + std::reverse(result.begin(), result.end()); + return result; +} + +int main() { + int arr1[] = {3,2,6,4,5,1}; + std::vector vec1(arr1, arr1 + sizeof(arr1)/sizeof(*arr1)); + std::vector result1 = lis(vec1); + std::copy(result1.begin(), result1.end(), std::ostream_iterator(std::cout, ", ")); + std::cout << std::endl; + + int arr2[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; + std::vector vec2(arr2, arr2 + sizeof(arr2)/sizeof(*arr2)); + std::vector result2 = lis(vec2); + std::copy(result2.begin(), result2.end(), std::ostream_iterator(std::cout, ", ")); + std::cout << std::endl; + return 0; +} diff --git a/Task/Longest-increasing-subsequence/C/longest-increasing-subsequence.c b/Task/Longest-increasing-subsequence/C/longest-increasing-subsequence.c new file mode 100644 index 0000000000..54d43049ab --- /dev/null +++ b/Task/Longest-increasing-subsequence/C/longest-increasing-subsequence.c @@ -0,0 +1,44 @@ +#include +#include + +struct node { + int val, len; + struct node *next; +}; + +void lis(int *v, int len) +{ + int i; + struct node *p, *n = calloc(len, sizeof *n); + for (i = 0; i < len; i++) + n[i].val = v[i]; + + for (i = len; i--; ) { + // find longest chain that can follow n[i] + for (p = n + i; p++ < n + len; ) { + if (p->val > n[i].val && p->len >= n[i].len) { + n[i].next = p; + n[i].len = p->len + 1; + } + } + } + + // find longest chain + for (i = 0, p = n; i < len; i++) + if (n[i].len > p->len) p = n + i; + + do printf(" %d", p->val); while ((p = p->next)); + putchar('\n'); + + free(n); +} + +int main(void) +{ + int x[] = { 3, 2, 6, 4, 5, 1 }; + int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; + + lis(x, sizeof(x) / sizeof(int)); + lis(y, sizeof(y) / sizeof(int)); + return 0; +} diff --git a/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-1.clj b/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-1.clj new file mode 100644 index 0000000000..1128044ed4 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-1.clj @@ -0,0 +1,12 @@ +(defn place [piles card] + (let [[les gts] (->> piles (split-with #(<= (ffirst %) card))) + newelem (cons card (->> les last first)) + modpile (cons newelem (first gts))] + (concat les (cons modpile (rest gts))))) + +(defn a-longest [cards] + (let [piles (reduce place '() cards)] + (->> piles last first reverse))) + +(println (a-longest [3 2 6 4 5 1])) +(println (a-longest [0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15])) diff --git a/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-2.clj b/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-2.clj new file mode 100644 index 0000000000..8318f79063 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Clojure/longest-increasing-subsequence-2.clj @@ -0,0 +1,2 @@ +(2 4 5) +(0 2 6 9 11 15) diff --git a/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-1.lisp b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-1.lisp new file mode 100644 index 0000000000..cfb34bb647 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-1.lisp @@ -0,0 +1,20 @@ +(defun longest-increasing-subseq (list) + (let ((subseqs nil)) + (dolist (item list) + (let ((longest-so-far (longest-list-in-lists (remove-if-not #'(lambda (l) (> item (car l))) subseqs)))) + (push (cons item longest-so-far) subseqs))) + (reverse (longest-list-in-lists subseqs)))) + +(defun longest-list-in-lists (lists) + (let ((longest nil) + (longest-len 0)) + (dolist (list lists) + (let ((len (length list))) + (when (> len longest-len) + (setf longest list + longest-len len)))) + longest)) + +(dolist (l (list (list 3 2 6 4 5 1) + (list 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))) + (format t "~A~%" (longest-increasing-subseq l)))) diff --git a/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-2.lisp b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-2.lisp new file mode 100644 index 0000000000..4c557db5e0 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-2.lisp @@ -0,0 +1,23 @@ +(defun lis-patience-sort (input-list) + (let ((piles nil)) + (dolist (item input-list) + (setf piles (insert-item item piles))) + (reverse (caar (last piles))))) + +(defun insert-item (item piles) + (let ((not-found t)) + (loop + while not-found + for pile in piles + and prev = nil then pile + and i from 0 + do (when (<= item (caar pile)) + (setf (elt piles i) (push (cons item (car prev)) (elt piles i)) + not-found nil))) + (if not-found + (append piles (list (list (cons item (caar (last piles)))))) + piles))) + +(dolist (l (list (list 3 2 6 4 5 1) + (list 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))) + (format t "~A~%" (lis-patience-sort l))) diff --git a/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-3.lisp b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-3.lisp new file mode 100644 index 0000000000..03705ad8c5 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Common-Lisp/longest-increasing-subsequence-3.lisp @@ -0,0 +1,20 @@ +(defun insert-item (item piles) + (multiple-value-bind + (i prev) + (do* ((prev nil (car x)) + (x piles (cdr x)) + (i 0 (1+ i))) + ((or (null x) (<= item (caaar x))) (values i prev))) + (if (= i (length piles)) + (append piles (list (list (cons item (caar (last piles)))))) + (progn (push (cons item (car prev)) (elt piles i)) + piles)))) + +(defun longest-inc-seq (input) + (do* ((piles nil (insert-item (car x) piles)) + (x input (cdr x))) + ((null x) (reverse (caar (last piles)))))) + +(dolist (l (list (list 3 2 6 4 5 1) + (list 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))) + (format t "~A~%" (longest-inc-seq l))) diff --git a/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-1.d b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-1.d new file mode 100644 index 0000000000..f8c0a9a8fe --- /dev/null +++ b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-1.d @@ -0,0 +1,15 @@ +import std.stdio, std.algorithm, power_set2; + +T[] lis(T)(T[] items) pure nothrow { + //return items.powerSet.filter!isSorted.max!q{ a.length }; + return items + .powerSet + .filter!isSorted + .minPos!q{ a.length > b.length } + .front; +} + +void main() { + [3, 2, 6, 4, 5, 1].lis.writeln; + [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15].lis.writeln; +} diff --git a/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-2.d b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-2.d new file mode 100644 index 0000000000..1731d6b384 --- /dev/null +++ b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-2.d @@ -0,0 +1,38 @@ +import std.stdio, std.algorithm, std.array; + +/// Return one of the Longest Increasing Subsequence of +/// items using patience sorting. +T[] lis(T)(in T[] items) pure nothrow +if (__traits(compiles, T.init < T.init)) +out(result) { + assert(result.length <= items.length); + assert(result.isSorted); + assert(result.all!(x => items.canFind(x))); +} body { + if (items.empty) + return null; + + static struct Node { T val; Node* back; } + auto pile = [[new Node(items[0])]]; + + OUTER: foreach (immutable di; items[1 .. $]) { + foreach (immutable j, ref pj; pile) + if (pj[$ - 1].val > di) { + pj ~= new Node(di, j ? pile[j - 1][$ - 1] : null); + continue OUTER; + } + pile ~= [new Node(di, pile[$ - 1][$ - 1])]; + } + + T[] result; + for (auto ptr = pile[$ - 1][$ - 1]; ptr != null; ptr = ptr.back) + result ~= ptr.val; + result.reverse(); + return result; +} + +void main() { + foreach (d; [[3,2,6,4,5,1], + [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]]) + d.lis.writeln; +} diff --git a/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-3.d b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-3.d new file mode 100644 index 0000000000..dc7e8755dc --- /dev/null +++ b/Task/Longest-increasing-subsequence/D/longest-increasing-subsequence-3.d @@ -0,0 +1,50 @@ +import std.stdio, std.algorithm, std.range, std.array; + +T[] lis(T)(in T[] items) pure nothrow +if (__traits(compiles, T.init < T.init)) +out(result) { + assert(result.length <= items.length); + assert(result.isSorted); + assert(result.all!(x => items.canFind(x))); +} body { + if (items.empty) + return null; + + static struct Node { + T value; + Node* pointer; + } + Node*[] pileTops; + auto nodes = minimallyInitializedArray!(Node[])(items.length); + + // Sort into piles. + foreach (idx, x; items) { + auto node = &nodes[idx]; + node.value = x; + immutable i = pileTops.length - + pileTops.assumeSorted!q{a.value < b.value} + .upperBound(node) + .length; + if (i != 0) + node.pointer = pileTops[i - 1]; + if (i != pileTops.length) + pileTops[i] = node; + else + pileTops ~= node; + } + + // Extract LIS from nodes. + size_t count = 0; + for (auto n = pileTops[$ - 1]; n != null; n = n.pointer) + count++; + auto result = minimallyInitializedArray!(T[])(count); + for (auto n = pileTops[$ - 1]; n != null; n = n.pointer) + result[--count] = n.value; + return result; +} + +void main() { + foreach (d; [[3,2,6,4,5,1], + [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]]) + d.writeln; +} diff --git a/Task/Longest-increasing-subsequence/Deja-Vu/longest-increasing-subsequence.djv b/Task/Longest-increasing-subsequence/Deja-Vu/longest-increasing-subsequence.djv new file mode 100644 index 0000000000..7bb2028859 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Deja-Vu/longest-increasing-subsequence.djv @@ -0,0 +1,25 @@ +in-pair: + if = :nil dup: + false drop + else: + @in-pair &> swap &< dup + +get-last lst: + get-from lst -- len lst + +lis-sub pile i di: + for j range 0 -- len pile: + local :pj get-from pile j + if > &< get-last pj di: + push-to pj & di if j get-last get-from pile -- j :nil + return + push-to pile [ & di get-last get-last pile ] + +lis d: + local :pile [ [ & get-from d 0 :nil ] ] + for i range 1 -- len d: + lis-sub pile i get-from d i + [ for in-pair get-last get-last pile ] + +!. lis [ 3 2 6 4 5 1 ] +!. lis [ 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 ] diff --git a/Task/Longest-increasing-subsequence/Go/longest-increasing-subsequence.go b/Task/Longest-increasing-subsequence/Go/longest-increasing-subsequence.go new file mode 100644 index 0000000000..346acf0cd8 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Go/longest-increasing-subsequence.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "sort" +) + +type Node struct { + val int + back *Node +} + +func lis (n []int) (result []int) { + var pileTops []*Node + // sort into piles + for _, x := range n { + j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) + node := &Node{ x, nil } + if j != 0 { node.back = pileTops[j-1] } + if j != len(pileTops) { + pileTops[j] = node + } else { + pileTops = append(pileTops, node) + } + } + + if len(pileTops) == 0 { return []int{} } + for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { + result = append(result, node.val) + } + // reverse + for i := 0; i < len(result)/2; i++ { + result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] + } + return +} + +func main() { + for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, + {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { + fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) + } +} diff --git a/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-1.hs b/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-1.hs new file mode 100644 index 0000000000..87a73febd6 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-1.hs @@ -0,0 +1,12 @@ +import Data.Ord ( comparing ) +import Data.List ( maximumBy, subsequences ) +import Data.List.Ordered ( isSorted, nub ) + +lis :: Ord a => [a] -> [a] +lis = maximumBy (comparing length) . map nub . filter isSorted . subsequences +-- longest <-- unique <-- increasing <-- all + +main = do + print $ lis [3,2,6,4,5,1] + print $ lis [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15] + print $ lis [1,1,1,1] diff --git a/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-2.hs b/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-2.hs new file mode 100644 index 0000000000..c9cf609d1c --- /dev/null +++ b/Task/Longest-increasing-subsequence/Haskell/longest-increasing-subsequence-2.hs @@ -0,0 +1,52 @@ +{-# LANGUAGE FlexibleContexts, UnicodeSyntax #-} + +module Main (main, lis) where + +import Control.Monad.ST ( ST, runST ) +import Control.Monad ( (>>=), (=<<), foldM ) +import Data.Array.ST ( Ix, STArray, readArray, writeArray, newArray ) +import Data.Array.MArray ( MArray ) + +infix 4 ≡ + +(≡) :: Eq α ⇒ α → α → Bool +(≡) = (==) + +(∘) = (.) + + +lis ∷ Ord α ⇒ [α] → [α] +lis xs = runST $ do + let lxs = length xs + pileTops ← newSTArray (min 1 lxs , lxs) [] + i ← foldM (stack pileTops) 0 xs + readArray pileTops i >>= return ∘ reverse + +stack ∷ (Integral ι, Ord ε, Ix ι, MArray α [ε] μ) + ⇒ α ι [ε] → ι → ε → μ ι +stack piles i x = do + j ← bsearch piles x i + writeArray piles j ∘ (x:) =<< if j ≡ 1 then return [] + else readArray piles (j-1) + return $ if j ≡ i+1 then i+1 else i + +bsearch ∷ (Integral ι, Ord ε, Ix ι, MArray α [ε] μ) + ⇒ α ι [ε] → ε → ι → μ ι +bsearch piles x = go 1 + where go lo hi | lo > hi = return lo + | otherwise = + do (y:_) ← readArray piles mid + if y < x then go (succ mid) hi + else go lo (pred mid) + + where mid = (lo + hi) `div` 2 + +newSTArray ∷ Ix ι ⇒ (ι,ι) → ε → ST σ (STArray σ ι ε) +newSTArray = newArray + + +main ∷ IO () +main = do + print $ lis [3, 2, 6, 4, 5, 1] + print $ lis [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] + print $ lis [1, 1, 1, 1] diff --git a/Task/Longest-increasing-subsequence/Icon/longest-increasing-subsequence.icon b/Task/Longest-increasing-subsequence/Icon/longest-increasing-subsequence.icon new file mode 100644 index 0000000000..09b15a9363 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Icon/longest-increasing-subsequence.icon @@ -0,0 +1,11 @@ +procedure main(A) + every writes((!lis(A)||" ") | "\n") +end + +procedure lis(A) + r := [A[1]] | fail + every (put(pt := [], [v := !A]), p := !pt) do + if put(p, p[-1] < v) then r := (*p > *r, p) + else p[-1] := (p[-2] < v) + return r +end diff --git a/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-1.j b/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-1.j new file mode 100644 index 0000000000..02860ff3ef --- /dev/null +++ b/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-1.j @@ -0,0 +1,2 @@ +increasing=: (-: /:~)@#~"1 #:@i.@^~&2@# +longestinc=: ] #~ [: (#~ ([: (= >./) +/"1)) #:@I.@increasing diff --git a/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-2.j b/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-2.j new file mode 100644 index 0000000000..da1b88c1b1 --- /dev/null +++ b/Task/Longest-increasing-subsequence/J/longest-increasing-subsequence-2.j @@ -0,0 +1,8 @@ + longestinc 3,2,6,4,5,1 +2 4 5 +3 4 5 + longestinc 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15 +0 2 6 9 11 15 +0 2 6 9 13 15 +0 4 6 9 11 15 +0 4 6 9 13 15 diff --git a/Task/Longest-increasing-subsequence/Java/longest-increasing-subsequence.java b/Task/Longest-increasing-subsequence/Java/longest-increasing-subsequence.java new file mode 100644 index 0000000000..3552f2eda7 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Java/longest-increasing-subsequence.java @@ -0,0 +1,40 @@ +import java.util.*; + +public class LIS { + public static > List lis(List n) { + List> pileTops = new ArrayList>(); + // sort into piles + for (E x : n) { + Node node = new Node(); + node.value = x; + int i = Collections.binarySearch(pileTops, node); + if (i < 0) i = ~i; + if (i != 0) + node.pointer = pileTops.get(i-1); + if (i != pileTops.size()) + pileTops.set(i, node); + else + pileTops.add(node); + } + // extract LIS from nodes + List result = new ArrayList(); + for (Node node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); + node != null; node = node.pointer) + result.add(node.value); + Collections.reverse(result); + return result; + } + + private static class Node> implements Comparable> { + public E value; + public Node pointer; + public int compareTo(Node y) { return value.compareTo(y.value); } + } + + public static void main(String[] args) { + List d = Arrays.asList(3,2,6,4,5,1); + System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); + d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); + System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); + } +} diff --git a/Task/Longest-increasing-subsequence/JavaScript/longest-increasing-subsequence.js b/Task/Longest-increasing-subsequence/JavaScript/longest-increasing-subsequence.js new file mode 100644 index 0000000000..39534cfcc5 --- /dev/null +++ b/Task/Longest-increasing-subsequence/JavaScript/longest-increasing-subsequence.js @@ -0,0 +1,38 @@ +var _ = require('underscore'); +function findIndex(input){ + var len = input.length; + var maxSeqEndingHere = _.range(len).map(function(){return 1;}); + for(var i=0; i=0;j--) + if(input[i] > input[j] && maxSeqEndingHere[j] >= maxSeqEndingHere[i]) + maxSeqEndingHere[i] = maxSeqEndingHere[j]+1; + return maxSeqEndingHere; +} + +function findSequence(input, result){ + var maxValue = Math.max.apply(null, result); + var maxIndex = result.indexOf(Math.max.apply(Math, result)); + var output = []; + output.push(input[maxIndex]); + for(var i = maxIndex ; i >= 0; i--){ + if(maxValue==0)break; + if(input[maxIndex] > input[i] && result[i] == maxValue-1){ + output.push(input[i]); + maxValue--; + } + } + output.reverse(); + return output; +} + + +var x = [0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]; +var y = [3, 2, 6, 4, 5, 1]; + +var result = findIndex(x); +var final = findSequence(x, result); +console.log(final); + +var result1 = findIndex(y); +var final1 = findSequence(y, result1); +console.log(final1); diff --git a/Task/Longest-increasing-subsequence/Lua/longest-increasing-subsequence.lua b/Task/Longest-increasing-subsequence/Lua/longest-increasing-subsequence.lua new file mode 100644 index 0000000000..e30c09c688 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Lua/longest-increasing-subsequence.lua @@ -0,0 +1,26 @@ +function buildLIS(seq) + local piles = { { {table.remove(seq, 1), nil} } } + while #seq>0 do + local x=table.remove(seq, 1) + for j=1,#piles do + if piles[j][#piles[j]][1]>x then + table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])}) + break + elseif j==#piles then + table.insert(piles, {{x, #piles[j]}}) + end + end + end + local t={} + table.insert(t, piles[#piles][1][1]) + local p=piles[#piles][1][2] + for i=#piles-1,1,-1 do + table.insert(t, piles[i][p][1]) + p=piles[i][p][2] + end + table.sort(t) + print(unpack(t)) +end + +buildLIS({3,2,6,4,5,1}) +buildLIS({0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}) diff --git a/Task/Longest-increasing-subsequence/Mathematica/longest-increasing-subsequence.math b/Task/Longest-increasing-subsequence/Mathematica/longest-increasing-subsequence.math new file mode 100644 index 0000000000..aa5a8a38bb --- /dev/null +++ b/Task/Longest-increasing-subsequence/Mathematica/longest-increasing-subsequence.math @@ -0,0 +1 @@ +LongestAscendingSequence/@{{3,2,6,4,5,1},{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}} diff --git a/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-1.ocaml b/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-1.ocaml new file mode 100644 index 0000000000..2c28ef5c2f --- /dev/null +++ b/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-1.ocaml @@ -0,0 +1,23 @@ +let longest l = List.fold_left (fun acc x -> if List.length acc < List.length x + then x + else acc) [] l + +let subsequences d l = + let rec check_subsequences acc = function + | x::s -> check_subsequences (if (List.hd (List.rev x)) < d + then x::acc + else acc) s + | [] -> acc + in check_subsequences [] l + +let lis d = + let rec lis' l = function + | x::s -> lis' ((longest (subsequences x l)@[x])::l) s + | [] -> longest l + in lis' [] d + +let _ = + let sequences = [[3; 2; 6; 4; 5; 1]; [0; 8; 4; 12; 2; 10; 6; 14; 1; 9; 5; 13; 3; 11; 7; 15]] + in + List.map (fun x -> print_endline (String.concat " " (List.map string_of_int + (lis x)))) sequences diff --git a/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-2.ocaml b/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-2.ocaml new file mode 100644 index 0000000000..30ff70c9c7 --- /dev/null +++ b/Task/Longest-increasing-subsequence/OCaml/longest-increasing-subsequence-2.ocaml @@ -0,0 +1,22 @@ +let lis cmp list = + let pile_tops = Array.make (List.length list) [] in + let bsearch_piles x len = + let rec aux lo hi = + if lo > hi then + lo + else + let mid = (lo + hi) / 2 in + if cmp (List.hd pile_tops.(mid)) x < 0 then + aux (mid+1) hi + else + aux lo (mid-1) + in + aux 0 (len-1) + in + let f len x = + let i = bsearch_piles x len in + pile_tops.(i) <- x :: if i = 0 then [] else pile_tops.(i-1); + if i = len then len+1 else len + in + let len = List.fold_left f 0 list in + List.rev pile_tops.(len-1) diff --git a/Task/Longest-increasing-subsequence/Objective-C/longest-increasing-subsequence.m b/Task/Longest-increasing-subsequence/Objective-C/longest-increasing-subsequence.m new file mode 100644 index 0000000000..f5b6f89fb3 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Objective-C/longest-increasing-subsequence.m @@ -0,0 +1,53 @@ +#import + +@interface Node : NSObject { +@public + id val; + Node *back; +} +@end + +@implementation Node +@end + +@interface NSArray (LIS) +- (NSArray *)longestIncreasingSubsequenceWithComparator:(NSComparator)comparator; +@end + +@implementation NSArray (LIS) +- (NSArray *)longestIncreasingSubsequenceWithComparator:(NSComparator)comparator { + NSMutableArray *pileTops = [[NSMutableArray alloc] init]; + // sort into piles + for (id x in self) { + Node *node = [[Node alloc] init]; + node->val = x; + int i = [pileTops indexOfObject:node + inSortedRange:NSMakeRange(0, [pileTops count]) + options:NSBinarySearchingInsertionIndex|NSBinarySearchingFirstEqual + usingComparator:^NSComparisonResult(Node *node1, Node *node2) { + return comparator(node1->val, node2->val); + }]; + if (i != 0) + node->back = pileTops[i-1]; + pileTops[i] = node; + } + + // follow pointers from last node + NSMutableArray *result = [[NSMutableArray alloc] init]; + for (Node *node = [pileTops lastObject]; node; node = node->back) + [result addObject:node->val]; + return [[result reverseObjectEnumerator] allObjects]; +} +@end + +int main(int argc, const char *argv[]) { + @autoreleasepool { + for (NSArray *d in @[@[@3, @2, @6, @4, @5, @1], + @[@0, @8, @4, @12, @2, @10, @6, @14, @1, @9, @5, @13, @3, @11, @7, @15]]) + NSLog(@"an L.I.S. of %@ is %@", d, + [d longestIncreasingSubsequenceWithComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1 compare:obj2]; + }]); + } + return 0; +} diff --git a/Task/Longest-increasing-subsequence/PHP/longest-increasing-subsequence.php b/Task/Longest-increasing-subsequence/PHP/longest-increasing-subsequence.php new file mode 100644 index 0000000000..9e58dbd901 --- /dev/null +++ b/Task/Longest-increasing-subsequence/PHP/longest-increasing-subsequence.php @@ -0,0 +1,37 @@ +val >= $x) + $high = $mid - 1; + else + $low = $mid + 1; + } + $i = $low; + $node = new Node(); + $node->val = $x; + if ($i != 0) + $node->back = $pileTops[$i-1]; + $pileTops[$i] = $node; + } + $result = array(); + for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL; + $node != NULL; $node = $node->back) + $result[] = $node->val; + + return array_reverse($result); +} + +print_r(lis(array(3, 2, 6, 4, 5, 1))); +print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15))); +?> diff --git a/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-1.pl6 b/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-1.pl6 new file mode 100644 index 0000000000..8c574be6e9 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-1.pl6 @@ -0,0 +1,16 @@ +sub lis(@d) { + my @l = [].item xx @d; + @l[0].push: @d[0]; + for 1 ..^ @d -> $i { + for ^$i -> $j { + if @d[$j] < @d[$i] && @l[$i] < @l[$j] + 1 { + @l[$i] = [ @l[$j][] ] + } + } + @l[$i].push: @d[$i]; + } + return max :by(*.elems), @l; +} + +say lis([3,2,6,4,5,1]); +say lis([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]); diff --git a/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 b/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 new file mode 100644 index 0000000000..7c97191c24 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 @@ -0,0 +1,16 @@ +sub lis(@deck is copy) { + my @S = [@deck.shift() => Mu].item; + for @deck -> $card { + if defined my $i = first { @S[$_][*-1].key > $card }, ^@S { + @S[$i].push: $card => @S[$i-1][*-1] // Mu + } else { + @S.push: [ $card => @S[*-1][*-1] // Mu ].item + } + } + reverse map *.key, ( + @S[*-1][*-1], *.value ...^ !*.defined + ) +} + +say lis <3 2 6 4 5 1>; +say lis <0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15>; diff --git a/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-1.pl b/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-1.pl new file mode 100644 index 0000000000..991976fa4e --- /dev/null +++ b/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-1.pl @@ -0,0 +1,20 @@ +sub lis { + my @l = map [], 1 .. @_; + push @{$l[0]}, +$_[0]; + for my $i (1 .. @_-1) { + for my $j (0 .. $i - 1) { + if ($_[$j] < $_[$i] and @{$l[$i]} < @{$l[$j]} + 1) { + $l[$i] = [ @{$l[$j]} ]; + } + } + push @{$l[$i]}, $_[$i]; + } + my ($max, $l) = 0, []; + for (@l) { + ($max, $l) = (scalar(@$_), $_) if @$_ > $max; + } + return @$l; +} + +print join ' ', lis 3, 2, 6, 4, 5, 1; +print join ' ', lis 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15; diff --git a/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-2.pl b/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-2.pl new file mode 100644 index 0000000000..5a899c5c4a --- /dev/null +++ b/Task/Longest-increasing-subsequence/Perl/longest-increasing-subsequence-2.pl @@ -0,0 +1,34 @@ +sub lis { + my @pileTops; + # sort into piles + foreach my $x (@_) { + # binary search + my $low = 0, $high = $#pileTops; + while ($low <= $high) { + my $mid = int(($low + $high) / 2); + if ($pileTops[$mid]{val} >= $x) { + $high = $mid - 1; + } else { + $low = $mid + 1; + } + } + my $i = $low; + my $node = {val => $x}; + $node->{back} = $pileTops[$i-1] if $i != 0; + $pileTops[$i] = $node; + } + my @result; + for (my $node = $pileTops[-1]; $node; $node = $node->{back}) { + push @result, $node->{val}; + } + + return reverse @result; +} + +foreach my $r ([3, 2, 6, 4, 5, 1], + [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) { + my @d = @$r; + my @lis = lis(@d); + print "an L.I.S. of [@d] is [@lis]\n"; + +} diff --git a/Task/Longest-increasing-subsequence/Prolog/longest-increasing-subsequence.pro b/Task/Longest-increasing-subsequence/Prolog/longest-increasing-subsequence.pro new file mode 100644 index 0000000000..79d6fd24a1 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Prolog/longest-increasing-subsequence.pro @@ -0,0 +1,14 @@ +lis(In, Out) :- + % we ask Prolog to find the longest sequence + aggregate(max(N,Is), (one_is(In, [], Is), length(Is, N)), max(_, Res)), + reverse(Res, Out). + + +% we describe the way to find increasing subsequence +one_is([], Current, Current). + + +one_is([H | T], Current, Final) :- + ( Current = [], one_is(T, [H], Final)); + ( Current = [H1 | _], H1 < H, one_is(T, [H | Current], Final)); + one_is(T, Current, Final). diff --git a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py new file mode 100644 index 0000000000..4e0b1167d4 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py @@ -0,0 +1,11 @@ +def longest_increasing_subsequence(d): + 'Return one of the L.I.S. of list d' + l = [] + for i in range(len(d)): + l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or [[]], key=len) + + [d[i]]) + return max(l, key=len) + +if __name__ == '__main__': + for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: + print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d))) diff --git a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py new file mode 100644 index 0000000000..1d48a6bc48 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py @@ -0,0 +1,34 @@ +from collections import namedtuple +from functools import total_ordering +from bisect import bisect_left + +@total_ordering +class Node(namedtuple('Node_', 'val back')): + def __iter__(self): + while self is not None: + yield self.val + self = self.back + def __lt__(self, other): + return self.val < other.val + def __eq__(self, other): + return self.val == other.val + +def lis(d): + """Return one of the L.I.S. of list d using patience sorting.""" + if not d: + return [] + pileTops = [] + for di in d: + j = bisect_left(pileTops, Node(di, None)) + new_node = Node(di, pileTops[j-1] if j > 0 else None) + if j == len(pileTops): + pileTops.append(new_node) + else: + pileTops[j] = new_node + + return list(pileTops[-1])[::-1] + +if __name__ == '__main__': + for d in [[3,2,6,4,5,1], + [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: + print('a L.I.S. of %s is %s' % (d, lis(d))) diff --git a/Task/Longest-increasing-subsequence/README b/Task/Longest-increasing-subsequence/README new file mode 100644 index 0000000000..52424efa5b --- /dev/null +++ b/Task/Longest-increasing-subsequence/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Longest_increasing_subsequence diff --git a/Task/Longest-increasing-subsequence/Racket/longest-increasing-subsequence.rkt b/Task/Longest-increasing-subsequence/Racket/longest-increasing-subsequence.rkt new file mode 100644 index 0000000000..34e0084df8 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Racket/longest-increasing-subsequence.rkt @@ -0,0 +1,27 @@ +#lang racket/base +(require data/gvector) + +(define (gvector-last gv) + (gvector-ref gv (sub1 (gvector-count gv)))) + +(define (lis-patience-sort input-list) + (let ([piles (gvector)]) + (for ([item (in-list input-list)]) + (insert-item! piles item)) + (reverse (gvector-last piles)))) + +(define (insert-item! piles item) + (if (zero? (gvector-count piles)) + (gvector-add! piles (cons item '())) + (cond + [(not (<= item (car (gvector-last piles)))) + (gvector-add! piles (cons item (gvector-last piles)))] + [(<= item (car (gvector-ref piles 0))) + (gvector-set! piles 0 (cons item '()))] + [else (let loop ([first 1] [last (sub1 (gvector-count piles))]) + (if (= first last) + (gvector-set! piles first (cons item (gvector-ref piles (sub1 first)))) + (let ([middle (quotient (+ first last) 2)]) + (if (<= item (car (gvector-ref piles middle))) + (loop first middle) + (loop (add1 middle) last)))))]))) diff --git a/Task/Longest-increasing-subsequence/Ruby/longest-increasing-subsequence.rb b/Task/Longest-increasing-subsequence/Ruby/longest-increasing-subsequence.rb new file mode 100644 index 0000000000..2d5d721d88 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Ruby/longest-increasing-subsequence.rb @@ -0,0 +1,33 @@ +Node = Struct.new(:val, :back) + +def lis(n) + pileTops = [] + # sort into piles + for x in n + # binary search + low, high = 0, pileTops.size-1 + while low <= high + mid = low + (high - low) / 2 + if pileTops[mid].val >= x + high = mid - 1 + else + low = mid + 1 + end + end + i = low + node = Node.new(x) + node.back = pileTops[i-1] if i > 0 + pileTops[i] = node + end + + result = [] + node = pileTops.last + while node + result.unshift(node.val) + node = node.back + end + result +end + +p lis([3, 2, 6, 4, 5, 1]) +p lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) diff --git a/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence.scala b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence.scala new file mode 100644 index 0000000000..1f734f534c --- /dev/null +++ b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence.scala @@ -0,0 +1,25 @@ +object LongestIncreasingSubsequence extends App { + def longest(l: Array[Int]) = l match { + case _ if l.length < 2 => Array(l) + case l => + def increasing(done: Array[Int], remaining: Array[Int]): Array[Array[Int]] = remaining match { + case Array() => Array(done) + case Array(head, _*) => + (if (head > done.last) increasing(done :+ head, remaining.tail) else Array()) ++ + increasing(done, remaining.tail) // all increasing combinations + } + val all = (1 to l.length).flatMap(i => increasing(l take i takeRight 1, l.drop(i+1))).sortBy(-_.length) + all.takeWhile(_.length == all.head.length).toArray // longest from all increasing combinations + } + + val tests = Map( + "3,2,6,4,5,1" -> Array("2,4,5", "3,4,5"), + "0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> Array("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15") + ) + def asInts(s: String): Array[Int] = s split "," map Integer.parseInt + assert(tests forall {case (given, expect) => + val lis = longest(asInts(given)) + println(s"$given has ${lis.size} longest increasing subsequences, e.g. "+lis.last.mkString(",")) + expect contains lis.last.mkString(",") + }) +} diff --git a/Task/Longest-increasing-subsequence/Scheme/longest-increasing-subsequence.ss b/Task/Longest-increasing-subsequence/Scheme/longest-increasing-subsequence.ss new file mode 100644 index 0000000000..66630fcf2d --- /dev/null +++ b/Task/Longest-increasing-subsequence/Scheme/longest-increasing-subsequence.ss @@ -0,0 +1,24 @@ +(define (lis less? lst) + (define pile-tops (make-vector (length lst))) + (define (bsearch-piles x len) + (let aux ((lo 0) + (hi (- len 1))) + (if (> lo hi) + lo + (let ((mid (quotient (+ lo hi) 2))) + (if (less? (car (vector-ref pile-tops mid)) x) + (aux (+ mid 1) hi) + (aux lo (- mid 1))))))) + (let aux ((len 0) + (lst lst)) + (if (null? lst) + (reverse (vector-ref pile-tops (- len 1))) + (let* ((x (car lst)) + (i (bsearch-piles x len))) + (vector-set! pile-tops i (cons x (if (= i 0) + '() + (vector-ref pile-tops (- i 1))))) + (aux (if (= i len) (+ len 1) len) (cdr lst)))))) + +(display (lis < '(3 2 6 4 5 1))) (newline) +(display (lis < '(0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))) (newline) diff --git a/Task/Longest-increasing-subsequence/Standard-ML/longest-increasing-subsequence.ml b/Task/Longest-increasing-subsequence/Standard-ML/longest-increasing-subsequence.ml new file mode 100644 index 0000000000..8d83a3dc0c --- /dev/null +++ b/Task/Longest-increasing-subsequence/Standard-ML/longest-increasing-subsequence.ml @@ -0,0 +1,31 @@ +fun lis cmp n = + let + val pile_tops = DynamicArray.array (length n, []) + fun bsearch_piles x = + let + fun aux (lo, hi) = + if lo > hi then + lo + else + let + val mid = (lo + hi) div 2 + in + if cmp (hd (DynamicArray.sub (pile_tops, mid)), x) = LESS then + aux (mid+1, hi) + else + aux (lo, mid-1) + end + in + aux (0, DynamicArray.bound pile_tops) + end + fun f x = + let + val i = bsearch_piles x + in + DynamicArray.update (pile_tops, i, + x :: (if i = 0 then [] else DynamicArray.sub (pile_tops, i-1))) + end + in + app f n; + rev (DynamicArray.sub (pile_tops, DynamicArray.bound pile_tops)) + end diff --git a/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-1.tcl b/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-1.tcl new file mode 100644 index 0000000000..7e79bfe937 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-1.tcl @@ -0,0 +1,21 @@ +package require Tcl 8.6 + +proc longestIncreasingSubsequence {sequence} { + # Get the increasing subsequences (and their lengths) + set subseq [list 1 [lindex $sequence 0]] + foreach value $sequence { + set max {} + foreach {len item} $subseq { + if {[lindex $item end] < $value} { + if {[llength [lappend item $value]] > [llength $max]} { + set max $item + } + } elseif {![llength $max]} { + set max [list $value] + } + } + lappend subseq [llength $max] $max + } + # Pick the longest subsequence; -stride requires Tcl 8.6 + return [lindex [lsort -stride 2 -index 0 $subseq] end] +} diff --git a/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-2.tcl b/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-2.tcl new file mode 100644 index 0000000000..8cafd9e8f7 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Tcl/longest-increasing-subsequence-2.tcl @@ -0,0 +1,2 @@ +puts [longestIncreasingSubsequence {3 2 6 4 5 1}] +puts [longestIncreasingSubsequence {0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15}] diff --git a/Task/Ludic-numbers/00DESCRIPTION b/Task/Ludic-numbers/00DESCRIPTION new file mode 100644 index 0000000000..b96738bfb1 --- /dev/null +++ b/Task/Ludic-numbers/00DESCRIPTION @@ -0,0 +1,29 @@ +[https://oeis.org/wiki/Ludic_numbers Ludic numbers] are related to prime numbers as they are generated by a sieve quite like the [[Sieve of Eratosthenes]] is used to generate prime numbers. + +The first ludic number is 1. +
To generate succeeding ludic numbers create an array of increasing integers starting from 2 +: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 ... +(Loop) +* Take the first member of the resultant array as the next Ludic number 2. +* Remove every '''2'nd''' indexed item from the array (including the first). +::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 ... +* (Unrolling a few loops...) +* Take the first member of the resultant array as the next Ludic number 3. +* Remove every '''3'rd''' indexed item from the array (including the first). +::3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... +* Take the first member of the resultant array as the next Ludic number 5. +* Remove every '''5'th''' indexed item from the array (including the first). +::5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... +* Take the first member of the resultant array as the next Ludic number 7. +* Remove every '''7'th''' indexed item from the array (including the first). +::7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... +* ... +* Take the first member of the current array as the next Ludic number L. +* Remove every '''L'th''' indexed item from the array (including the first). +* ... + +;Task: +* Generate and show here the first 25 ludic numbers. +* How many ludic numbers are there less than or equal to 1000? +* Show the 2000..2005'th ludic numbers. +* A triplet is any three numbers x, x+2, x+6 where all three numbers are also ludic numbers. Show all triplets of ludic numbers < 250 (Stretch goal) diff --git a/Task/Ludic-numbers/00META.yaml b/Task/Ludic-numbers/00META.yaml new file mode 100644 index 0000000000..d4fa65ce91 --- /dev/null +++ b/Task/Ludic-numbers/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Sieves diff --git a/Task/Ludic-numbers/AutoHotkey/ludic-numbers.ahk b/Task/Ludic-numbers/AutoHotkey/ludic-numbers.ahk new file mode 100644 index 0000000000..34479dcdfe --- /dev/null +++ b/Task/Ludic-numbers/AutoHotkey/ludic-numbers.ahk @@ -0,0 +1,45 @@ +#NoEnv +SetBatchLines, -1 +Ludic := LudicSieve(22000) + +Loop, 25 ; the first 25 ludic numbers + Task1 .= Ludic[A_Index] " " + +for i, Val in Ludic ; the number of ludic numbers less than or equal to 1000 + if (Val <= 1000) + Task2++ + else + break + +Loop, 6 ; the 2000..2005'th ludic numbers + Task3 .= Ludic[1999 + A_Index] " " + +for i, Val in Ludic { ; all triplets of ludic numbers < 250 + if (Val + 6 > 249) + break + if (Ludic[i + 1] = Val + 2 && Ludic[i + 2] = Val + 6 || i = 1) + Task4 .= "(" Val " " Val + 2 " " Val + 6 ") " +} + +MsgBox, % "First 25:`t`t" Task1 + . "`nLudics below 1000:`t" Task2 + . "`nLudic 2000 to 2005:`t" Task3 + . "`nTriples below 250:`t" Task4 +return + +LudicSieve(Limit) { + Arr := [], Ludic := [] + Loop, % Limit + Arr.Insert(A_Index) + Ludic.Insert(Arr.Remove(1)) + while Arr.MaxIndex() != 1 { + Ludic.Insert(n := Arr.Remove(1)) + , Removed := 0 + Loop, % Arr.MaxIndex() // n { + Arr.Remove(A_Index * n - Removed) + , Removed++ + } + } + Ludic.Insert(Arr[1]) + return Ludic +} diff --git a/Task/Ludic-numbers/C++/ludic-numbers.cpp b/Task/Ludic-numbers/C++/ludic-numbers.cpp new file mode 100644 index 0000000000..b7b907d3f6 --- /dev/null +++ b/Task/Ludic-numbers/C++/ludic-numbers.cpp @@ -0,0 +1,81 @@ +#include +#include +using namespace std; + +class ludic +{ +public: + void ludicList() + { + _list.push_back( 1 ); + + vector v; + for( int x = 2; x < 22000; x++ ) + v.push_back( x ); + + while( true ) + { + vector::iterator i = v.begin(); + int z = *i; + _list.push_back( z ); + + while( true ) + { + i = v.erase( i ); + if( distance( i, v.end() ) <= z - 1 ) break; + advance( i, z - 1 ); + } + if( v.size() < 1 ) return; + } + } + + void show( int s, int e ) + { + for( int x = s; x < e; x++ ) + cout << _list[x] << " "; + } + + void findTriplets( int e ) + { + int lu, x = 0; + while( _list[x] < e ) + { + lu = _list[x]; + if( inList( lu + 2 ) && inList( lu + 6 ) ) + cout << "(" << lu << " " << lu + 2 << " " << lu + 6 << ")\n"; + x++; + } + } + + int count( int e ) + { + int x = 0, c = 0; + while( _list[x++] <= 1000 ) c++; + return c; + } + +private: + bool inList( int lu ) + { + for( int x = 0; x < 250; x++ ) + if( _list[x] == lu ) return true; + return false; + } + + vector _list; +}; + +int main( int argc, char* argv[] ) +{ + ludic l; + l.ludicList(); + cout << "first 25 ludic numbers:" << "\n"; + l.show( 0, 25 ); + cout << "\n\nThere are " << l.count( 1000 ) << " ludic numbers <= 1000" << "\n"; + cout << "\n2000 to 2005'th ludic numbers:" << "\n"; + l.show( 1999, 2005 ); + cout << "\n\nall triplets of ludic numbers < 250:" << "\n"; + l.findTriplets( 250 ); + cout << "\n\n"; + return system( "pause" ); +} diff --git a/Task/Ludic-numbers/C/ludic-numbers.c b/Task/Ludic-numbers/C/ludic-numbers.c new file mode 100644 index 0000000000..713317397a --- /dev/null +++ b/Task/Ludic-numbers/C/ludic-numbers.c @@ -0,0 +1,71 @@ +#include +#include + +typedef unsigned uint; +typedef struct { uint i, v; } filt_t; + +// ludics with at least so many elements and reach at least such value +uint* ludic(uint min_len, uint min_val, uint *len) +{ + uint cap, i, v, active = 1, nf = 0; + filt_t *f = calloc(cap = 2, sizeof(*f)); + f[1].i = 4; + + for (v = 1; ; ++v) { + for (i = 1; i < active && --f[i].i; i++); + + if (i < active) + f[i].i = f[i].v; + else if (nf == f[i].i) + f[i].i = f[i].v, ++active; // enable one more filter + else { + if (nf >= cap) + f = realloc(f, sizeof(*f) * (cap*=2)); + f[nf] = (filt_t){ v + nf, v }; + if (++nf >= min_len && v >= min_val) break; + } + } + + // pack the sequence into a uint[] + // filt_t struct was used earlier for cache locality in loops + uint *x = (void*) f; + for (i = 0; i < nf; i++) x[i] = f[i].v; + x = realloc(x, sizeof(*x) * nf); + + *len = nf; + return x; +} + +int find(uint *a, uint v) +{ + uint i; + for (i = 0; a[i] <= v; i++) + if (v == a[i]) return 1; + return 0; +} + +int main(void) +{ + uint len, i, *x = ludic(2005, 1000, &len); + + printf("First 25:"); + for (i = 0; i < 25; i++) printf(" %u", x[i]); + putchar('\n'); + + for (i = 0; x[i] <= 1000; i++); + printf("Ludics below 1000: %u\n", i); + + printf("Ludic 2000 to 2005:"); + for (i = 2000; i <= 2005; i++) printf(" %u", x[i - 1]); + putchar('\n'); + + printf("Triples below 250:"); + for (i = 0; x[i] + 6 <= 250; i++) + if (find(x, x[i] + 2) && find(x, x[i] + 6)) + printf(" (%u %u %u)", x[i], x[i] + 2, x[i] + 6); + + putchar('\n'); + + free(x); + return 0; +} diff --git a/Task/Ludic-numbers/Clojure/ludic-numbers.clj b/Task/Ludic-numbers/Clojure/ludic-numbers.clj new file mode 100644 index 0000000000..b8ac16f2d0 --- /dev/null +++ b/Task/Ludic-numbers/Clojure/ludic-numbers.clj @@ -0,0 +1,25 @@ +(defn ints-from [n] + (cons n (lazy-seq (ints-from (inc n))))) + +(defn drop-nth [n seq] + (cond + (zero? n) seq + (empty? seq) [] + :else (concat (take (dec n) seq) (lazy-seq (drop-nth n (drop n seq)))))) + +(def ludic ((fn ludic + ([] (ludic 1)) + ([n] (ludic n (ints-from (inc n)))) + ([n [f & r]] (cons n (lazy-seq (ludic f (drop-nth f r)))))))) + +(defn ludic? [n] (= (first (filter (partial <= n) ludic)) n)) + +(print "First 25: ") +(println (take 25 ludic)) +(print "Count below 1000: ") +(println (count (take-while (partial > 1000) ludic))) +(print "2000th through 2005th: ") +(println (map (partial nth ludic) (range 1999 2005))) +(print "Triplets < 250: ") +(println (filter (partial every? ludic?) + (for [i (range 250)] (list i (+ i 2) (+ i 6))))) diff --git a/Task/Ludic-numbers/D/ludic-numbers-1.d b/Task/Ludic-numbers/D/ludic-numbers-1.d new file mode 100644 index 0000000000..fa875b2574 --- /dev/null +++ b/Task/Ludic-numbers/D/ludic-numbers-1.d @@ -0,0 +1,51 @@ +struct Ludics(T) { + int opApply(int delegate(in ref T) dg) { + int result; + T[] rotor, taken = [T(1)]; + result = dg(taken[0]); + if (result) return result; + + for (T i = 2; ; i++) { // Shoud be stopped if T has a max. + size_t j = 0; + for (; j < rotor.length; j++) + if (!--rotor[j]) + break; + + if (j < rotor.length) { + rotor[j] = taken[j + 1]; + } else { + result = dg(i); + if (result) return result; + taken ~= i; + rotor ~= taken[j + 1]; + } + } + } +} + +void main() { + import std.stdio, std.range, std.algorithm; + + // std.algorithm.take can't be used here. + uint[] L; + foreach (const x; Ludics!uint()) + if (L.length < 2005) + L ~= x; + else + break; + + writeln("First 25 ludic primes:\n", L.take(25)); + writefln("\nThere are %d ludic numbers <= 1000.", + L.until!q{ a > 1000 }.walkLength); + + writeln("\n2000'th .. 2005'th ludic primes:\n", L[1999 .. 2005]); + + enum m = 250; + const triplets = L.filter!(x => x + 6 < m && + L.canFind(x + 2) && L.canFind(x + 6)) + // Ugly output: + //.map!(x => tuple(x, x + 2, x + 6)).array; + .map!(x => [x, x + 2, x + 6]).array; + writefln("\nThere are %d triplets less than %d:\n%s", + triplets.length, m, triplets); +} diff --git a/Task/Ludic-numbers/D/ludic-numbers-2.d b/Task/Ludic-numbers/D/ludic-numbers-2.d new file mode 100644 index 0000000000..e59b4298e0 --- /dev/null +++ b/Task/Ludic-numbers/D/ludic-numbers-2.d @@ -0,0 +1,58 @@ +struct Ludics(T) { + T[] rotor, taken = [T(1)]; + T i; + size_t j; + T front = 1; // = taken[0]; + bool running = false; + static immutable bool empty = false; + + void popFront() pure nothrow @safe { + if (running) + goto RESUME; + else + running = true; + + i = 2; + while (true) { + j = 0; + + while (j < rotor.length) { + rotor[j]--; + if (!rotor[j]) + break; + j++; + } + if (j < rotor.length) { + rotor[j] = taken[j + 1]; + } else { + front = i; + return; + RESUME: + taken ~= i; + rotor ~= taken[j + 1]; + } + i++; // Could overflow if T has a max. + } + } +} + +void main() { + import std.stdio, std.range, std.algorithm, std.array; + + Ludics!uint L; + writeln("First 25 ludic primes:\n", L.take(25)); + writefln("\nThere are %d ludic numbers <= 1000.", + L.until!q{ a > 1000 }.walkLength); + + writeln("\n2000'th .. 2005'th ludic primes:\n", L.drop(1999).take(6)); + + enum uint m = 250; + const few = L.until!(x => x > m).array; + const triplets = few.filter!(x => x + 6 < m && few.canFind(x + 2) + && few.canFind(x + 6)) + // Ugly output: + //.map!(x => tuple(x, x + 2, x + 6)).array; + .map!(x => [x, x + 2, x + 6]).array; + writefln("\nThere are %d triplets less than %d:\n%s", + triplets.length, m, triplets); +} diff --git a/Task/Ludic-numbers/D/ludic-numbers-3.d b/Task/Ludic-numbers/D/ludic-numbers-3.d new file mode 100644 index 0000000000..8b01680c98 --- /dev/null +++ b/Task/Ludic-numbers/D/ludic-numbers-3.d @@ -0,0 +1,42 @@ +void main() { + import std.stdio, std.range, std.algorithm, std.concurrency; + + Generator!T ludics(T)() { + return new typeof(return)({ + T[] rotor, taken = [T(1)]; + yield(taken[0]); + + for (T i = 2; ; i++) { // Shoud be stopped if T has a max. + size_t j = 0; + for (; j < rotor.length; j++) + if (!--rotor[j]) + break; + + if (j < rotor.length) { + rotor[j] = taken[j + 1]; + } else { + yield(i); + taken ~= i; + rotor ~= taken[j + 1]; + } + } + }); + } + + const L = ludics!uint.take(2005).array; + + writeln("First 25 ludic primes:\n", L.take(25)); + writefln("\nThere are %d ludic numbers <= 1000.", + L.until!q{ a > 1000 }.walkLength); + + writeln("\n2000'th .. 2005'th ludic primes:\n", L[1999 .. 2005]); + + enum m = 250; + const triplets = L.filter!(x => x + 6 < m && + L.canFind(x + 2) && L.canFind(x + 6)) + // Ugly output: + //.map!(x => tuple(x, x + 2, x + 6)).array; + .map!(x => [x, x + 2, x + 6]).array; + writefln("\nThere are %d triplets less than %d:\n%s", + triplets.length, m, triplets); +} diff --git a/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e b/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e new file mode 100644 index 0000000000..9c1bfacc10 --- /dev/null +++ b/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e @@ -0,0 +1,78 @@ +class + LUDIC_NUMBERS +create make +feature + make(n: INTEGER) + -- make an Initial Array filled with the numbers from 1 to n + -- make an Array for ludic_numbers filled with an initial 1 + require + n_positive: n>0 + local + i: INTEGER + do + create initial.make_filled (0, 1, n-1) + create ludic_numbers.make_filled(1,1,1) + from i:= 2 + until i> n + loop + initial.put (i, i-1) + i:= i+1 + end + ludic + end + ludic_numbers: ARRAY[INTEGER] + +feature{NONE} + initial: ARRAY[INTEGER] + + ludic + --- forces the first element (initial[1]) of the initial array into ludic_numbers + --- before deleting it and all multiples of it + local + count: INTEGER + new_array: ARRAY[INTEGER] + do + create new_array.make_from_array (initial) + from + count:= 1 + until + count> initial.count + loop + if ludic_numbers[ludic_numbers.count]/= new_array[1] then + ludic_numbers.force (new_array[1], count+1) + end + new_array:= delete_i_elements(new_array) + count:= count+1 + end + end + + delete_i_elements(ar: ARRAY[INTEGER]): ARRAY[INTEGER] + --- delete all multiples of ar[1] from the array ar (Eiffel starts indexing at 1) + require + ar_not_empty: ar.count >0 + local + s_array: ARRAY[INTEGER] + i,k: INTEGER + do + create s_array.make_empty + from + i:= 1 + k:= 1 + until + i>ar.count + loop + if (i-1)\\(ar[1])/=0 then + s_array.force (ar[i], k) + k:= k+1 + end + i:= i+1 + end + if s_array.count=0 then + Result:= ar + else + Result:= s_array + end + ensure + not_empty : Result.count>0 + end +end diff --git a/Task/Ludic-numbers/Eiffel/ludic-numbers-2.e b/Task/Ludic-numbers/Eiffel/ludic-numbers-2.e new file mode 100644 index 0000000000..a74e3f76c3 --- /dev/null +++ b/Task/Ludic-numbers/Eiffel/ludic-numbers-2.e @@ -0,0 +1,32 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + local + k, count: INTEGER + do + create ludic.make(22000) + + io.put_string ("%NLudic numbers up to 25. %N") + across ludic.ludic_numbers.subarray (1, 25) as ld loop io.put_string (ld.item.out + "%N") end + + io.put_string ("%NLudic numbers from 2000 ... 2005. %N") + across ludic.ludic_numbers.subarray (2000, 2005) as ld loop io.put_string (ld.item.out + "%N") end + + io.put_string ("%NNumber of Ludic numbers smaller than 1000. %N") + from + k:= 1 + until + ludic.ludic_numbers[k]>= 1000 + loop + k:= k +1 + count:= count+1 + end + io.put_integer (count) + end + ludic: LUDIC_NUMBERS +end diff --git a/Task/Ludic-numbers/Go/ludic-numbers.go b/Task/Ludic-numbers/Go/ludic-numbers.go new file mode 100644 index 0000000000..38c1225bb6 --- /dev/null +++ b/Task/Ludic-numbers/Go/ludic-numbers.go @@ -0,0 +1,81 @@ +package main + +import "fmt" + +// Ludic returns a slice of Ludic numbers stopping after +// either n entries or when max is exceeded. +// Either argument may be <=0 to disable that limit. +func Ludic(n int, max int) []uint32 { + const maxInt32 = 1<<31 - 1 // i.e. math.MaxInt32 + if max > 0 && n < 0 { + n = maxInt32 + } + if n < 1 { + return nil + } + if max < 0 { + max = maxInt32 + } + sieve := make([]uint32, 10760) // XXX big enough for 2005 Ludics + sieve[0] = 1 + sieve[1] = 2 + if n > 2 { + // We start with even numbers already removed + for i, j := 2, uint32(3); i < len(sieve); i, j = i+1, j+2 { + sieve[i] = j + } + // We leave the Ludic numbers in place, + // k is the index of the next Ludic + for k := 2; k < n; k++ { + l := int(sieve[k]) + if l >= max { + n = k + break + } + i := l + l-- + // last is the last valid index + last := k + i - 1 + for j := k + i + 1; j < len(sieve); i, j = i+1, j+1 { + last = k + i + sieve[last] = sieve[j] + if i%l == 0 { + j++ + } + } + // Truncate down to only the valid entries + if last < len(sieve)-1 { + sieve = sieve[:last+1] + } + } + } + if n > len(sieve) { + panic("program error") // should never happen + } + return sieve[:n] +} + +func has(x []uint32, v uint32) bool { + for i := 0; i < len(x) && x[i] <= v; i++ { + if x[i] == v { + return true + } + } + return false +} + +func main() { + // Ludic() is so quick we just call it repeatedly + fmt.Println("First 25:", Ludic(25, -1)) + fmt.Println("Numner of Ludics below 1000:", len(Ludic(-1, 1000))) + fmt.Println("Ludic 2000 to 2005:", Ludic(2005, -1)[1999:]) + + fmt.Print("Tripples below 250:") + x := Ludic(-1, 250) + for i, v := range x[:len(x)-2] { + if has(x[i+1:], v+2) && has(x[i+2:], v+6) { + fmt.Printf(", (%d %d %d)", v, v+2, v+6) + } + } + fmt.Println() +} diff --git a/Task/Ludic-numbers/Haskell/ludic-numbers-1.hs b/Task/Ludic-numbers/Haskell/ludic-numbers-1.hs new file mode 100644 index 0000000000..23e4e6a888 --- /dev/null +++ b/Task/Ludic-numbers/Haskell/ludic-numbers-1.hs @@ -0,0 +1,12 @@ +import Data.List (unfoldr, genericSplitAt) + +ludic :: [Integer] +ludic = 1 : unfoldr (\xs@(x:_) -> Just (x, dropEvery x xs)) [2..] where + dropEvery n = concat . map tail . unfoldr (Just . genericSplitAt n) + +main :: IO () +main = do + print $ take 25 $ ludic + print $ length $ takeWhile (<= 1000) $ ludic + print $ take 6 $ drop 1999 $ ludic + -- haven't done triplets task yet diff --git a/Task/Ludic-numbers/Haskell/ludic-numbers-2.hs b/Task/Ludic-numbers/Haskell/ludic-numbers-2.hs new file mode 100644 index 0000000000..97a072eab7 --- /dev/null +++ b/Task/Ludic-numbers/Haskell/ludic-numbers-2.hs @@ -0,0 +1,9 @@ +ludic = 1:2 : f 3 [3..] [(4,2)] where + f n (x:xs) yy@((i,y):ys) + | n == i = f n (dropEvery y xs) ys + | otherwise = x : f (1+n) xs (yy ++ [(n+x, x)]) + +dropEvery n s = a ++ dropEvery n (tail b) where + (a,b) = splitAt (n-1) s + +main = print $ ludic !! 10000 diff --git a/Task/Ludic-numbers/Icon/ludic-numbers.icon b/Task/Ludic-numbers/Icon/ludic-numbers.icon new file mode 100644 index 0000000000..a520b1756e --- /dev/null +++ b/Task/Ludic-numbers/Icon/ludic-numbers.icon @@ -0,0 +1,35 @@ +global num, cascade, sieve, nfilter + +procedure main(A) + lds := ludic(2005) # All we need for the four tasks. + every writes("First 25:" | (" "||!lds)\25 | "\n") + every (n := 0) +:= (!lds < 1000, 1) + write("There are ",n," Ludic numbers < 1000.") + every writes("2000th through 2005th: " | (lds[2000 to 20005]||" ") | "\n") + writes("Triplets:") + every (250 > (x := !lds)) & (250 > (x+2 = !lds)) & (250 > (x+6 = !lds)) do + writes(" [",x,",",x+2,",",x+6,"]") + write() +end + +procedure ludic(limit) + candidates := create seq(2) + put(cascade := [], create { + repeat { + report(l := num, limit) + put(cascade, create (cnt:=0, repeat ((cnt+:=1)%l=0, @sieve) | @@nfilter)) + cascade[-2] :=: cascade[-1] # keep this sink as the last filter + @sieve + } + }) + sieve := create while num := @candidates do @@(nfilter := create !cascade) + report(1, limit) + return @sieve +end + +procedure report(ludic, limit) + static count, lds + initial {count := 0; lds := []} + if (count +:= 1) > limit then lds@&main + put(lds, ludic) +end diff --git a/Task/Ludic-numbers/J/ludic-numbers-1.j b/Task/Ludic-numbers/J/ludic-numbers-1.j new file mode 100644 index 0000000000..5c4a0593ad --- /dev/null +++ b/Task/Ludic-numbers/J/ludic-numbers-1.j @@ -0,0 +1 @@ + ludic =: _1 |.!.1 [: {."1 [: (#~ 0 ~: {. | i.@#)^:a: 2 + i. diff --git a/Task/Ludic-numbers/J/ludic-numbers-2.j b/Task/Ludic-numbers/J/ludic-numbers-2.j new file mode 100644 index 0000000000..a937f49108 --- /dev/null +++ b/Task/Ludic-numbers/J/ludic-numbers-2.j @@ -0,0 +1,22 @@ + # ludic 110 NB. 110 is sufficient to generate 25 Ludic numbers +25 + ludic 110 NB. First 25 Ludic numbers +1 2 3 5 7 11 13 17 23 25 29 37 41 43 47 53 61 67 71 77 83 89 91 97 107 + + #ludic 1000 NB. 142 Ludic numbers <= 1000 +142 + + # ludic 22000 NB. 22000 is sufficient to generate > 2005 Ludic numbers +2042 + (2000+i.6) { ludic 22000 NB. Ludic numbers 2000-2005 +21481 21487 21493 21503 21511 21523 + + 0 2 6 (] (*./ .e.~ # |:@]) +/) ludic 250 NB. Ludic triplets <= 250 + 1 3 7 + 5 7 11 + 11 13 17 + 23 25 29 + 41 43 47 +173 175 179 +221 223 227 +233 235 239 diff --git a/Task/Ludic-numbers/Java/ludic-numbers.java b/Task/Ludic-numbers/Java/ludic-numbers.java new file mode 100644 index 0000000000..adb571f7b1 --- /dev/null +++ b/Task/Ludic-numbers/Java/ludic-numbers.java @@ -0,0 +1,45 @@ +import java.util.ArrayList; +import java.util.List; + +public class Ludic{ + public static List ludicUpTo(int n){ + List ludics = new ArrayList(n); + for(int i = 1; i <= n; i++){ //fill the initial list + ludics.add(i); + } + + //start at index 1 because the first ludic number is 1 and we don't remove anything for it + for(int cursor = 1; cursor < ludics.size(); cursor++){ + int thisLudic = ludics.get(cursor); //the first item in the list is a ludic number + int removeCursor = cursor + thisLudic; //start removing that many items later + while(removeCursor < ludics.size()){ + ludics.remove(removeCursor); //remove the next item + removeCursor = removeCursor + thisLudic - 1; //move the removal cursor up as many spaces as we need to + //then back one to make up for the item we just removed + } + } + return ludics; + } + + public static List> getTriplets(List ludics){ + List> triplets = new ArrayList>(); + for(int i = 0; i < ludics.size() - 2; i++){ //only need to check up to the third to last item + int thisLudic = ludics.get(i); + if(ludics.contains(thisLudic + 2) && ludics.contains(thisLudic + 6)){ + List triplet = new ArrayList(3); + triplet.add(thisLudic); + triplet.add(thisLudic + 2); + triplet.add(thisLudic + 6); + triplets.add(triplet); + } + } + return triplets; + } + + public static void main(String[] srgs){ + System.out.println("First 25 Ludics: " + ludicUpTo(110)); //110 will get us 25 numbers + System.out.println("Ludics up to 1000: " + ludicUpTo(1000).size()); + System.out.println("2000th - 2005th Ludics: " + ludicUpTo(22000).subList(1999, 2005)); //22000 will get us 2005 numbers + System.out.println("Triplets up to 250: " + getTriplets(ludicUpTo(250))); + } +} diff --git a/Task/Ludic-numbers/Mathematica/ludic-numbers.math b/Task/Ludic-numbers/Mathematica/ludic-numbers.math new file mode 100644 index 0000000000..eae49c2b72 --- /dev/null +++ b/Task/Ludic-numbers/Mathematica/ludic-numbers.math @@ -0,0 +1,10 @@ +n=10^5; +Ludic={1}; +seq=Range[2,n]; +ClearAll[DoStep] +DoStep[seq:{f_,___}]:=Module[{out=seq}, + AppendTo[Ludic,f]; + out[[;;;;f]]=Sequence[]; + out +] +Nest[DoStep,seq,2500]; diff --git a/Task/Ludic-numbers/PL-I/ludic-numbers.pli b/Task/Ludic-numbers/PL-I/ludic-numbers.pli new file mode 100644 index 0000000000..2077ffb622 --- /dev/null +++ b/Task/Ludic-numbers/PL-I/ludic-numbers.pli @@ -0,0 +1,52 @@ +Ludic_numbers: procedure options (main); /* 18 April 2014 */ + declare V(2:22000) fixed, L(2200) fixed; + declare (step, i, j, k, n) fixed binary; + +Ludic: procedure; + n = hbound(V,1); k = 1; L(1) = 1; + do i = 2 to n; V(i) = i; end; + + do forever; + + k = k + 1; L(k), step = V(2); + + do i = 2 to n by step; + V(i) = 0; + end; + call compress; + if L(k) >= 21511 then leave; + end; + + put skip list ('The first 25 Ludic numbers are:'); + put skip edit ( (L(i) do i = 1 to 25) ) (F(4)); + + k = 0; + do i = 1 by 1; + if L(i) < 1000 then k = k + 1; else leave; + end; + + put skip list ('There are ' || trim(k) || ' Ludic numbers < 1000'); + put skip list ('Six Ludic numbers from the 2000-th:'); + put skip edit ( (L(i) do i = 2000 to 2005) ) (f(7)); + /* Triples are values of the form x, x+2, x+6 */ + put skip list ('Triples are:'); + put skip; + i = 1; + do i = 1 by 1 while (L(i+2) <= 250); + if (L(i) = L(i+1) - 2) & (L(i) = L(i+2) - 6) then + put edit ('(', L(i), L(i+1), L(i+2), ') ' ) (A, 3 F(4), A); + end; + +compress: procedure; + j = 2; + do i = 2 to n; + if V(i) ^= 0 then do; V(j) = V(i); j = j + 1; end; + end; + n = j-1; +end compress; + +end Ludic; + +call Ludic; + +end Ludic_numbers; diff --git a/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 b/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 new file mode 100644 index 0000000000..2d3f9155b9 --- /dev/null +++ b/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 @@ -0,0 +1,29 @@ +constant ludic = gather { + my @taken = take 1; + my @rotor; + + for 2..* -> $i { + loop (my $j = 0; $j < @rotor; $j++) { + --@rotor[$j] or last; + } + if $j < @rotor { + @rotor[$j] = @taken[$j+1]; + } + else { + push @taken, take $i; + push @rotor, @taken[$j+1]; + } + } + } + +say ludic[^25]; +say "Number of Ludic numbers <= 1000: ", +(ludic ...^ * > 1000); +say "Ludic numbers 2000..2005: ", ludic[1999..2004]; + +my \l250 = set ludic ...^ * > 250; +say "Ludic triples < 250: ", gather + for l250.keys -> $a { + my $b = $a + 2; + my $c = $a + 6; + take "<$a $b $c>" if $b ∈ l250 and $c ∈ l250; + } diff --git a/Task/Ludic-numbers/Perl/ludic-numbers.pl b/Task/Ludic-numbers/Perl/ludic-numbers.pl new file mode 100644 index 0000000000..18dde38cee --- /dev/null +++ b/Task/Ludic-numbers/Perl/ludic-numbers.pl @@ -0,0 +1,60 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; + +{ my @ludic = (1); + my $max = 3; + my @candidates; + + sub sieve { + my $l = shift; + for (my $i = 0; $i <= $#candidates; $i += $l) { + splice @candidates, $i, 1; + } + } + + sub ludic { + my ($type, $n) = @_; + die "Arg0 Type must be 'count' or 'max'\n" + unless grep $_ eq $type, qw( count max ); + die "Arg1 Number must be > 0\n" if 0 >= $n; + + return (@ludic[ 0 .. $n - 1 ]) if 'count' eq $type and @ludic >= $n; + + return (grep $_ <= $n, @ludic) if 'max' eq $type and $ludic[-1] >= $n; + + while (1) { + if (@candidates) { + last if ('max' eq $type and $candidates[0] > $n) + or ($n == @ludic); + + push @ludic, $candidates[0]; + sieve($ludic[-1] - 1); + + } else { + $max *= 2; + @candidates = 2 .. $max; + for my $l (@ludic) { + sieve($l - 1) unless 1 == $l; + } + } + } + return (@ludic) + } + +} + +my @triplet; +my %ludic; +undef @ludic{ ludic(max => 250) }; +for my $i (keys %ludic) { + push @triplet, $i if exists $ludic{ $i + 2 } and exists $ludic { $i + 6 }; +} + +say 'First 25: ', join ' ', ludic(count => 25); +say 'Count < 1000: ', scalar ludic(max => 1000); +say '2000..2005th: ', join ' ', (ludic(count => 2005))[1999 .. 2004]; +say 'triplets < 250: ', join ' ', + map { '(' . join(' ',$_, $_ + 2, $_ + 6) . ')' } + sort { $a <=> $b } @triplet; diff --git a/Task/Ludic-numbers/PicoLisp/ludic-numbers.l b/Task/Ludic-numbers/PicoLisp/ludic-numbers.l new file mode 100644 index 0000000000..6099034a6e --- /dev/null +++ b/Task/Ludic-numbers/PicoLisp/ludic-numbers.l @@ -0,0 +1,40 @@ +(de drop (Lst) + (let N (car Lst) + (make + (for (I . X) (cdr Lst) + (unless (=0 (% I N)) (link X)) ) ) ) ) + +(de comb (M Lst) + (cond + ((=0 M) '(NIL)) + ((not Lst)) + (T + (conc + (mapcar + '((Y) (cons (car Lst) Y)) + (comb (dec M) (cdr Lst)) ) + (comb M (cdr Lst)) ) ) ) ) + +(de ludic (N) + (let Ludic (range 1 100000) + (make + (link (pop 'Ludic)) + (do (dec N) + (link (car Ludic)) + (setq Ludic (drop Ludic)) ) ) ) ) + +(let L (ludic 2005) + (println (head 25 L)) + (println (cnt '((X) (< X 1000)) L)) + (println (tail 6 L)) + (println + (filter + '((Lst) + (and + (= (+ 2 (car Lst)) (cadr Lst)) + (= (+ 6 (car Lst)) (caddr Lst)) ) ) + (comb + 3 + (filter '((X) (< X 250)) L) ) ) ) ) + +(bye) diff --git a/Task/Ludic-numbers/Python/ludic-numbers-1.py b/Task/Ludic-numbers/Python/ludic-numbers-1.py new file mode 100644 index 0000000000..c3356947f4 --- /dev/null +++ b/Task/Ludic-numbers/Python/ludic-numbers-1.py @@ -0,0 +1,22 @@ +def ludic(nmax=100000): + yield 1 + lst = list(range(2, nmax + 1)) + while lst: + yield lst[0] + del lst[::lst[0]] + +ludics = [l for i,l in zip(range(2005), ludic())] + +print('First 25 ludic primes:') +print(ludics[:25]) +print("\nThere are %i ludic numbers <= 1000" + % sum(1 for l in ludics if l <= 1000)) +print("\n2000'th..2005'th ludic primes:") +print(ludics[2000-1: 2005]) + +n = 250 +triplets = [(x, x+2, x+6) + for x in ludics + if x+6 < n and x+2 in ludics and x+6 in ludics] +print('\nThere are %i triplets less than %i:\n %r' + % (len(triplets), n, triplets)) diff --git a/Task/Ludic-numbers/Python/ludic-numbers-2.py b/Task/Ludic-numbers/Python/ludic-numbers-2.py new file mode 100644 index 0000000000..eff1797328 --- /dev/null +++ b/Task/Ludic-numbers/Python/ludic-numbers-2.py @@ -0,0 +1,12 @@ +def ludic(nmax=64): + yield 1 + taken = [] + while True: + lst, nmax = list(range(2, nmax + 1)), nmax * 2 + for t in taken: + del lst[::t] + while lst: + t = lst[0] + taken.append(t) + yield t + del lst[::t] diff --git a/Task/Ludic-numbers/README b/Task/Ludic-numbers/README new file mode 100644 index 0000000000..ec15fd9733 --- /dev/null +++ b/Task/Ludic-numbers/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Ludic_numbers diff --git a/Task/Ludic-numbers/REXX/ludic-numbers.rexx b/Task/Ludic-numbers/REXX/ludic-numbers.rexx new file mode 100644 index 0000000000..ddfbb08bae --- /dev/null +++ b/Task/Ludic-numbers/REXX/ludic-numbers.rexx @@ -0,0 +1,39 @@ +/*REXX program to display (a range of) ludic numbers, or a count of same*/ +parse arg N count bot top triples . /*obtain optional parameters/args*/ +if N=='' then N=25 /*Not specified? Use the default.*/ +if count=='' then count=1000 /* " " " " " */ +if bot=='' then bot=2000 /* " " " " " */ +if top=='' then top=2005 /* " " " " " */ +if triples=='' then triples=250-1 /* " " " " " */ +say 'The first ' N " ludic numbers: " ludic(n) +say +say "There are " words(ludic(-count)) ' ludic numbers from 1───►'count " (inclusive)." +say +say "The " bot ' to ' top " ludic numbers are: " ludic(bot,top) +$=ludic(-triples) 0 0; #=0; @= +say + do j=1 for words($); _=word($,j) /*it is known that ludic _ exists*/ + if wordpos(_+2,$)==0 | wordpos(_+6,$)==0 then iterate /*¬triple.*/ + #=#+1; @=@ '◄'_ _+2 _+6"► " /*bump triple counter, and ··· */ + end /*j*/ /* [↑] append found triple ──► @*/ + +if @=='' then say 'From 1──►'triples", no triples found." + else say 'From 1──►'triples", " # ' triples found:' @ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────LUDIC subroutine────────────────────*/ +ludic: procedure; parse arg m 1 mm,h; am=abs(m); if h\=='' then am=h +$=1 2; @= /*$=ludic #s superset, @=# series*/ + /* [↓] construct a ludic series.*/ + do j=3 by 2 to am * max(1,15*((m>0)|h\=='')); @=@ j; end; @=@' ' + /* [↑] high limit: approx|exact */ + do while words(@)\==0 /* [↓] examine the first word. */ + f=word(@,1); $=$ f /*append this first word to list.*/ + do d=1 by f while d<=words(@) /*use 1st #, elide all occurances*/ + @=changestr(' 'word(@,d)" ",@, ' . ') /*delete the # in the seq#*/ + end /*d*/ /* [↑] done eliding "1st" number*/ + @=translate(@,,.) /*translate periods to blanks. */ + end /*forever*/ /* [↑] done eliding ludic #s. */ +@=space(@) /*remove extra blanks from list. */ + +if h=='' then return subword($,1,am) /*return a range of ludic numbers*/ + return subword($,m,h-m+1) /*return a section of a range.*/ diff --git a/Task/Ludic-numbers/Racket/ludic-numbers.rkt b/Task/Ludic-numbers/Racket/ludic-numbers.rkt new file mode 100644 index 0000000000..2acd6cc700 --- /dev/null +++ b/Task/Ludic-numbers/Racket/ludic-numbers.rkt @@ -0,0 +1,40 @@ +#lang racket +(define lucid-sieve-size 25000) ; this should be enough to do me! +(define lucid? + (let ((lucid-bytes-sieve + (delay + (define sieve-bytes (make-bytes lucid-sieve-size 1)) + (bytes-set! sieve-bytes 0 0) ; not a lucid number + (define (sieve-pass L) + (let loop ((idx (add1 L)) (skip (sub1 L))) + (cond + [(= idx lucid-sieve-size) + (for/first ((rv (in-range (add1 L) lucid-sieve-size)) + #:unless (zero? (bytes-ref sieve-bytes rv))) rv)] + [(zero? (bytes-ref sieve-bytes idx)) + (loop (add1 idx) skip)] + [(= skip 0) + (bytes-set! sieve-bytes idx 0) + (loop (add1 idx) (sub1 L))] + [else (loop (add1 idx) (sub1 skip))]))) + (let loop ((l 2)) + (when l (loop (sieve-pass l)))) + sieve-bytes))) + + (λ (n) (= 1 (bytes-ref (force lucid-bytes-sieve) n))))) + +(define (dnl . things) (for-each displayln things)) + +(dnl + "Generate and show here the first 25 ludic numbers." + (for/list ((_ 25) (l (sequence-filter lucid? (in-naturals)))) l) + "How many ludic numbers are there less than or equal to 1000?" + (for/sum ((n 1001) #:when (lucid? n)) 1) + "Show the 2000..2005'th ludic numbers." + (for/list ((i 2006) (l (sequence-filter lucid? (in-naturals))) #:when (>= i 2000)) l) + #< EMPTY_SET do + ludicNumber := min(sieve); + incl(ludicNumbers, ludicNumber); + count := 0; + for number range sieve do + if count rem ludicNumber = 0 then + excl(sieve, number); + end if; + incr(count); + end for; + end while; + end func; + +const integer: limit is 22000; +const set of integer: ludicNumbers is ludicNumbers(limit); + +const proc: main is func + local + var integer: number is 0; + var integer: count is 0; + begin + write("First 25:"); + for number range ludicNumbers until count = 25 do + write(" " <& number); + incr(count); + end for; + writeln; + count := 0; + for number range ludicNumbers until number > 1000 do + incr(count); + end for; + writeln("Ludics below 1000: " <& count); + write("Ludic 2000 to 2005:"); + count := 0; + for number range ludicNumbers until count >= 2005 do + incr(count); + if count >= 2000 then + write(" " <& number); + end if; + end for; + writeln; + write("Triples below 250:"); + for number range ludicNumbers until number > 250 do + if number + 2 in ludicNumbers and number + 6 in ludicNumbers then + write(" (" <& number <& ", " <& number + 2 <& ", " <& number + 6 <& ")"); + end if; + end for; + writeln; + end func; diff --git a/Task/Ludic-numbers/Tcl/ludic-numbers.tcl b/Task/Ludic-numbers/Tcl/ludic-numbers.tcl new file mode 100644 index 0000000000..492045aec6 --- /dev/null +++ b/Task/Ludic-numbers/Tcl/ludic-numbers.tcl @@ -0,0 +1,43 @@ +package require Tcl 8.6 + +proc ludic n { + global ludicList ludicGenerator + for {} {[llength $ludicList] <= $n} {lappend ludicList $i} { + set i [$ludicGenerator] + set ludicGenerator [coroutine L_$i apply {{gen k} { + yield [info coroutine] + while true { + set val [$gen] + if {[incr i] == $k} {set i 0} else {yield $val} + } + }} $ludicGenerator $i] + } + return [lindex $ludicList $n] +} +# Bootstrap the generator sequence +set ludicList [list 1] +set ludicGenerator [coroutine L_1 apply {{} { + set n 1 + yield [info coroutine] + while true {yield [incr n]} +}}] + +# Default of 1000 is not enough +interp recursionlimit {} 5000 + +for {set i 0;set l {}} {$i < 25} {incr i} {lappend l [ludic $i]} +puts "first25: [join $l ,]" + +for {set i 0} {[ludic $i] <= 1000} {incr i} {} +puts "below=1000: $i" + +for {set i 1999;set l {}} {$i < 2005} {incr i} {lappend l [ludic $i]} +puts "2000-2005: [join $l ,]" + +for {set i 0} {[ludic $i] < 256} {incr i} {set isl([ludic $i]) $i} +for {set i 1;set l {}} {$i < 250} {incr i} { + if {[info exists isl($i)] && [info exists isl([expr {$i+2}])] && [info exists isl([expr {$i+6}])]} { + lappend l ($i,[expr {$i+2}],[expr {$i+6}]) + } +} +puts "triplets: [join $l ,]" diff --git a/Task/Machine-code/00DESCRIPTION b/Task/Machine-code/00DESCRIPTION new file mode 100644 index 0000000000..ae7e757e01 --- /dev/null +++ b/Task/Machine-code/00DESCRIPTION @@ -0,0 +1,17 @@ +The task requires poking machine code directly into memory and executing it. This is strictly for x86 (32 bit) architectures. The machine code is the opcodes of the following simple program: + +mov EAX, [ESP+4] +add EAX, [ESP+8] +ret + +which translates into the following opcodes: +(139 68 36 4 3 68 36 8 195) +and in Hex this would correspond to the following: +("8B" "44" "24" "4" "3" "44" "24" "8" "C3") + +Implement the following in your favorite programming language (take the common lisp code as an example if you wish): +
    +
  1. Poke the above opcodes into a memory pointer
  2. +
  3. Excute it with the following arguments: [ESP+4] => unsigned-byte argument of value 7; [ESP+8] => unsigned-byte argument of value 12; The result would be 19.
  4. +
  5. Free the Pointer
  6. +
diff --git a/Task/Machine-code/AutoHotkey/machine-code.ahk b/Task/Machine-code/AutoHotkey/machine-code.ahk new file mode 100644 index 0000000000..7ab5fbc140 --- /dev/null +++ b/Task/Machine-code/AutoHotkey/machine-code.ahk @@ -0,0 +1,11 @@ +MCode(Var, "8B44240403442408C3") +MsgBox, % DllCall(&Var, "Char",7, "Char",12) +Var := "" +return + +; http://www.autohotkey.com/board/topic/19483-machine-code-functions-bit-wizardry/ +MCode(ByRef code, hex) { ; allocate memory and write Machine Code there + VarSetCapacity(code, StrLen(hex) // 2) + Loop % StrLen(hex) // 2 + NumPut("0x" . SubStr(hex, 2 * A_Index - 1, 2), code, A_Index - 1, "Char") +} diff --git a/Task/Machine-code/BBC-BASIC/machine-code.bbc b/Task/Machine-code/BBC-BASIC/machine-code.bbc new file mode 100644 index 0000000000..4d4d116e92 --- /dev/null +++ b/Task/Machine-code/BBC-BASIC/machine-code.bbc @@ -0,0 +1,18 @@ + REM Claim 9 bytes of memory + SYS "GlobalAlloc",0,9 TO code% + + REM Poke machine code into it + P%=code% + [OPT 0 + mov EAX, [ESP+4] + add EAX, [ESP+8] + ret + ] + + REM Run code + SYS code%,7,12 TO result% + PRINT result% + + REM Free memory + SYS "GlobalFree",code% + END diff --git a/Task/Machine-code/C/machine-code.c b/Task/Machine-code/C/machine-code.c new file mode 100644 index 0000000000..1e90bb2573 --- /dev/null +++ b/Task/Machine-code/C/machine-code.c @@ -0,0 +1,31 @@ +#include +#include +#include + +int test (int a, int b) +{ + /* + mov EAX, [ESP+4] + add EAX, [ESP+8] + ret + */ + char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; + void *buf; + int c; + /* copy code to executable buffer */ + buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_PRIVATE|MAP_ANON,-1,0); + + memcpy (buf, code, sizeof(code)); + /* run code */ + c = ((int (*) (int, int))buf)(a, b); + /* free buffer */ + munmap (buf, sizeof(code)); + return c; +} + +int main () +{ + printf("%d\n", test(7,12)); + return 0; +} diff --git a/Task/Machine-code/Common-Lisp/machine-code.lisp b/Task/Machine-code/Common-Lisp/machine-code.lisp new file mode 100644 index 0000000000..e02929112c --- /dev/null +++ b/Task/Machine-code/Common-Lisp/machine-code.lisp @@ -0,0 +1,55 @@ +;;Note that by using the 'CFFI' library, one can apply this procedure portably in any lisp implementation; +;; in this code however I chose to demonstrate only the implementation-dependent programs. + +;;CCL +;; Allocate a memory pointer and poke the opcode into it +(defparameter ptr (ccl::malloc 9)) + +(loop for i in '(139 68 36 4 3 68 36 8 195) + for j from 0 do + (setf (ccl::%get-unsigned-byte ptr j) i)) + +;; Execute with the required arguments and return the result as an unsigned-byte +(ccl::ff-call ptr :UNSIGNED-BYTE 7 :UNSIGNED-BYTE 12 :UNSIGNED-BYTE) + +;; Output = 19 + +;; Free the pointer +(ccl::free ptr) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;SBCL +(defparameter mmap (list 139 68 36 4 3 68 36 8 195)) + +(defparameter pointer (sb-alien:make-alien sb-alien:unsigned-char (length mmap))) + +(defparameter callp (loop FOR i FROM 0 BELOW (length mmap) + do + (setf (sb-alien:deref pointer i) (elt mmap i)) + finally + (return (sb-alien:cast pointer (function integer integer integer))))) + +(sb-alien:alien-funcall callp 7 12) + +(loop for i from 0 below 18 collect (sb-alien:deref ptr i)) + +(sb-alien:free-alien pointer) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;CLISP +(defparameter mmap (list 139 68 36 4 3 68 36 8 195)) + +(defparameter POINTER (FFI:FOREIGN-ADDRESS (FFI:FOREIGN-ALLOCATE 'FFI:UINT8 :COUNT 9))) + +(loop for i in mmap + for j from 0 do + (FUNCALL #'(SETF FFI:MEMORY-AS) i POINTER 'FFI:INT j)) + +(FUNCALL + (FFI:FOREIGN-FUNCTION POINTER + (LOAD-TIME-VALUE + (FFI:PARSE-C-TYPE + '(FFI:C-FUNCTION (:ARGUMENTS 'FFI:INT 'FFI:INT) (:RETURN-TYPE FFI:INT) (:LANGUAGE :STDC))))) + 7 12) + +(FFI:FOREIGN-FREE POINTER) diff --git a/Task/Machine-code/D/machine-code.d b/Task/Machine-code/D/machine-code.d new file mode 100644 index 0000000000..c06abfd131 --- /dev/null +++ b/Task/Machine-code/D/machine-code.d @@ -0,0 +1,17 @@ +int test(in int a, in int b) pure nothrow @nogc { + /* + mov EAX, [ESP+4] + add EAX, [ESP+8] + ret + */ + immutable ubyte[9] code = [0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]; + alias F = extern(C) int function(int, int) pure nothrow @nogc; + immutable f = cast(F)code.ptr; + return f(a, b); // Run code. +} + +void main() { + import std.stdio; + + test(7, 12).writeln; +} diff --git a/Task/Machine-code/PARI-GP/machine-code.pari b/Task/Machine-code/PARI-GP/machine-code.pari new file mode 100644 index 0000000000..e3b798fad7 --- /dev/null +++ b/Task/Machine-code/PARI-GP/machine-code.pari @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +int +test(int a, int b) +{ + char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; + void *buf; + int c; + /* copy code to executable buffer */ + buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_PRIVATE|MAP_ANON,-1,0); + + memcpy (buf, code, sizeof(code)); + /* run code */ + c = ((int (*) (int, int))buf)(a, b); + /* free buffer */ + munmap (buf, sizeof(code)); + return c; +} + +void +init_auto(void) +{ + pari_printf("%d\n", test(7,12)); + return 0; +} diff --git a/Task/Machine-code/Pascal/machine-code.pascal b/Task/Machine-code/Pascal/machine-code.pascal new file mode 100644 index 0000000000..213f422921 --- /dev/null +++ b/Task/Machine-code/Pascal/machine-code.pascal @@ -0,0 +1,35 @@ +Program Example66; +{Inspired... program to demonstrate the MMap function. Freepascal docs } +Uses + BaseUnix,Unix; + +const + code : array[0..9] of byte = ($8B, $44, $24, $4, $3, $44, $24, $8, $C3, $00); + a :longInt= 12; + b :longInt= 7; +type + tDummyFunc = function(a,b:LongInt):LongInt;cdecl; +Var + Len,k : cint; + P : Pointer; + +begin + len := sizeof(code); + P:= fpmmap(nil, + len+1 , + PROT_READ OR PROT_WRITE OR PROT_EXEC, + MAP_ANONYMOUS OR MAP_PRIVATE, + -1, // for MAP_ANONYMOUS + 0); + If P = Pointer(-1) then + Halt(4); + + for k := 0 to len-1 do + pChar(p)[k] := char(code[k]); + + k := tDummyFunc(P)(a,b); + + Writeln(a,'+',b,' = ',k); + if fpMUnMap(P,Len)<>0 Then + Halt(fpgeterrno); +end. diff --git a/Task/Machine-code/PureBasic/machine-code.purebasic b/Task/Machine-code/PureBasic/machine-code.purebasic new file mode 100644 index 0000000000..3bc5a08ef1 --- /dev/null +++ b/Task/Machine-code/PureBasic/machine-code.purebasic @@ -0,0 +1,38 @@ +Procedure MachineCodeVirtualAlloc(a,b) +*vm = VirtualAlloc_(#Null,?ecode-?scode,#MEM_COMMIT,#PAGE_EXECUTE_READWRITE) + If(*vm) + CopyMemory_(*vm,?scode,?ecode-?scode) + eax_result=CallFunctionFast(*vm,a,b) + VirtualFree_(*vm,0,#MEM_RELEASE) + ProcedureReturn eax_result + EndIf +EndProcedure + +rv=MachineCodeVirtualAlloc(7,12) +MessageRequester("MachineCodeVirtualAlloc",str(rv)+space(50),#PB_MessageRequester_Ok) + +#HEAP_CREATE_ENABLE_EXECUTE=$00040000 + +Procedure MachineCodeHeapCreate(a,b) +hHeap=HeapCreate_(#HEAP_CREATE_ENABLE_EXECUTE,?ecode-?scode,?ecode-?scode) + If(hHeap) + CopyMemory_(hHeap,?scode,?ecode-?scode) + eax_result=CallFunctionFast(hHeap,a,b) + HeapDestroy_(hHeap) + ProcedureReturn eax_result + EndIf +EndProcedure + +rv=MachineCodeHeapCreate(7,12) +MessageRequester("MachineCodeHeapCreate",str(rv)+space(50),#PB_MessageRequester_Ok) +End + +; 8B442404 mov eax,[esp+4] +; 03442408 add eax,[esp+8] +; C20800 ret 8 + +DataSection +scode: +Data.c $8B,$44,$24,$04,$03,$44,$24,$08,$C2,$08,$00 +ecode: +EndDataSection diff --git a/Task/Machine-code/Python/machine-code.py b/Task/Machine-code/Python/machine-code.py new file mode 100644 index 0000000000..379e427c8c --- /dev/null +++ b/Task/Machine-code/Python/machine-code.py @@ -0,0 +1,37 @@ +import ctypes +import os +from ctypes import c_ubyte, c_int + +code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3]) + +code_size = len(code) +# copy code into an executable buffer +if (os.name == 'posix'): + import mmap + executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC) + # we must keep a reference to executable_map until the call, to avoid freeing the mapped memory + executable_map.write(code) + # the mmap object won't tell us the actual address of the mapping, but we can fish it out by allocating + # some ctypes object over its buffer, then asking the address of that + func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map)) +elif (os.name == 'nt'): + # the mmap module doesn't support protection flags on Windows, so execute VirtualAlloc instead + code_buffer = ctypes.create_string_buffer(code) + PAGE_EXECUTE_READWRITE = 0x40 # Windows constants that would usually come from header files + MEM_COMMIT = 0x1000 + executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE) + if (executable_buffer_address == 0): + print('Warning: Failed to enable code execution, call will likely cause a protection fault.') + func_address = ctypes.addressof(code_buffer) + else: + ctypes.memmove(executable_buffer_address, code_buffer, code_size) + func_address = executable_buffer_address +else: + # for other platforms, we just hope DEP isn't enabled + code_buffer = ctypes.create_string_buffer(code) + func_address = ctypes.addressof(code_buffer) + +prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) # build a function prototype from return type and argument types +func = prototype(func_address) # build an actual function from the prototype by specifying the address +res = func(7,12) +print(res) diff --git a/Task/Machine-code/README b/Task/Machine-code/README new file mode 100644 index 0000000000..5d453e6170 --- /dev/null +++ b/Task/Machine-code/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Machine_code diff --git a/Task/Machine-code/Tcl/machine-code-1.tcl b/Task/Machine-code/Tcl/machine-code-1.tcl new file mode 100644 index 0000000000..75ce3d74d6 --- /dev/null +++ b/Task/Machine-code/Tcl/machine-code-1.tcl @@ -0,0 +1,30 @@ +package require critcl + +critcl::ccode { + #include +} + +# Define a command using C. The C is embedded in Tcl, and will be +# built into a shared library at runtime. Note that Tcl does not +# provide a native way of doing this sort of thing; this thunk is +# mandatory. +critcl::cproc runMachineCode {Tcl_Obj* codeObj int a int b} int { + int size, result; + unsigned char *code = Tcl_GetByteArrayFromObj(codeObj, &size); + void *buf; + + /* copy code to executable buffer */ + buf = mmap(0, (size_t) size, PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_PRIVATE|MAP_ANON, -1, 0); + memcpy(buf, code, (size_t) size); + /* run code */ + result = ((int (*) (int, int)) buf)(a, b); + /* dispose buffer */ + munmap(buf, (size_t) size); + + return result; +} + +# But now we have our thunk, we can execute arbitrary binary blobs +set code [binary format c* {0x8B 0x44 0x24 0x4 0x3 0x44 0x24 0x8 0xC3}] +puts [runMachineCode $code 7 12] diff --git a/Task/Machine-code/Tcl/machine-code-2.tcl b/Task/Machine-code/Tcl/machine-code-2.tcl new file mode 100644 index 0000000000..d2939f3b78 --- /dev/null +++ b/Task/Machine-code/Tcl/machine-code-2.tcl @@ -0,0 +1,4 @@ +package require machineCodeThunk 1.0 + +set code [binary format c* {0x8B 0x44 0x24 0x4 0x3 0x44 0x24 0x8 0xC3}] +puts [runMachineCode $code 7 12] diff --git a/Task/Magic-squares-of-odd-order/00DESCRIPTION b/Task/Magic-squares-of-odd-order/00DESCRIPTION new file mode 100644 index 0000000000..f78b189c75 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/00DESCRIPTION @@ -0,0 +1,23 @@ +A magic square is an N\times N square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). + +The numbers are usually (but not always) the 1st N^2 positive integers. + +A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''. + +{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:125%" +|- +| '''8''' || '''1''' || '''6''' +|- +| '''3''' || '''5''' || '''7''' +|- +| '''4''' || '''9''' || '''2''' +|} + +;Task + +For any odd N, [[wp:Magic square#Method_for_constructing_a_magic_square_of_odd_order|generate a magic square]] with the integers [1, \ldots, N^2] and show the results. Optionally, show the ''magic number''. + +You should demonstrate the generator by showing at least a magic square for N=5. + +;Also see: +* MathWorld™ entry: [http://mathworld.wolfram.com/MagicSquare.html Magic_square] diff --git a/Task/Magic-squares-of-odd-order/AWK/magic-squares-of-odd-order.awk b/Task/Magic-squares-of-odd-order/AWK/magic-squares-of-odd-order.awk new file mode 100644 index 0000000000..465d3d5f40 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/AWK/magic-squares-of-odd-order.awk @@ -0,0 +1,70 @@ +# syntax: GAWK -f MAGIC_SQUARES_OF_ODD_ORDER.AWK +BEGIN { + build(5) + build(3,1) # verify sum + build(7) + exit(0) +} +function build(n,check, arr,i,width,x,y) { + if (n !~ /^[0-9]*[13579]$/ || n < 3) { + printf("error: %s is invalid\n",n) + return + } + printf("\nmagic constant for %dx%d is %d\n",n,n,(n*n+1)*n/2) + x = 0 + y = int(n/2) + for (i=1; i<=(n*n); i++) { + arr[x,y] = i + if (arr[(x+n-1)%n,(y+n+1)%n]) { + x = (x+n+1) % n + } + else { + x = (x+n-1) % n + y = (y+n+1) % n + } + } + width = length(n*n) + for (x=0; x (others => Undef)); + -- initially undefined; at the end holding the magic square + + X: Index := 0; Y: Index := N/2; -- start position for the algorithm +begin + for I in Constants loop -- write 1, 2, ..., N*N into the magic array + A(X, Y) := I; -- write I into the magic array + if A(Dec(X), Inc(Y)) = Undef then + X := Dec(X); Y := Inc(Y); -- go right-up + else + X := Inc(X); -- go down + end if; + end loop; + + for Row in Index loop -- output the magic array + for Collumn in Index loop + CIO.Put(A(Row, Collumn), + Width => (if N*N < 10 then 2 elsif N*N < 100 then 3 else 4)); + end loop; + Ada.Text_IO.New_Line; + end loop; +end Magic_Square; diff --git a/Task/Magic-squares-of-odd-order/AutoHotkey/magic-squares-of-odd-order.ahk b/Task/Magic-squares-of-odd-order/AutoHotkey/magic-squares-of-odd-order.ahk new file mode 100644 index 0000000000..b51ea6723a --- /dev/null +++ b/Task/Magic-squares-of-odd-order/AutoHotkey/magic-squares-of-odd-order.ahk @@ -0,0 +1,39 @@ +msgbox % OddMagicSquare(5) +msgbox % OddMagicSquare(7) +return + +OddMagicSquare(oddN){ + sq := oddN**2 + obj := {} + loop % oddN + obj[A_Index] := {} ; dis is row + mid := Round((oddN+1)/2) + sum := Round(sq*(sq+1)/2/oddN) + obj[1][mid] := 1 + cR := 1 , cC := mid + loop % sq-1 + { + done := 0 , a := A_index+1 + while !done { + nR := cR-1 , nC := cC+1 + if !nR + nR := oddN + if (nC>oddN) + nC := 1 + if obj[nR][nC] ;filled + cR += 1 + else cR := nR , cC := nC + if !obj[cR][cC] + obj[cR][cC] := a , done := 1 + } + } + + str := "Magic Constant for " oddN "x" oddN " is " sum "`n" + for k,v in obj + { + for k2,v2 in v + str .= " " v2 + str .= "`n" + } + return str +} diff --git a/Task/Magic-squares-of-odd-order/C++/magic-squares-of-odd-order.cpp b/Task/Magic-squares-of-odd-order/C++/magic-squares-of-odd-order.cpp new file mode 100644 index 0000000000..55778d90a1 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/C++/magic-squares-of-odd-order.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +using namespace std; + +class magicSqr +{ +public: + magicSqr() { sqr = 0; } + ~magicSqr() { if( sqr ) delete [] sqr; } + + void create( int d ) + { + if( sqr ) delete [] sqr; + if( !( d & 1 ) ) d++; sz = d; + sqr = new int[sz * sz]; + memset( sqr, 0, sz * sz * sizeof( int ) ); + fillSqr(); + } + + void display() + { + cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; + cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; + ostringstream cvr; cvr << sz * sz; + int l = cvr.str().size(); + + for( int y = 0; y < sz; y++ ) + { + int yy = y * sz; + for( int x = 0; x < sz; x++ ) + cout << setw( l + 2 ) << sqr[yy + x]; + + cout << "\n"; + } + cout << "\n\n"; + } + +private: + void fillSqr() + { + int sx = sz / 2, sy = 0, c = 0; + while( c < sz * sz ) + { + if( !sqr[sx + sy * sz] ) + { + sqr[sx + sy * sz]= c + 1; + inc( sx ); dec( sy ); + c++; + } + else + { + dec( sx ); inc( sy ); inc( sy ); + } + } + } + + int magicNumber() + { return ( ( ( sz * sz + 1 ) / 2 ) * sz ); } + + void inc( int& a ) + { if( ++a == sz ) a = 0; } + + void dec( int& a ) + { if( --a < 0 ) a = sz - 1; } + + bool checkPos( int x, int y ) + { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } + + bool isInside( int s ) + { return ( s < sz && s > -1 ); } + + int* sqr; + int sz; +}; + +int main( int argc, char* argv[] ) +{ + magicSqr s; + s.create( 5 ); + s.display(); + return system( "pause" ); +} diff --git a/Task/Magic-squares-of-odd-order/C/magic-squares-of-odd-order.c b/Task/Magic-squares-of-odd-order/C/magic-squares-of-odd-order.c new file mode 100644 index 0000000000..254c641689 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/C/magic-squares-of-odd-order.c @@ -0,0 +1,19 @@ +#include +#include + +int f(int n, int x, int y) +{ + return (x + y*2 + 1)%n; +} + +int main(int argc, char **argv) +{ + int i, j, n = atoi(argv[1]); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) + printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); + putchar('\n'); + } + + return 0; +} diff --git a/Task/Magic-squares-of-odd-order/Common-Lisp/magic-squares-of-odd-order.lisp b/Task/Magic-squares-of-odd-order/Common-Lisp/magic-squares-of-odd-order.lisp new file mode 100644 index 0000000000..2b70e8e2f9 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Common-Lisp/magic-squares-of-odd-order.lisp @@ -0,0 +1,21 @@ +(defun magic-square (n) + (loop for i from 1 to n + collect + (loop for j from 1 to n + collect + (+ (* n (mod (+ i j (floor n 2) -1) + n)) + (mod (+ i (* 2 j) -2) + n) + 1)))) + +(defun magic-constant (n) + (* n + (/ (1+ (* n n)) + 2))) + +(defun output (n) + (format T "Magic constant for n=~a: ~a~%" n (magic-constant n)) + (let* ((size (length (write-to-string (* n n)))) + (format-str (format NIL "~~{~~{~~~ad~~^ ~~}~~%~~}~~%" size))) + (format T format-str (magic-square n)))) diff --git a/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-1.d b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-1.d new file mode 100644 index 0000000000..4116d29213 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-1.d @@ -0,0 +1,15 @@ +void main(in string[] args) { + import std.stdio, std.conv, std.range, std.algorithm,std.exception; + + immutable n = args.length == 2 ? args[1].to!uint : 5; + enforce(n > 0 && n % 2 == 1, "Only odd n > 1"); + immutable len = text(n ^^ 2).length.text; + + foreach (immutable r; 1 .. n + 1) + writefln("%-(%" ~ len ~ "d %)", + iota(1, n + 1) + .map!(c => n * ((r + c - 1 + n / 2) % n) + + ((r + 2 * c - 2) % n))); + + writeln("\nMagic constant: ", (n * n + 1) * n / 2); +} diff --git a/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-2.d b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-2.d new file mode 100644 index 0000000000..dd8824ea03 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-2.d @@ -0,0 +1,66 @@ +import std.stdio, std.conv, std.string, std.range, std.algorithm; + +uint[][] magicSquare(immutable uint n) pure nothrow @safe +in { + assert(n > 0 && n % 2 == 1); +} out(mat) { + // mat is square of the right size. + assert(mat.length == n); + assert(mat.all!(row => row.length == n)); + + immutable magic = mat[0].sum; + + // The sum of all rows is the same magic number. + assert(mat.all!(row => row.sum == magic)); + + // The sum of all columns is the same magic number. + //assert(mat.transposed.all!(col => col.sum == magic)); + assert(mat.dup.transposed.all!(col => col.sum == magic)); + + // The sum of the main diagonals is the same magic number. + assert(mat.enumerate.map!(ir => ir[1][ir[0]]).sum == magic); + //assert(mat.enumerate.map!({i, r} => r[i]).sum == magic); + assert(mat.enumerate.map!(ir => ir[1][ir[0]]).sum == magic); +} body { + enum M = (in uint x) pure nothrow @safe @nogc => (x + n - 1) % n; + auto m = new uint[][](n, n); + + uint i = 0; + uint j = n / 2; + foreach (immutable uint k; 1 .. n ^^ 2 + 1) { + m[i][j] = k; + if (m[M(i)][M(j)]) { + i = (i + 1) % n; + } else { + i = M(i); + j = M(j); + } + } + + return m; +} + +void showSquare(in uint[][] m) +in { + assert(m.all!(row => row.length == m[0].length)); +} body { + immutable maxLen = text(m.length ^^ 2).length.text; + writefln("%(%(%" ~ maxLen ~ "d %)\n%)", m); + writeln("\nMagic constant: ", m[0].sum); +} + +int main(in string[] args) { + if (args.length == 1) { + 5.magicSquare.showSquare; + return 0; + } else if (args.length == 2) { + immutable n = args[1].to!uint; + if (n > 0 && n % 2 == 1) { + n.magicSquare.showSquare; + return 0; + } + } + + stderr.writefln("Requires n odd and larger than 0."); + return 1; +} diff --git a/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-3.d b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-3.d new file mode 100644 index 0000000000..01c88203f6 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/D/magic-squares-of-odd-order-3.d @@ -0,0 +1,25 @@ +procedure main(A) + n := integer(!A) | 3 + write("Magic number: ",n*(n*n+1)/2) + sq := buildSquare(n) + showSquare(sq) +end + +procedure buildSquare(n) + sq := [: |list(n)\n :] + r := 0 + c := n/2 + every i := !(n*n) do { + /sq[r+1,c+1] := i + nr := (n+r-1)%n + nc := (c+1)%n + if /sq[nr+1,nc+1] then (r := nr,c := nc) else r := (r+1)%n + } + return sq +end + +procedure showSquare(sq) + n := *sq + s := *(n*n)+2 + every r := !sq do every writes(right(!r,s)|"\n") +end diff --git a/Task/Magic-squares-of-odd-order/Go/magic-squares-of-odd-order.go b/Task/Magic-squares-of-odd-order/Go/magic-squares-of-odd-order.go new file mode 100644 index 0000000000..6b63a10e0f --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Go/magic-squares-of-odd-order.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "log" +) + +func ms(n int) (int, []int) { + M := func(x int) int { return (x + n - 1) % n } + if n <= 0 || n&1 == 0 { + n = 5 + log.Println("forcing size", n) + } + m := make([]int, n*n) + i, j := 0, n/2 + for k := 1; k <= n*n; k++ { + m[i*n+j] = k + if m[M(i)*n+M(j)] != 0 { + i = (i + 1) % n + } else { + i, j = M(i), M(j) + } + } + return n, m +} + +func main() { + n, m := ms(5) + i := 2 + for j := 1; j <= n*n; j *= 10 { + i++ + } + f := fmt.Sprintf("%%%dd", i) + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + fmt.Printf(f, m[i*n+j]) + } + fmt.Println() + } +} diff --git a/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order.hs b/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order.hs new file mode 100644 index 0000000000..1aefe40541 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order.hs @@ -0,0 +1,62 @@ +-- as a translation from imperative code, this is probably not a "good" implementation +import Data.List + +type Var = (Int, Int, Int, Int) -- sx sy sz c + +magicSum :: Int -> Int +magicSum x = ((x * x + 1) `div` 2) * x + +wrapInc :: Int -> Int -> Int +wrapInc max x + | x + 1 == max = 0 + | otherwise = x + 1 + +wrapDec :: Int -> Int -> Int +wrapDec max x + | x == 0 = max - 1 + | otherwise = x - 1 + +isZero :: [[Int]] -> Int -> Int -> Bool +isZero m x y = m !! x !! y == 0 + +setAt :: (Int,Int) -> Int -> [[Int]] -> [[Int]] +setAt (x, y) val table + | (upper, current : lower) <- splitAt x table, + (left, this : right) <- splitAt y current + = upper ++ (left ++ val : right) : lower + | otherwise = error "Outside" + +create :: Int -> [[Int]] +create x = replicate x $ replicate x 0 + +cells :: [[Int]] -> Int +cells m = x*x where x = length m + +fill :: Var -> [[Int]] -> [[Int]] +fill (sx, sy, sz, c) m + | c < cells m = + if isZero m sx sy + then fill ((wrapInc sz sx), (wrapDec sz sy), sz, c + 1) (setAt (sx, sy) (c + 1) m) + else fill ((wrapDec sz sx), (wrapInc sz(wrapInc sz sy)), sz, c) m + | otherwise = m + +magicNumber :: Int -> [[Int]] +magicNumber d = transpose $ fill (d `div` 2, 0, d, 0) (create d) + +display :: [[Int]] -> String +display (x:xs) + | null xs = vdisplay x + | otherwise = vdisplay x ++ ('\n' : display xs) + +vdisplay :: [Int] -> String +vdisplay (x:xs) + | null xs = show x + | otherwise = show x ++ " " ++ vdisplay xs + + +magicSquare x = do + putStr "Magic Square of " + putStr $ show x + putStr " = " + putStrLn $ show $ magicSum x + putStrLn $ display $ magicNumber x diff --git a/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-1.j b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-1.j new file mode 100644 index 0000000000..1e74a7679b --- /dev/null +++ b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-1.j @@ -0,0 +1 @@ +ms=: i:@<.@-: |."0 1&|:^:2 >:@i.@,~ diff --git a/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-2.j b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-2.j new file mode 100644 index 0000000000..12d73318fe --- /dev/null +++ b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-2.j @@ -0,0 +1,4 @@ + >:@i.@,~ 3 +1 2 3 +4 5 6 +7 8 9 diff --git a/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-3.j b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-3.j new file mode 100644 index 0000000000..1172224a93 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-3.j @@ -0,0 +1,2 @@ + i:@<.@-: 3 +_1 0 1 diff --git a/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-4.j b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-4.j new file mode 100644 index 0000000000..12fde54fbd --- /dev/null +++ b/Task/Magic-squares-of-odd-order/J/magic-squares-of-odd-order-4.j @@ -0,0 +1,10 @@ + ms 5 + 9 15 16 22 3 +20 21 2 8 14 + 1 7 13 19 25 +12 18 24 5 6 +23 4 10 11 17 + ~.+/ms 5 +65 + ~.+/ms 101 +515201 diff --git a/Task/Magic-squares-of-odd-order/Java/magic-squares-of-odd-order.java b/Task/Magic-squares-of-odd-order/Java/magic-squares-of-odd-order.java new file mode 100644 index 0000000000..a1b696c1d5 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Java/magic-squares-of-odd-order.java @@ -0,0 +1,47 @@ +public class MagicSquare { + + public static void main(String[] args) { + int n = 5; + for (int[] row : magicSquareOdd(n)) { + for (int x : row) + System.out.format("%2s ", x); + System.out.println(); + } + System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); + } + + public static int[][] magicSquareOdd(final int base) { + if (base % 2 == 0 || base < 3) + throw new IllegalArgumentException("base must be odd and > 2"); + + int[][] grid = new int[base][base]; + int r = 0, number = 0; + int size = base * base; + + int c = base / 2; + while (number++ < size) { + grid[r][c] = number; + if (r == 0) { + if (c == base - 1) { + r++; + } else { + r = base - 1; + c++; + } + } else { + if (c == base - 1) { + r--; + c = 0; + } else { + if (grid[r - 1][c + 1] == 0) { + r--; + c++; + } else { + r++; + } + } + } + } + return grid; + } +} diff --git a/Task/Magic-squares-of-odd-order/Mathematica/magic-squares-of-odd-order.math b/Task/Magic-squares-of-odd-order/Mathematica/magic-squares-of-odd-order.math new file mode 100644 index 0000000000..4f7515014d --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Mathematica/magic-squares-of-odd-order.math @@ -0,0 +1,7 @@ +rp[v_, pos_] := RotateRight[v, (Length[v] + 1)/2 - pos]; +rho[m_] := MapIndexed[rp, m]; +magic[n_] := + rho[Transpose[rho[Table[i*n + j, {i, 0, n - 1}, {j, 1, n}]]]]; + +square = magic[11] // Grid +Print["Magic number is ", Total[square[[1, 1]]]] diff --git a/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-1.maxima b/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-1.maxima new file mode 100644 index 0000000000..aa537bddce --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-1.maxima @@ -0,0 +1,17 @@ +wrap1(i):= if i>%n% then 1 else if i<1 then %n% else i; +wrap(P):=maplist('wrap1, P); + +uprigth(P):= wrap(P + [-1, 1]); +down(P):= wrap(P + [1, 0]); + +magic(n):=block([%n%: n, + M: zeromatrix (n, n), + P: [1, (n + 1)/2], + m: 1, Pc], + do ( + M[P[1],P[2]]: m, + m: m + 1, + if m>n^2 then return(M), + Pc: uprigth(P), + if M[Pc[1],Pc[2]]=0 then P: Pc + else while(M[P[1],P[2]]#0) do P: down(P))); diff --git a/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-2.maxima b/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-2.maxima new file mode 100644 index 0000000000..3df06ba691 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Maxima/magic-squares-of-odd-order-2.maxima @@ -0,0 +1,33 @@ +(%i6) magic(3); + [ 8 1 6 ] + [ ] +(%o6) [ 3 5 7 ] + [ ] + [ 4 9 2 ] +(%i7) magic(5); + [ 17 24 1 8 15 ] + [ ] + [ 23 5 7 14 16 ] + [ ] +(%o7) [ 4 6 13 20 22 ] + [ ] + [ 10 12 19 21 3 ] + [ ] + [ 11 18 25 2 9 ] +(%i8) magic(7); + [ 30 39 48 1 10 19 28 ] + [ ] + [ 38 47 7 9 18 27 29 ] + [ ] + [ 46 6 8 17 26 35 37 ] + [ ] +(%o8) [ 5 14 16 25 34 36 45 ] + [ ] + [ 13 15 24 33 42 44 4 ] + [ ] + [ 21 23 32 41 43 3 12 ] + [ ] + [ 22 31 40 49 2 11 20 ] +/* magic number for n=7 */ +(%i9) lsum(q, q, first(magic(7))); +(%o9) 175 diff --git a/Task/Magic-squares-of-odd-order/PL-I/magic-squares-of-odd-order.pli b/Task/Magic-squares-of-odd-order/PL-I/magic-squares-of-odd-order.pli new file mode 100644 index 0000000000..c67f495375 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/PL-I/magic-squares-of-odd-order.pli @@ -0,0 +1,38 @@ +magic: procedure options (main); /* 18 April 2014 */ + declare n fixed binary; + + put skip list ('What is the order of the magic square?'); + get list (n); + if n < 3 | iand(n, 1) = 0 then + do; put skip list ('The value is out of range'); stop; end; + put skip list ('The order is ' || trim(n)); + + begin; + declare m(n, n) fixed, (i, j, k) fixed binary; + + on subrg snap put data (i, j, k); + m = 0; + i = 1; j = (n+1)/2; + + do k = 1 to n*n; + if m(i,j) = 0 then + m(i,j) = k; + else + do; + i = i + 2; j = j + 1; + if i > n then i = mod(i,n); + if j > n then j = 1; + m(i,j) = k; + end; + i = i - 1; j = j - 1; + if i < 1 then i = n; + if j < 1 then j = n; + end; + + do i = 1 to n; + put skip edit (m(i, *)) (f(4)); + end; + + put skip list ('The magic number is' || sum(m(1,*))); + end; +end magic; diff --git a/Task/Magic-squares-of-odd-order/Perl-6/magic-squares-of-odd-order.pl6 b/Task/Magic-squares-of-odd-order/Perl-6/magic-squares-of-odd-order.pl6 new file mode 100644 index 0000000000..ba800b12f3 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Perl-6/magic-squares-of-odd-order.pl6 @@ -0,0 +1,16 @@ +sub MAIN (Int $n = 5) { + + note "Sorry, must be a positive odd integer." and exit if $n %% 2 or $n < 0; + + my $x = $n/2; + my $y = 0; + my $i = 1; + my @sq; + + @sq[($i % $n ?? $y-- !! $y++) % $n][($i % $n ?? $x++ !! $x) % $n] = $i++ for ^($n * $n); + + my $f = "%{$i.chars}d"; + say .fmt($f, ' ') for @sq; + + say "\nThe magic number is ", [+] @sq[0].list; +} diff --git a/Task/Magic-squares-of-odd-order/Python/magic-squares-of-odd-order.py b/Task/Magic-squares-of-odd-order/Python/magic-squares-of-odd-order.py new file mode 100644 index 0000000000..1d0c3bca3d --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Python/magic-squares-of-odd-order.py @@ -0,0 +1,45 @@ +>>> def magic(n): + for row in range(1, n + 1): + print(' '.join('%*i' % (len(str(n**2)), cell) for cell in + (n * ((row + col - 1 + n // 2) % n) + + ((row + 2 * col - 2) % n) + 1 + for col in range(1, n + 1)))) + print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) + + +>>> for n in (5, 3, 7): + print('\nOrder %i\n=======' % n) + magic(n) + + + +Order 5 +======= +17 24 1 8 15 +23 5 7 14 16 + 4 6 13 20 22 +10 12 19 21 3 +11 18 25 2 9 + +All sum to magic number 65 + +Order 3 +======= +8 1 6 +3 5 7 +4 9 2 + +All sum to magic number 15 + +Order 7 +======= +30 39 48 1 10 19 28 +38 47 7 9 18 27 29 +46 6 8 17 26 35 37 + 5 14 16 25 34 36 45 +13 15 24 33 42 44 4 +21 23 32 41 43 3 12 +22 31 40 49 2 11 20 + +All sum to magic number 175 +>>> diff --git a/Task/Magic-squares-of-odd-order/README b/Task/Magic-squares-of-odd-order/README new file mode 100644 index 0000000000..2e4716d3b0 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Magic_squares_of_odd_order diff --git a/Task/Magic-squares-of-odd-order/REXX/magic-squares-of-odd-order.rexx b/Task/Magic-squares-of-odd-order/REXX/magic-squares-of-odd-order.rexx new file mode 100644 index 0000000000..824dae647e --- /dev/null +++ b/Task/Magic-squares-of-odd-order/REXX/magic-squares-of-odd-order.rexx @@ -0,0 +1,18 @@ +/*REXX program generates and displays true magic squares (for odd N). */ +parse arg N .; if N=='' then N=5 /*matrix size ¬given? Use default*/ +w=length(N*N); r=2; c=(n+1)%2-1 /*define initial row and column. */ +@.=. /* [↓] uses the Siamese method.*/ + do j=1 for n*n; br=r==N & c==N; r=r-1; c=c+1 /*BR=bottom right*/ + if r<1 & c>N then do; r=r+2; c=c-1; end /*R under, C over*/ + if r<1 then r=n; if r>n then r=1; if c>n then c=1 /*overflow*/ + if @.r.c\==. then do; r=r+2; c=c-1; if br then do; r=N; c=c+1; end;end + @.r.c=j /*assign #───►square matrix cell.*/ + end /*j*/ /* [↑] can handle even N matrix.*/ + /* [↓] displays (aligned) matrix*/ + do r=1 for N; _= /*display 1 matrix row at a time.*/ + do c=1 for N; _=_ right(@.r.c, w); end /*c*/ /*build row*/ + say substr(_,2) /*row has an extra leading blank.*/ + end /*c*/ /* [↑] also right-justified #s.*/ +say /*might as well show a blank line*/ +if N//2 then say 'The magic number (or magic constant is): ' N*(n*n+1)%2 + /*stick a fork in it, we're done.*/ diff --git a/Task/Magic-squares-of-odd-order/Racket/magic-squares-of-odd-order.rkt b/Task/Magic-squares-of-odd-order/Racket/magic-squares-of-odd-order.rkt new file mode 100644 index 0000000000..79ce6b0a9c --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Racket/magic-squares-of-odd-order.rkt @@ -0,0 +1,33 @@ +#lang racket +;; Using "helpful formulae" in: +;; http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order +(define (squares n) n) + +(define (last-no n) (sqr n)) + +(define (middle-no n) (/ (add1 (sqr n)) 2)) + +(define (M n) (* n (middle-no n))) + +(define ((Ith-row-Jth-col n) I J) + (+ (* (modulo (+ I J -1 (exact-floor (/ n 2))) n) n) + (modulo (+ I (* 2 J) -2) n) + 1)) + +(define (magic-square n) + (define IrJc (Ith-row-Jth-col n)) + (for/list ((I (in-range 1 (add1 n)))) (for/list ((J (in-range 1 (add1 n)))) (IrJc I J)))) + +(define (fmt-list-of-lists l-o-l width) + (string-join + (for/list ((row l-o-l)) + (string-join (map (λ (x) (~a #:align 'right #:width width x)) row) " ")) + "\n")) + +(define (show-magic-square n) + (format "MAGIC SQUARE ORDER:~a~%~a~%MAGIC NUMBER:~a~%" + n (fmt-list-of-lists (magic-square n) (+ (order-of-magnitude (last-no n)) 1)) (M n))) + +(displayln (show-magic-square 3)) +(displayln (show-magic-square 5)) +(displayln (show-magic-square 9)) diff --git a/Task/Magic-squares-of-odd-order/Ruby/magic-squares-of-odd-order.rb b/Task/Magic-squares-of-odd-order/Ruby/magic-squares-of-odd-order.rb new file mode 100644 index 0000000000..e9c7338ea6 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Ruby/magic-squares-of-odd-order.rb @@ -0,0 +1,10 @@ +def odd_magic_square(n) + raise ArgumentError "Need odd positive number" if n.even? || n <= 0 + n.times.map{|i| n.times.map{|j| n*((i+j+1+n/2)%n) + ((i+2*j-5)%n) + 1} } +end + +[3, 5, 9].each do |n| + puts "\nSize #{n}, magic sum #{(n*n+1)/2*n}" + fmt = "%#{(n*n).to_s.size + 1}d" * n + odd_magic_square(n).each{|row| puts fmt % row} +end diff --git a/Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust b/Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust new file mode 100644 index 0000000000..4ab4fa8cc8 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust @@ -0,0 +1,13 @@ +fn main() { + let n = 9; + let mut square = Vec::from_fn(n, |_| Vec::from_fn(n, |_| 0u)); + for (i, row) in square.iter_mut().enumerate() { + for (j, e) in row.iter_mut().enumerate() { + *e = n * (((i + 1) + (j + 1) - 1 + (n >> 1)) % n) + (((i + 1) + (2 * (j + 1)) - 2) % n) + 1; + print!("{:3} ", e); + } + println!(""); + } + let sum = n * (((n * n) + 1) / 2); + println!("The sum of the square is {}.", sum); +} diff --git a/Task/Magic-squares-of-odd-order/Seed7/magic-squares-of-odd-order.seed7 b/Task/Magic-squares-of-odd-order/Seed7/magic-squares-of-odd-order.seed7 new file mode 100644 index 0000000000..75153544a0 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Seed7/magic-squares-of-odd-order.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + +const func integer: succ (in integer: num, in integer: max) is + return succ(num mod max); + +const func integer: pred (in integer: num, in integer: max) is + return succ((num - 2) mod max); + +const proc: main is func + local + var integer: size is 3; + var array array integer: magic is 0 times 0 times 0; + var integer: row is 1; + var integer: column is 1; + var integer: number is 0; + begin + if length(argv(PROGRAM)) >= 1 then + size := integer parse (argv(PROGRAM)[1]); + end if; + magic := size times size times 0; + column := succ(size div 2); + for number range 1 to size ** 2 do + magic[row][column] := number; + if magic[pred(row, size)][succ(column, size)] = 0 then + row := pred(row, size); + column := succ(column, size); + else + row := succ(row, size); + end if; + end for; + for key row range magic do + for key column range magic[row] do + write(magic[row][column] lpad 4); + end for; + writeln; + end for; + end func; diff --git a/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-1.tcl b/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-1.tcl new file mode 100644 index 0000000000..8ea6268d84 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-1.tcl @@ -0,0 +1,18 @@ +proc magicSquare {order} { + if {!($order & 1) || $order < 0} { + error "order must be odd and positive" + } + set s [lrepeat $order [lrepeat $order 0]] + set x [expr {$order / 2}] + set y 0 + for {set i 1} {$i <= $order**2} {incr i} { + lset s $y $x $i + set x [expr {($x + 1) % $order}] + set y [expr {($y - 1) % $order}] + if {[lindex $s $y $x]} { + set x [expr {($x - 1) % $order}] + set y [expr {($y + 2) % $order}] + } + } + return $s +} diff --git a/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-2.tcl b/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-2.tcl new file mode 100644 index 0000000000..c712906193 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Tcl/magic-squares-of-odd-order-2.tcl @@ -0,0 +1,5 @@ +package require Tcl 8.6 + +set square [magicSquare 5] +puts [join [lmap row $square {join [lmap n $row {format "%2s" $n}]}] "\n"] +puts "magic number = [tcl::mathop::+ {*}[lindex $square 0]]" diff --git a/Task/Make-directory-path/00DESCRIPTION b/Task/Make-directory-path/00DESCRIPTION new file mode 100644 index 0000000000..f86919663c --- /dev/null +++ b/Task/Make-directory-path/00DESCRIPTION @@ -0,0 +1,9 @@ +Create a directory and any missing parents. + +This task is named after the posix [http://www.unix.com/man-page/POSIX/0/mkdir/ mkdir -p] command, and several libraries which implement the same behavior. + +Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. +If the directory already exists, return successfully. +Ideally implementations will work equally well cross-platform (on windows, linux, and OS X). + +It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented. diff --git a/Task/Make-directory-path/00META.yaml b/Task/Make-directory-path/00META.yaml new file mode 100644 index 0000000000..40458d9f21 --- /dev/null +++ b/Task/Make-directory-path/00META.yaml @@ -0,0 +1,2 @@ +--- +note: File System Operations diff --git a/Task/Make-directory-path/Clojure/make-directory-path.clj b/Task/Make-directory-path/Clojure/make-directory-path.clj new file mode 100644 index 0000000000..f8b8898d8a --- /dev/null +++ b/Task/Make-directory-path/Clojure/make-directory-path.clj @@ -0,0 +1,5 @@ +(defn mkdirp [path] + (let [dir (java.io.File. path)] + (if (.exists dir) + true + (.mkdirs dir)))) diff --git a/Task/Make-directory-path/Go/make-directory-path.go b/Task/Make-directory-path/Go/make-directory-path.go new file mode 100644 index 0000000000..13bd7dce60 --- /dev/null +++ b/Task/Make-directory-path/Go/make-directory-path.go @@ -0,0 +1 @@ + os.MkdirAll("/tmp/some/path/to/dir", 0770) diff --git a/Task/Make-directory-path/Java/make-directory-path.java b/Task/Make-directory-path/Java/make-directory-path.java new file mode 100644 index 0000000000..bc899bd00c --- /dev/null +++ b/Task/Make-directory-path/Java/make-directory-path.java @@ -0,0 +1,14 @@ +import java.io.File; + +public interface Test { + + public static void main(String[] args) { + try { + File f = new File("C:/parent/test"); + if (f.mkdirs()) + System.out.println("path successfully created"); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/Task/Make-directory-path/JavaScript/make-directory-path.js b/Task/Make-directory-path/JavaScript/make-directory-path.js new file mode 100644 index 0000000000..651c731261 --- /dev/null +++ b/Task/Make-directory-path/JavaScript/make-directory-path.js @@ -0,0 +1,27 @@ +var path = require('path'); +var fs = require('fs'); + +function mkdirp (p, cb) { + cb = cb || function () {}; + p = path.resolve(p); + + fs.mkdir(p, function (er) { + if (!er) { + return cb(null); + } + switch (er.code) { + case 'ENOENT': + // The directory doesn't exist. Make its parent and try again. + mkdirp(path.dirname(p), function (er) { + if (er) cb(er); + else mkdirp(p, cb); + }); + break; + + // In the case of any other error, something is borked. + default: + cb(er); + break; + } + }); +} diff --git a/Task/Make-directory-path/Mathematica/make-directory-path.math b/Task/Make-directory-path/Mathematica/make-directory-path.math new file mode 100644 index 0000000000..362c179b22 --- /dev/null +++ b/Task/Make-directory-path/Mathematica/make-directory-path.math @@ -0,0 +1 @@ +mkdirp[path_] := Quiet[CreateDirectory[path,{CreateIntermediateDirectories->True}],{CreateDirectory::filex}] diff --git a/Task/Make-directory-path/Perl-6/make-directory-path.pl6 b/Task/Make-directory-path/Perl-6/make-directory-path.pl6 new file mode 100644 index 0000000000..4fdb0d544b --- /dev/null +++ b/Task/Make-directory-path/Perl-6/make-directory-path.pl6 @@ -0,0 +1 @@ +mkdir 'path/to/dir' diff --git a/Task/Make-directory-path/Python/make-directory-path-1.py b/Task/Make-directory-path/Python/make-directory-path-1.py new file mode 100644 index 0000000000..4f3c5ed137 --- /dev/null +++ b/Task/Make-directory-path/Python/make-directory-path-1.py @@ -0,0 +1,23 @@ +from errno import EEXIST +from os import mkdir, curdir +from os.path import split, exists + +def mkdirp(path, mode=0777): + head, tail = split(path) + if not tail: + head, tail = split(head) + if head and tail and not exists(head): + try: + mkdirp(head, mode) + except OSError as e: + # be happy if someone already created the path + if e.errno != EEXIST: + raise + if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists + return + try: + mkdir(path, mode) + except OSError as e: + # be happy if someone already created the path + if e.errno != EEXIST: + raise diff --git a/Task/Make-directory-path/Python/make-directory-path-2.py b/Task/Make-directory-path/Python/make-directory-path-2.py new file mode 100644 index 0000000000..cbbcb3f436 --- /dev/null +++ b/Task/Make-directory-path/Python/make-directory-path-2.py @@ -0,0 +1,7 @@ +def mkdirp(path): + try: + os.makedirs(path) + except OSError as exc: # Python >2.5 + if exc.errno == errno.EEXIST and os.path.isdir(path): + pass + else: raise diff --git a/Task/Make-directory-path/Python/make-directory-path-3.py b/Task/Make-directory-path/Python/make-directory-path-3.py new file mode 100644 index 0000000000..813eac69b1 --- /dev/null +++ b/Task/Make-directory-path/Python/make-directory-path-3.py @@ -0,0 +1,2 @@ +def mkdirp(path): + os.makedirs(path, exist_ok=True) diff --git a/Task/Make-directory-path/README b/Task/Make-directory-path/README new file mode 100644 index 0000000000..4355a45f95 --- /dev/null +++ b/Task/Make-directory-path/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Make_directory_path diff --git a/Task/Make-directory-path/REXX/make-directory-path.rexx b/Task/Make-directory-path/REXX/make-directory-path.rexx new file mode 100644 index 0000000000..b78ad4ce49 --- /dev/null +++ b/Task/Make-directory-path/REXX/make-directory-path.rexx @@ -0,0 +1,5 @@ +/*REXX program creates a directory and all its parent paths as necessary*/ +trace off /*suppress possible warning msgs.*/ +dPath = 'path\to\dir' +'MKDIR' dPath "2>nul" /*alias could be used: MD Dpath */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Make-directory-path/Racket/make-directory-path.rkt b/Task/Make-directory-path/Racket/make-directory-path.rkt new file mode 100644 index 0000000000..21df17e577 --- /dev/null +++ b/Task/Make-directory-path/Racket/make-directory-path.rkt @@ -0,0 +1,22 @@ +#lang racket +(define path-str "/tmp/woo/yay") +(define path/..-str "/tmp/woo") + +;; clean up from a previous run +(when (directory-exists? path-str) + (delete-directory path-str) + (delete-directory path/..-str)) +;; delete-directory/files could also be used -- but that requires goggles and rubber +;; gloves to handle safely! + +(define (report-path-exists) + (printf "~s exists (as a directory?):~a~%~s exists (as a directory?):~a~%~%" + path/..-str (directory-exists? path/..-str) + path-str (directory-exists? path-str))) + +(report-path-exists) + +;; Really ... this is the only bit that matters! +(make-directory* path-str) + +(report-path-exists) diff --git a/Task/Make-directory-path/Ruby/make-directory-path.rb b/Task/Make-directory-path/Ruby/make-directory-path.rb new file mode 100644 index 0000000000..375ef7fd4b --- /dev/null +++ b/Task/Make-directory-path/Ruby/make-directory-path.rb @@ -0,0 +1,2 @@ +require 'fileutils' +FileUtils.mkdir_p("path/to/dir") diff --git a/Task/Make-directory-path/Scala/make-directory-path-1.scala b/Task/Make-directory-path/Scala/make-directory-path-1.scala new file mode 100644 index 0000000000..ab701a72ba --- /dev/null +++ b/Task/Make-directory-path/Scala/make-directory-path-1.scala @@ -0,0 +1 @@ +new java.io.File("/path/to/dir").mkdirs diff --git a/Task/Make-directory-path/Scala/make-directory-path-2.scala b/Task/Make-directory-path/Scala/make-directory-path-2.scala new file mode 100644 index 0000000000..f15f146811 --- /dev/null +++ b/Task/Make-directory-path/Scala/make-directory-path-2.scala @@ -0,0 +1,6 @@ +import java.io.File + +def mkdirs(path: List[String]) = // return true if path was created + path.tail.foldLeft(new File(path.head)){(a,b) => a.mkdir; new File(a,b)}.mkdir + +mkdirs(List("/path", "to", "dir")) diff --git a/Task/Make-directory-path/Tcl/make-directory-path.tcl b/Task/Make-directory-path/Tcl/make-directory-path.tcl new file mode 100644 index 0000000000..24fb0ea37b --- /dev/null +++ b/Task/Make-directory-path/Tcl/make-directory-path.tcl @@ -0,0 +1 @@ +file mkdir ./path/to/dir diff --git a/Task/Make-directory-path/UNIX-Shell/make-directory-path.sh b/Task/Make-directory-path/UNIX-Shell/make-directory-path.sh new file mode 100644 index 0000000000..f2241d58b3 --- /dev/null +++ b/Task/Make-directory-path/UNIX-Shell/make-directory-path.sh @@ -0,0 +1 @@ +function mkdirp() { mkdir -p "$1"; } diff --git a/Task/Maximum-triangle-path-sum/00DESCRIPTION b/Task/Maximum-triangle-path-sum/00DESCRIPTION new file mode 100644 index 0000000000..2c05aded4c --- /dev/null +++ b/Task/Maximum-triangle-path-sum/00DESCRIPTION @@ -0,0 +1,35 @@ +Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: +
+                          55
+                        94 48
+                       95 30 96
+                     77 71 26 67
+ +One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. + +Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. + +'''Task:''' find the maximum total in the triangle below: +
+                          55
+                        94 48
+                       95 30 96
+                     77 71 26 67
+                    97 13 76 38 45
+                  07 36 79 16 37 68
+                 48 07 09 18 70 26 06
+               18 72 79 46 59 79 29 90
+              20 76 87 11 32 07 07 49 18
+            27 83 58 35 71 11 25 57 29 85
+           14 64 36 96 27 11 58 56 92 18 55
+         02 90 03 60 48 49 41 46 33 36 47 23
+        92 50 48 02 36 59 42 79 72 20 82 77 42
+      56 78 38 80 39 75 02 71 66 66 01 03 55 72
+     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
+   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
+  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
+27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
+ +Such numbers can be included in the solution code, or read from a "triangle.txt" file. + +This task is derived from the [http://projecteuler.net/problem=18 Euler Problem #18]. diff --git a/Task/Maximum-triangle-path-sum/ALGOL-68/maximum-triangle-path-sum.alg b/Task/Maximum-triangle-path-sum/ALGOL-68/maximum-triangle-path-sum.alg new file mode 100644 index 0000000000..435574a23e --- /dev/null +++ b/Task/Maximum-triangle-path-sum/ALGOL-68/maximum-triangle-path-sum.alg @@ -0,0 +1,46 @@ +# create a triangular array of the required values # + + [ 1]INT row 1 := ( 55 ); + [ 2]INT row 2 := ( 94, 48 ); + [ 3]INT row 3 := ( 95, 30, 96 ); + [ 4]INT row 4 := ( 77, 71, 26, 67 ); + [ 5]INT row 5 := ( 97, 13, 76, 38, 45 ); + [ 6]INT row 6 := ( 07, 36, 79, 16, 37, 68 ); + [ 7]INT row 7 := ( 48, 07, 09, 18, 70, 26, 06 ); + [ 8]INT row 8 := ( 18, 72, 79, 46, 59, 79, 29, 90 ); + [ 9]INT row 9 := ( 20, 76, 87, 11, 32, 07, 07, 49, 18 ); + [10]INT row 10 := ( 27, 83, 58, 35, 71, 11, 25, 57, 29, 85 ); + [11]INT row 11 := ( 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55 ); + [12]INT row 12 := ( 02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23 ); + [13]INT row 13 := ( 92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42 ); + [14]INT row 14 := ( 56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72 ); + [15]INT row 15 := ( 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36 ); + [16]INT row 16 := ( 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52 ); + [17]INT row 17 := ( 06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15 ); + [18]INT row 18 := ( 27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 ); + +[18]REF[]INT triangle := ( row 1, row 2, row 3, row 4, row 5, row 6 + , row 7, row 8, row 9, row 10, row 11, row 12 + , row 13, row 14, row 15, row 16, row 17, row 18 + ); + +PROC max = ( INT a, INT b )INT: IF a > b THEN a ELSE b FI; + +# working backwards, we replace the elements of each row with the sum of that # +# element and the maximum of the two elements below it. # +# That destroys the triangle but leaves element [1][1] equal to the required # +# maximum # + + +FOR row FROM UPB triangle - 1 BY -1 TO 1 +DO + FOR element FROM 1 TO UPB triangle[row] + DO + # the elements "under" triangle[row][element] are # + # triangle[row+1][element] and triangle[row+1][element+1] # + triangle[row][element] + +:= max( triangle[row+1][element], triangle[row+1][element+1] ) + OD +OD; + +print( ( triangle[1][1], newline ) ) diff --git a/Task/Maximum-triangle-path-sum/Ada/maximum-triangle-path-sum.ada b/Task/Maximum-triangle-path-sum/Ada/maximum-triangle-path-sum.ada new file mode 100644 index 0000000000..3b71f953c6 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Ada/maximum-triangle-path-sum.ada @@ -0,0 +1,41 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Max_Sum is + + Triangle : array (Positive range <>) of integer := + (55, + 94, 48, + 95, 30, 96, + 77, 71, 26, 67, + 97, 13, 76, 38, 45, + 07, 36, 79, 16, 37, 68, + 48, 07, 09, 18, 70, 26, 06, + 18, 72, 79, 46, 59, 79, 29, 90, + 20, 76, 87, 11, 32, 07, 07, 49, 18, + 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, + 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, + 02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23, + 92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42, + 56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72, + 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, + 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52, + 06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15, + 27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93); + + Last : Integer := Triangle'Length; + Tn : Integer := 1; + +begin + while (Tn * (Tn + 1) / 2) < Last loop + Tn := Tn + 1; + end loop; + for N in reverse 2 .. Tn loop + for I in 2 .. N loop + Triangle (Last - N) := Triangle (Last - N) + + Integer'Max(Triangle (Last - 1), Triangle (Last)); + Last := Last - 1; + end loop; + Last := Last - 1; + end loop; + Put_Line(Integer'Image(Triangle(1))); +end Max_Sum; diff --git a/Task/Maximum-triangle-path-sum/Bracmat/maximum-triangle-path-sum.bracmat b/Task/Maximum-triangle-path-sum/Bracmat/maximum-triangle-path-sum.bracmat new file mode 100644 index 0000000000..1d9d199e2a --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Bracmat/maximum-triangle-path-sum.bracmat @@ -0,0 +1,44 @@ +( " + 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 +" + : ?triangle +& ( max + = a b + . !arg:(?a.?b)&(!a:>!b|!b) + ) +& 0:?accumulator +& whl + ' ( @(!triangle:?row (\n|\r) ?triangle) + & :?newaccumulator + & 0:?first + & whl + ' ( @(!row:? #%?n (" " ?row|:?row)) + & !accumulator:#%?second ?accumulator + & !newaccumulator max$(!first.!second)+!n:?newaccumulator + & !second:?first + ) + & !newaccumulator 0:?accumulator + ) +& ( -1:?Max + & !accumulator + : ? (%@:>!Max:?Max&~) ? + | out$!Max + ) +) diff --git a/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp new file mode 100644 index 0000000000..880efae094 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp @@ -0,0 +1,43 @@ +#include + +int main( int argc, char* argv[] ) +{ + int triangle[] = + { + 55, + 94, 48, + 95, 30, 96, + 77, 71, 26, 67, + 97, 13, 76, 38, 45, + 7, 36, 79, 16, 37, 68, + 48, 7, 9, 18, 70, 26, 6, + 18, 72, 79, 46, 59, 79, 29, 90, + 20, 76, 87, 11, 32, 7, 7, 49, 18, + 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, + 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, + 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, + 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, + 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, + 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, + 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, + 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, + 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 + }; + + int last = sizeof( triangle ) / sizeof( int ), + tn = 1; + while( ( tn * ( tn + 1 ) / 2 ) < last ) tn += 1; + + last--; + for( int n = tn; n >= 2; n-- ) + { + for( int i = 2; i <= n; i++ ) + { + triangle[last - n] = triangle[last - n] + std::max( triangle[last - 1], triangle[last] ); + last--; + } + last--; + } + std::cout << "Maximum total: " << triangle[0] << "\n\n"; + return system( "pause" ); +} diff --git a/Task/Maximum-triangle-path-sum/C/maximum-triangle-path-sum.c b/Task/Maximum-triangle-path-sum/C/maximum-triangle-path-sum.c new file mode 100644 index 0000000000..63702e2958 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/C/maximum-triangle-path-sum.c @@ -0,0 +1,45 @@ +#include +#include + +#define max(x,y) ((x) > (y) ? (x) : (y)) + +int tri[] = { + 55, + 94, 48, + 95, 30, 96, + 77, 71, 26, 67, + 97, 13, 76, 38, 45, + 7, 36, 79, 16, 37, 68, + 48, 7, 9, 18, 70, 26, 6, + 18, 72, 79, 46, 59, 79, 29, 90, + 20, 76, 87, 11, 32, 7, 7, 49, 18, + 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, + 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, + 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, + 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, + 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, + 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, + 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, + 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, + 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 +}; + +int main(void) +{ + const int len = sizeof(tri) / sizeof(tri[0]); + const int base = (sqrt(8*len + 1) - 1) / 2; + int step = base - 1; + int stepc = 0; + + int i; + for (i = len - base - 1; i >= 0; --i) { + tri[i] += max(tri[i + step], tri[i + step + 1]); + if (++stepc == step) { + step--; + stepc = 0; + } + } + + printf("%d\n", tri[0]); + return 0; +} diff --git a/Task/Maximum-triangle-path-sum/Common-Lisp/maximum-triangle-path-sum.lisp b/Task/Maximum-triangle-path-sum/Common-Lisp/maximum-triangle-path-sum.lisp new file mode 100644 index 0000000000..47178d00b2 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Common-Lisp/maximum-triangle-path-sum.lisp @@ -0,0 +1,24 @@ +(defun find-max-path-sum (s) + (let ((triangle (loop for line = (read-line s NIL NIL) + while line + collect (with-input-from-string (str line) + (loop for n = (read str NIL NIL) + while n + collect n))))) + (flet ((get-max-of-pairs (xs) + (maplist (lambda (ys) + (and (cdr ys) (max (car ys) (cadr ys)))) + xs))) + (car (reduce (lambda (xs ys) + (mapcar #'+ (get-max-of-pairs xs) ys)) + (reverse triangle)))))) + +(defparameter *small-triangle* + " 55 + 94 48 + 95 30 96 + 77 71 26 67") +(format T "~a~%" (with-input-from-string (s *small-triangle*) + (find-max-path-sum s))) +(format T "~a~%" (with-open-file (f "triangle.txt") + (find-max-path-sum f))) diff --git a/Task/Maximum-triangle-path-sum/D/maximum-triangle-path-sum.d b/Task/Maximum-triangle-path-sum/D/maximum-triangle-path-sum.d new file mode 100644 index 0000000000..14ccb96671 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/D/maximum-triangle-path-sum.d @@ -0,0 +1,9 @@ +void main() { + import std.stdio, std.algorithm, std.range, std.file, std.conv; + + "triangle.txt".File.byLine.map!split.map!(to!(int[])).array.retro + .reduce!((x, y) => zip(y, x, x.dropOne) + .map!(t => t[0] + t[1 .. $].max) + .array)[0] + .writeln; +} diff --git a/Task/Maximum-triangle-path-sum/Go/maximum-triangle-path-sum.go b/Task/Maximum-triangle-path-sum/Go/maximum-triangle-path-sum.go new file mode 100644 index 0000000000..78efd71d24 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Go/maximum-triangle-path-sum.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "strconv" + "strings" +) + +const t = ` 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` + +func main() { + lines := strings.Split(t, "\n") + f := strings.Fields(lines[len(lines)-1]) + d := make([]int, len(f)) + var err error + for i, s := range f { + if d[i], err = strconv.Atoi(s); err != nil { + panic(err) + } + } + d1 := d[1:] + var l, r, u int + for row := len(lines) - 2; row >= 0; row-- { + l = d[0] + for i, s := range strings.Fields(lines[row]) { + if u, err = strconv.Atoi(s); err != nil { + panic(err) + } + if r = d1[i]; l > r { + d[i] = u + l + } else { + d[i] = u + r + } + l = r + } + } + fmt.Println(d[0]) +} diff --git a/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs b/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs new file mode 100644 index 0000000000..b50d00199b --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs @@ -0,0 +1,5 @@ +parse = map (map read . words) . lines +f x y z = x + max y z +g xs ys = zipWith3 f xs ys $ tail ys +solve = head . foldr1 g +main = readFile "triangle.txt" >>= print . solve . parse diff --git a/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-1.j b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-1.j new file mode 100644 index 0000000000..0e169a5267 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-1.j @@ -0,0 +1,2 @@ +padTri=: 0 ". [: ];._2 ] NB. parse triangle and pad with zeros +maxSum=: [: {. (+ (0 ,~ 2 >./\ ]))/ NB. find max triangle path sum diff --git a/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-2.j b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-2.j new file mode 100644 index 0000000000..c28b1b079a --- /dev/null +++ b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-2.j @@ -0,0 +1,2 @@ + maxSum padTri freads 'triangle.txt' +1320 diff --git a/Task/Maximum-triangle-path-sum/Java/maximum-triangle-path-sum.java b/Task/Maximum-triangle-path-sum/Java/maximum-triangle-path-sum.java new file mode 100644 index 0000000000..1ff2f01c6a --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Java/maximum-triangle-path-sum.java @@ -0,0 +1,19 @@ +import java.nio.file.*; +import static java.util.Arrays.stream; + +public class MaxPathSum { + + public static void main(String[] args) throws Exception { + int[][] data = Files.lines(Paths.get("triangle.txt")) + .map(s -> stream(s.trim().split("\\s+")) + .mapToInt(Integer::parseInt) + .toArray()) + .toArray(int[][]::new); + + for (int r = data.length - 1; r > 0; r--) + for (int c = 0; c < data[r].length - 1; c++) + data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); + + System.out.println(data[0][0]); + } +} diff --git a/Task/Maximum-triangle-path-sum/Mathematica/maximum-triangle-path-sum.math b/Task/Maximum-triangle-path-sum/Mathematica/maximum-triangle-path-sum.math new file mode 100644 index 0000000000..cb6a6ad397 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Mathematica/maximum-triangle-path-sum.math @@ -0,0 +1,4 @@ +nums={{55},{94,48},{95,30,96},{77,71,26,67},{97,13,76,38,45},{7,36,79,16,37,68},{48,7,9,18,70,26,6},{18,72,79,46,59,79,29,90},{20,76,87,11,32,7,7,49,18},{27,83,58,35,71,11,25,57,29,85},{14,64,36,96,27,11,58,56,92,18,55},{2,90,3,60,48,49,41,46,33,36,47,23},{92,50,48,2,36,59,42,79,72,20,82,77,42},{56,78,38,80,39,75,2,71,66,66,1,3,55,72},{44,25,67,84,71,67,11,61,40,57,58,89,40,56,36},{85,32,25,85,57,48,84,35,47,62,17,1,1,99,89,52},{6,71,28,75,94,48,37,10,23,51,6,48,53,18,74,98,15},{27,2,92,23,8,71,76,84,15,52,92,63,81,10,44,10,69,93}}; +ClearAll[DoStep,MaximumTrianglePathSum] +DoStep[lst1_List,lst2_List]:=lst2+Join[{First[lst1]},Max/@Partition[lst1,2,1],{Last[lst1]}] +MaximumTrianglePathSum[triangle_List]:=Max[Fold[DoStep,First[triangle],Rest[triangle]]] diff --git a/Task/Maximum-triangle-path-sum/PARI-GP/maximum-triangle-path-sum.pari b/Task/Maximum-triangle-path-sum/PARI-GP/maximum-triangle-path-sum.pari new file mode 100644 index 0000000000..72e5fa7426 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/PARI-GP/maximum-triangle-path-sum.pari @@ -0,0 +1,2 @@ +V=[[55],[94,48],[95,30,96],[77,71,26,67],[97,13,76,38,45],[07,36,79,16,37,68],[48,07,09,18,70,26,06],[18,72,79,46,59,79,29,90],[20,76,87,11,32,07,07,49,18],[27,83,58,35,71,11,25,57,29,85],[14,64,36,96,27,11,58,56,92,18,55],[02,90,03,60,48,49,41,46,33,36,47,23],[92,50,48,02,36,59,42,79,72,20,82,77,42],[56,78,38,80,39,75,02,71,66,66,01,03,55,72],[44,25,67,84,71,67,11,61,40,57,58,89,40,56,36],[85,32,25,85,57,48,84,35,47,62,17,01,01,99,89,52],[06,71,28,75,94,48,37,10,23,51,06,48,53,18,74,98,15],[27,02,92,23,08,71,76,84,15,52,92,63,81,10,44,10,69,93]]; +forstep(i=#V,2,-1,V[i-1]+=vector(i-1,j,max(V[i][j],V[i][j+1]))); V[1][1] diff --git a/Task/Maximum-triangle-path-sum/Pascal/maximum-triangle-path-sum.pascal b/Task/Maximum-triangle-path-sum/Pascal/maximum-triangle-path-sum.pascal new file mode 100644 index 0000000000..34a8cd5a44 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Pascal/maximum-triangle-path-sum.pascal @@ -0,0 +1,106 @@ +program TriSum; +{'triangle.txt' +* one element per line +55 +94 +48 +95 +30 +96 +...} +const + cMaxTriHeight = 18; + cMaxTriElemCnt = (cMaxTriHeight+1)*cMaxTriHeight DIV 2 +1; +type + tElem = longint; + tbaseRow = array[0..cMaxTriHeight] of tElem; + tmyTri = array[0..cMaxTriElemCnt] of tElem; + +function ReadTri( fname:string; + out t:tmyTri):integer; +{read triangle values into t and returns height} +var + f : text; + s : string; + i : integer; + ValCode : word; +begin + i := 0; + fillchar(t,Sizeof(t),#0); + + Assign(f,fname); + {$I-} + reset(f); + IF ioResult <> 0 then + begin + writeln('IO-Error ',ioResult); + close(f); + ReadTri := i; + EXIT; + end; + {$I+} + + while NOT(EOF(f)) AND (i 0 then + begin + writeln(ValCode,' conversion error at line ',i); + fillchar(t,Sizeof(t),#0); + i := 0; + BREAK; + end; + end; + close(f); + ReadTri := round(sqrt(2*(i-1))); +end; + +function TriMaxSum(var t: tmyTri;hei:integer):integer; +{sums up higher values bottom to top} +var + i,r,h,tmpMax : integer; + idxN : integer; + sumrow : tbaseRow; +begin + h := hei; + idxN := (h*(h+1)) div 2 -1; + {copy base row} + move(t[idxN-h+1],sumrow[0],SizeOf(tElem)*h); + dec(h); +{ for r := 0 to h do write(sumrow[r]:4);writeln;} + idxN := idxN-h; + while idxN >0 do + begin + i := idxN-h; + r := 0; + while r < h do + begin + tmpMax:= sumrow[r]; + IF tmpMax 1320} + h := ReadTri('triangle.txt',triangle); + writeln('height sum'); + while h > 0 do + begin + writeln(h:4,TriMaxSum(triangle,h):7); + dec(h); + end; +end. diff --git a/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-1.pl6 b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-1.pl6 new file mode 100644 index 0000000000..d4126abf02 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-1.pl6 @@ -0,0 +1,8 @@ +my @rows = slurp("triangle.txt").lines.map: { [.words] } + +while @rows > 1 { + my @last := @rows.pop; + @rows[*-1] = @rows[*-1][] Z+ (@last Zmax @last[1..*]); +} + +say @rows; diff --git a/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-2.pl6 b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-2.pl6 new file mode 100644 index 0000000000..a0c9a63752 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-2.pl6 @@ -0,0 +1,3 @@ +sub infix:(@a,@b) { (@a Zmax @a[1..*]) Z+ @b } + +say [op] slurp("triangle.txt").lines.reverse.map: { [.words] } diff --git a/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-3.pl6 b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-3.pl6 new file mode 100644 index 0000000000..a51fe21be4 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum-3.pl6 @@ -0,0 +1,3 @@ +sub infix:(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b[1..*]) } + +say [op] slurp("triangle.txt").lines.map: { [.words] } diff --git a/Task/Maximum-triangle-path-sum/Perl/maximum-triangle-path-sum.pl b/Task/Maximum-triangle-path-sum/Perl/maximum-triangle-path-sum.pl new file mode 100644 index 0000000000..66d37e1749 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Perl/maximum-triangle-path-sum.pl @@ -0,0 +1,12 @@ +use 5.10.0; +use List::Util 'max'; + +my @sum; +while (<>) { + my @x = split; + @sum = ($x[0] + $sum[0], + map($x[$_] + max(@sum[$_-1, $_]), 1 .. @x-2), + $x[-1] + $sum[-1]); +} + +say max(@sum); diff --git a/Task/Maximum-triangle-path-sum/Prolog/maximum-triangle-path-sum.pro b/Task/Maximum-triangle-path-sum/Prolog/maximum-triangle-path-sum.pro new file mode 100644 index 0000000000..791c3b567d --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Prolog/maximum-triangle-path-sum.pro @@ -0,0 +1,40 @@ +max_path(N, V) :- + data(N, T), + path(0, T, V). + +path(_N, [], 0) . +path(N, [H | T], V) :- + nth0(N, H, V0), + N1 is N+1, + path(N, T, V1), + path(N1, T, V2), + V is V0 + max(V1, V2). + +data(1, P) :- + P = + [ [55], + [94, 48], + [95, 30, 96], + [77, 71, 26, 67]]. + + +data(2, P) :- + P = + [ [55], + [94, 48], + [95, 30, 96], + [77, 71, 26, 67], + [97, 13, 76, 38, 45], + [7, 36, 79, 16, 37, 68], + [48, 7, 9, 18, 70, 26, 6], + [18, 72, 79, 46, 59, 79, 29, 90], + [20, 76, 87, 11, 32, 7, 7, 49, 18], + [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], + [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], + [2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23], + [92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42], + [56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72], + [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], + [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52], + [6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15], + [27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]]. diff --git a/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-1.py b/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-1.py new file mode 100644 index 0000000000..7870d1ac39 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-1.py @@ -0,0 +1,31 @@ +def solve(tri): + while len(tri) > 1: + t0 = tri.pop() + t1 = tri.pop() + tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)]) + return tri[0][0] + +def main(): + data = """\ + 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93""" + + print solve([map(int, row.split()) for row in data.splitlines()]) + +main() diff --git a/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-2.py b/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-2.py new file mode 100644 index 0000000000..00e8e49f2b --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Python/maximum-triangle-path-sum-2.py @@ -0,0 +1,6 @@ +from itertools import imap + +f = lambda x, y, z: x + max(y, z) +g = lambda xs, ys: list(imap(f, ys, xs, xs[1:])) +data = [map(int, row.split()) for row in open("triangle.txt")][::-1] +print reduce(g, data)[0] diff --git a/Task/Maximum-triangle-path-sum/README b/Task/Maximum-triangle-path-sum/README new file mode 100644 index 0000000000..5c60a931dc --- /dev/null +++ b/Task/Maximum-triangle-path-sum/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Maximum_triangle_path_sum diff --git a/Task/Maximum-triangle-path-sum/REXX/maximum-triangle-path-sum.rexx b/Task/Maximum-triangle-path-sum/REXX/maximum-triangle-path-sum.rexx new file mode 100644 index 0000000000..7ffce4a3f2 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/REXX/maximum-triangle-path-sum.rexx @@ -0,0 +1,34 @@ +/*REXX program finds the max sum of a "column" of numbers in a triangle.*/ +@. = +@.1 = 55 +@.2 = 94 48 +@.3 = 95 30 96 +@.4 = 77 71 26 67 +@.5 = 97 13 76 38 45 +@.6 = 07 36 79 16 37 68 +@.7 = 48 07 09 18 70 26 06 +@.8 = 18 72 79 46 59 79 29 90 +@.9 = 20 76 87 11 32 07 07 49 18 +@.10 = 27 83 58 35 71 11 25 57 29 85 +@.11 = 14 64 36 96 27 11 58 56 92 18 55 +@.12 = 02 90 03 60 48 49 41 46 33 36 47 23 +@.13 = 92 50 48 02 36 59 42 79 72 20 82 77 42 +@.14 = 56 78 38 80 39 75 02 71 66 66 01 03 55 72 +@.15 = 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 +@.16 = 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 +@.17 = 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +@.18 = 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 + + do r=1 while @.r\=='' /*build a version of the triangle*/ + do k=1 for words(@.r) /*build a row, number by number. */ + #.r.k=word(@.r,k) /*assign a number to an array num*/ + end /*k*/ + end /*r*/ +rows=r-1 /*compute the number of rows. */ + do r=rows by -1 to 2; p=r-1 /*traipse through triangle rows. */ + do k=1 for p; kn=k+1 /*re-calculate the previous row. */ + #.p.k=max(#.r.k, #.r.kn) + #.p.k /*replace previous #. */ + end /*k*/ + end /*r*/ +say 'maximum path sum:' #.1.1 /*display the top (row 1) number.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Maximum-triangle-path-sum/Racket/maximum-triangle-path-sum.rkt b/Task/Maximum-triangle-path-sum/Racket/maximum-triangle-path-sum.rkt new file mode 100644 index 0000000000..9b726ab5fc --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Racket/maximum-triangle-path-sum.rkt @@ -0,0 +1,59 @@ +#lang racket +(require math/number-theory) + +(define (trinv n) ; OEIS A002024 + (exact-floor (/ (+ 1 (sqrt (* 1 (* 8 n)))) 2))) + +(define (triangle-neighbour-bl n) + (define row (trinv n)) + (+ n (- (triangle-number row) (triangle-number (- row 1))))) + +(define (maximum-triangle-path-sum T) + (define n-rows (trinv (vector-length T))) + (define memo# (make-hash)) + (define (inner i) + (hash-ref! + memo# i + (λ () + (+ (vector-ref T (sub1 i)) ; index is 1-based (so vector-refs need -1'ing) + (cond [(= (trinv i) n-rows) 0] + [else + (define bl (triangle-neighbour-bl i)) + (max (inner bl) (inner (add1 bl)))]))))) + (inner 1)) + +(module+ main + (maximum-triangle-path-sum + #(55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 + 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93))) + +(module+ test + (require rackunit) + (check-equal? (for/list ((n (in-range 1 (add1 10)))) (trinv n)) '(1 2 2 3 3 3 4 4 4 4)) + ; 1 + ; 2 3 + ; 4 5 6 + ; 7 8 9 10 + (check-eq? (triangle-neighbour-bl 1) 2) + (check-eq? (triangle-neighbour-bl 3) 5) + (check-eq? (triangle-neighbour-bl 5) 8) + (define test-triangle + #(55 94 48 95 30 96 77 71 26 67)) + (check-equal? (maximum-triangle-path-sum test-triangle) 321) + ) diff --git a/Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb b/Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb new file mode 100644 index 0000000000..682fe5fc2a --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb @@ -0,0 +1,26 @@ +triangle = +" 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93" + +ar = triangle.each_line.map{|line| line.strip.split.map(&:to_i)} +until ar.size == 1 do + maxes = ar.pop.each_cons(2).map(&:max) + ar[-1]= ar[-1].zip(maxes).map{|r1,r2| r1 + r2}.flatten +end +puts ar # => 1320 diff --git a/Task/Maximum-triangle-path-sum/Scala/maximum-triangle-path-sum.scala b/Task/Maximum-triangle-path-sum/Scala/maximum-triangle-path-sum.scala new file mode 100644 index 0000000000..f08d4c1699 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Scala/maximum-triangle-path-sum.scala @@ -0,0 +1,21 @@ +object MaximumTrianglePathSum extends App { + // Solution: + def sum(triangle: Array[Array[Int]]) = + triangle.reduceRight((upper, lower) => + upper zip (lower zip lower.tail) + map {case (above, (left, right)) => above + Math.max(left, right)} + ).head + + // Tests: + def triangle = """ + 55 + 94 48 + 95 30 96 + 77 71 26 67 + """ + def parse(s: String) = s.trim.split("\\s+").map(_.toInt) + def parseLines(s: String) = s.trim.split("\n").map(parse) + def parseFile(f: String) = scala.io.Source.fromFile(f).getLines.map(parse).toArray + println(sum(parseLines(triangle))) + println(sum(parseFile("triangle.txt"))) +} diff --git a/Task/Maximum-triangle-path-sum/Tcl/maximum-triangle-path-sum.tcl b/Task/Maximum-triangle-path-sum/Tcl/maximum-triangle-path-sum.tcl new file mode 100644 index 0000000000..a68dcaaf00 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Tcl/maximum-triangle-path-sum.tcl @@ -0,0 +1,45 @@ +package require Tcl 8.6 + +proc maxTrianglePathSum {definition} { + # Parse the definition, stripping whitespace and leading zeroes. + set lines [lmap line [split [string trim $definition] "\n"] { + lmap val $line {scan $val %d} + }] + # Paths are bit strings (0 = go left, 1 = go right). + # Enumerate the possible paths. + set numPaths [expr {2 ** [llength $lines]}] + for {set path 0; set max -inf} {$path < $numPaths} {incr path} { + # Work out how much the current path costs. + set sum [set idx [set row 0]] + for {set bit 1} {$row < [llength $lines]} {incr row} { + incr sum [lindex $lines $row $idx] + if {$path & $bit} {incr idx} + set bit [expr {$bit << 1}] + } + # Remember the max so far. + if {$sum > $max} {set max $sum} + } + return $max +} + +puts [maxTrianglePathSum { + 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 +}] +# Reading from a file is left as an exercise… diff --git a/Task/Move-to-front-algorithm/00DESCRIPTION b/Task/Move-to-front-algorithm/00DESCRIPTION new file mode 100644 index 0000000000..bae2743cfc --- /dev/null +++ b/Task/Move-to-front-algorithm/00DESCRIPTION @@ -0,0 +1,94 @@ +Given a symbol table of a ''zero-indexed'' array of all possible input symbols +[[wp:Move-to-front transform|this algorithm]] reversibly transforms a sequence +of input symbols into an array of output numbers (indices).
+The transform in many cases acts to give frequently repeated input symbols +lower indices which is [[wp:Move-to-front_transform#Use_in_practical_data_compression_algorithms| useful in some compression algorithms]]. + +;Encoding algorithm: +
+    for each symbol of the input sequence:
+        output the index of the symbol in the symbol table
+        move that symbol to the front of the symbol table
+
+ +;Decoding algorithm: +
+    # Using the same starting symbol table
+    for each index of the input sequence:
+        output the symbol at that index of the symbol table
+        move that symbol to the front of the symbol table
+
+ +;Example: +Encoding the string of character symbols 'broood' using a symbol table of +the characters 'a'-to-'z' + +{| class="wikitable" border="1" +|- +! Input +! Output +! SymbolTable +|- +| '''b'''roood +| 1 +| 'abcdefghijklmnopqrstuvwxyz' +|- +| b'''r'''oood +| 1 17 +| 'bacdefghijklmnopqrstuvwxyz' +|- +| br'''o'''ood +| 1 17 15 +| 'rbacdefghijklmnopqstuvwxyz' +|- +| bro'''o'''od +| 1 17 15 0 +| 'orbacdefghijklmnpqstuvwxyz' +|- +| broo'''o'''d +| 1 17 15 0 0 +| 'orbacdefghijklmnpqstuvwxyz' +|- +| brooo'''d''' +| 1 17 15 0 0 5 +| 'orbacdefghijklmnpqstuvwxyz' +|} + +Decoding the indices back to the original symbol order: +{| class="wikitable" border="1" +|- +! Input +! Output +! SymbolTable +|- +| '''1''' 17 15 0 0 5 +| b +| 'abcdefghijklmnopqrstuvwxyz' +|- +| 1 '''17''' 15 0 0 5 +| br +| 'bacdefghijklmnopqrstuvwxyz' +|- +| 1 17 '''15''' 0 0 5 +| bro +| 'rbacdefghijklmnopqstuvwxyz' +|- +| 1 17 15 '''0''' 0 5 +| broo +| 'orbacdefghijklmnpqstuvwxyz' +|- +| 1 17 15 0 '''0''' 5 +| brooo +| 'orbacdefghijklmnpqstuvwxyz' +|- +| 1 17 15 0 0 '''5''' +| broood +| 'orbacdefghijklmnpqstuvwxyz' +|} + +;Task: +* Encode and decode the following three strings of characters using the symbol table of the characters 'a'-to-'z' as above. +* Show the strings and their encoding here. +* Add a check to ensure that the decoded string is the same as the original. + +The strings are: 'broood', 'bananaaa', and 'hiphophiphop'. (Note the spellings). diff --git a/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg b/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg new file mode 100644 index 0000000000..c1e61c69e7 --- /dev/null +++ b/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg @@ -0,0 +1,137 @@ +# move the character at text pos to the front of text # +# note text pos is based from 0 # +PROC move to front = ( STRING text, INT text pos )STRING: + IF text pos < 1 + THEN + # the character is already at the front (or not in the string) # + text + ELSE + # the character isn't already at the front - construct the new string # + + INT char pos = LWB text + text pos; + + ( text[ char pos : char pos ] + + text[ : char pos - 1 ] + + text[ char pos + 1 : ] + ) + + FI; + + +# encode the string "text", using "initial table" as the starting symbol table# +PROC encode = ( STRING text, STRING initial table )[]INT: +BEGIN + + [ 1 : ( UPB text - LWB text ) + 1 ]INT result; + + STRING symbol table := initial table; + + FOR text pos FROM LWB text TO UPB text + DO + INT symbol pos := 0; + + result[ text pos ] + := IF char in string( text[ text pos ], symbol pos, symbol table ) + THEN + # the character is in the symbol table at symbol pos # + # (indexed from LWB text) - we store the positions # + # indexed from 0 # + symbol pos - LWB text + ELSE + # the character isn't in the symbol table # + -1 + FI; + + # modify the symbol table so the latest character is at the front # + symbol table := move to front( symbol table, result[ text pos ] ) + + OD; + + result +END; # encode # + + + +# decode "encoded", using "initial table" as the starting symbol table # +PROC decode = ( []INT encoded, STRING initial table )STRING: +BEGIN + + STRING result := ""; + STRING symbol table := initial table; + + FOR text pos FROM LWB encoded TO UPB encoded + DO + result + +:= IF encoded[ text pos ] < 0 + THEN + # the encoded character wasn't in the string # + "?" + ELSE + # the character is in the symbol table # + symbol table[ encoded[ text pos ] + LWB symbol table ] + FI; + + # modify the symbol table so the latest character is at the front # + symbol table := move to front( symbol table, encoded[ text pos ] ) + + OD; + + result +END; # decode # + + + +# routine to test the encode and decode routines # +PROC test encode and decode = ( STRING text )VOID: +BEGIN + + # initial value for the symbol table # + []CHAR initial table = "abcdefghijklmnopqrstuvwxyz"; + + # procedure to format the encoded value # + PROC format encoded value = ( []INT values )STRING: + BEGIN + STRING result := ""; + FOR value pos FROM LWB values TO UPB values + DO + result +:= ( " " + whole( values[ value pos ], 0 ) ) + OD; + + result + END; # format encoded value # + + []INT encoded = encode( text, initial table ); + STRING decoded = decode( encoded, initial table ); + + print( ( ( text + + " encodes to [" + + format encoded value( encoded ) + + " ] which " + + IF text = decoded + THEN + "correctly" + ELSE + "INCORRECTLY" + FI + + " decodes to """ + + decoded + + """" + ) + , newline + ) + ) + +END; # test encode and decode # + + + +main: ( + + test encode and decode( "broood" ) + ; test encode and decode( "bananaaa" ) + ; test encode and decode( "hiphophiphop" ) + +# ; test encode and decode( "abcdefghijklmnopqrstuvwxyz" ) # +# ; test encode and decode( "zyxwvutsrqponmlkjihgfedcba" ) # + +) diff --git a/Task/Move-to-front-algorithm/Ada/move-to-front-algorithm.ada b/Task/Move-to-front-algorithm/Ada/move-to-front-algorithm.ada new file mode 100644 index 0000000000..a564a0376c --- /dev/null +++ b/Task/Move-to-front-algorithm/Ada/move-to-front-algorithm.ada @@ -0,0 +1,82 @@ +with Ada.Text_IO; + +procedure Move_To_Front is + + subtype Lower_Case is Character range 'a' .. 'z'; + subtype Index is Integer range 0 .. 25; + type Table is array (Index) of Lower_Case; + Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz"; + type Number_String is array(Positive range <>) of Natural; + + function Encode(S: String) return Number_String is + Key: Table := Alphabet; + + function Encode(S: String; Tab: in out Table) return Number_String is + + procedure Look_Up(A: in out Table; Ch: Lower_Case; Pos: out Index) is + begin + for I in A'Range loop + if A(I) = Ch then + Pos := I; + A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); + return; + end if; + end loop; + raise Program_Error with "unknown character"; + end Look_Up; + + Empty: Number_String(1 .. 0); + Result: Natural; + begin + if S'Length = 0 then + return Empty; + else + Look_Up(Tab, S(S'First), Result); + return Result & Encode(S(S'First+1 .. S'Last), Tab); + end if; + end Encode; + + begin + return Encode(S, Key); + end Encode; + + function Decode(N: Number_String) return String is + Key: Table := Alphabet; + + function Decode(N: Number_String; Tab: in out Table) return String is + + procedure Look_Up(A: in out Table; Pos: Index; Ch: out Lower_Case) is + begin + Ch := A(Pos); + A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last); + end Look_Up; + + Result: String(N'Range); + begin + for I in N'Range loop + Look_Up(Tab, N(I), Result(I)); + end loop; + return Result; + end Decode; + + begin + return Decode(N, Key); + end Decode; + + procedure Encode_Write_Check(S: String) is + N: Number_String := Encode(S); + T: String := Decode(N); + Check: String := (if S=T then "Correct!" else "*WRONG*!"); + begin + Ada.Text_IO.Put("'" & S & "' encodes to"); + for Num of N loop + Ada.Text_IO.Put(Integer'Image(Num)); + end loop; + Ada.Text_IO.Put_Line(". This decodes to '" & T & "'. " & Check); + end Encode_Write_Check; + +begin + Encode_Write_Check("broood"); + Encode_Write_Check("bananaaa"); + Encode_Write_Check("hiphophiphop"); +end Move_To_Front; diff --git a/Task/Move-to-front-algorithm/C++/move-to-front-algorithm.cpp b/Task/Move-to-front-algorithm/C++/move-to-front-algorithm.cpp new file mode 100644 index 0000000000..534931d673 --- /dev/null +++ b/Task/Move-to-front-algorithm/C++/move-to-front-algorithm.cpp @@ -0,0 +1,82 @@ +#include +#include +#include +#include + +using namespace std; + +class MTF +{ +public: + string encode( string str ) + { + fillSymbolTable(); + vector output; + for( string::iterator it = str.begin(); it != str.end(); it++ ) + { + for( int i = 0; i < 26; i++ ) + { + if( *it == symbolTable[i] ) + { + output.push_back( i ); + moveToFront( i ); + break; + } + } + } + string r; + for( vector::iterator it = output.begin(); it != output.end(); it++ ) + { + ostringstream ss; + ss << *it; + r += ss.str() + " "; + } + return r; + } + + string decode( string str ) + { + fillSymbolTable(); + istringstream iss( str ); vector output; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( output ) ); + string r; + for( vector::iterator it = output.begin(); it != output.end(); it++ ) + { + r.append( 1, symbolTable[*it] ); + moveToFront( *it ); + } + return r; + } + +private: + void moveToFront( int i ) + { + char t = symbolTable[i]; + for( int z = i - 1; z >= 0; z-- ) + symbolTable[z + 1] = symbolTable[z]; + + symbolTable[0] = t; + } + + void fillSymbolTable() + { + for( int x = 0; x < 26; x++ ) + symbolTable[x] = x + 'a'; + } + + char symbolTable[26]; +}; + +int main() +{ + MTF mtf; + string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; + for( int x = 0; x < 3; x++ ) + { + a = str[x]; + cout << a << " -> encoded = "; + a = mtf.encode( a ); + cout << a << "; decoded = " << mtf.decode( a ) << endl; + } + return 0; +} diff --git a/Task/Move-to-front-algorithm/C/move-to-front-algorithm.c b/Task/Move-to-front-algorithm/C/move-to-front-algorithm.c new file mode 100644 index 0000000000..ed74044593 --- /dev/null +++ b/Task/Move-to-front-algorithm/C/move-to-front-algorithm.c @@ -0,0 +1,88 @@ +#include +#include +#include + +#define MAX_SIZE 100 + +int move_to_front(char *str,char c) +{ + char *q,*p; + int shift=0; + p=(char *)malloc(strlen(str)+1); + strcpy(p,str); + q=strchr(p,c); //returns pointer to location of char c in string str + shift=q-p; // no of characters from 0 to position of c in str + strncpy(str+1,p,shift); + str[0]=c; + free(p); + // printf("\n%s\n",str); + return shift; +} + +void decode(int* pass,int size,char *sym) +{ + int i,index; + char c; + char table[]="abcdefghijklmnopqrstuvwxyz"; + for(i=0;i e >= 0 && e < lowercase.length)); +} body { + ubyte[lowercase.length] order = lowercase.representation; + auto encoded = new typeof(return)(data.length); + + size_t i = 0; + foreach (immutable b; data) { + immutable j = encoded[i++] = order[].countUntil(b); + bringToFront(order[0 .. j], order[j .. j + 1]); + } + + return encoded; +} + +string mtfDecoder(in ptrdiff_t[] encoded) pure nothrow @safe +in { + assert(encoded.all!(e => e >= 0 && e < lowercase.length)); +} out(result) { + assert(result.length == encoded.length); + assert(result.countchars("a-z") == result.length); +} body { + ubyte[lowercase.length] order = lowercase.representation; + auto decoded = new char[encoded.length]; + + size_t i = 0; + foreach (immutable code; encoded) { + decoded[i++] = order[code]; + bringToFront(order[0 .. code], order[code .. code + 1]); + } + + return decoded; +} + +void main() { + foreach (immutable word; ["broood", "bananaaa", "hiphophiphop"]) { + immutable encoded = word.mtfEncoder; + immutable decoded = encoded.mtfDecoder; + writefln("'%s' encodes to %s, which decodes back to '%s'", + word, encoded, decoded); + assert(word == decoded); + } +} diff --git a/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go b/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go new file mode 100644 index 0000000000..5f45f5ca11 --- /dev/null +++ b/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go @@ -0,0 +1,46 @@ +package main + +import ( + "bytes" + "fmt" +) + +type moveToFront string + +func (symbols moveToFront) encode(s string) []int { + seq := make([]int, len(s)) + pad := []byte(symbols) + c1 := []byte{0} + for i := 0; i < len(s); i++ { + c := s[i] + c1[0] = c + x := bytes.Index(pad, c1) + seq[i] = x + copy(pad[1:], pad[:x]) + pad[0] = c + } + return seq +} +func (symbols moveToFront) decode(seq []int) string { + chars := make([]byte, len(seq)) + pad := []byte(symbols) + for i, x := range seq { + c := pad[x] + chars[i] = c + copy(pad[1:], pad[:x]) + pad[0] = c + } + return string(chars) +} + +func main() { + m := moveToFront("abcdefghijklmnopqrstuvwxyz") + for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { + enc := m.encode(s) + dec := m.decode(enc) + fmt.Println(s, enc, dec) + if dec != s { + panic("Whoops!") + } + } +} diff --git a/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs b/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs new file mode 100644 index 0000000000..01726c7889 --- /dev/null +++ b/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs @@ -0,0 +1,19 @@ +import qualified Data.List as L +import qualified Data.Maybe as M + +table :: String +table = ['a'..'z'] + +encode :: String -> [Int] +encode = snd . L.mapAccumL f table + where + f t s = ((s : L.delete s t), M.fromJust (L.elemIndex s t)) + +decode :: [Int] -> String +decode = snd . L.mapAccumL f table + where + f t i = let s = (t !! i) in ((s : L.delete s t), s) + +main :: IO () +main = mapM_ (\s -> let t@(e, _) = (encode s, decode e) in print t) + ["broood", "bananaaa", "hiphophiphop"] diff --git a/Task/Move-to-front-algorithm/Icon/move-to-front-algorithm.icon b/Task/Move-to-front-algorithm/Icon/move-to-front-algorithm.icon new file mode 100644 index 0000000000..8883c517d4 --- /dev/null +++ b/Task/Move-to-front-algorithm/Icon/move-to-front-algorithm.icon @@ -0,0 +1,29 @@ +procedure main(A) + every writes(s := !A, " -> [") do { + every writes(!(enc := encode(&lcase,s))," ") + writes("] -> ",s2 := decode(&lcase,enc)) + write((s == s2, " (Correct)") | " (Incorrect)") + } +end + +procedure encode(m,s) + enc := [] + every c := !s do { + m ?:= reorder(tab(i := upto(c)),move(1),tab(0)) + put(enc,i-1) # Strings are 1-based + } + return enc +end + +procedure decode(m,enc) + dec := "" + every i := 1 + !enc do { # Lists are 1-based + dec ||:= m[i] + m ?:= reorder(tab(i),move(1),tab(0)) + } + return dec +end + +procedure reorder(s1,s2,s3) + return s2||s1||s3 +end diff --git a/Task/Move-to-front-algorithm/J/move-to-front-algorithm-1.j b/Task/Move-to-front-algorithm/J/move-to-front-algorithm-1.j new file mode 100644 index 0000000000..c4caba3f9d --- /dev/null +++ b/Task/Move-to-front-algorithm/J/move-to-front-algorithm-1.j @@ -0,0 +1,21 @@ +spindizzy=:3 :0 + 'seq table'=. y + ndx=.$0 + orig=. table + for_sym. seq do. + ndx=.ndx,table i.sym + table=. sym,table-.sym + end. + ndx + assert. seq-:yzzidnips ndx;orig +) + +yzzidnips=:3 :0 + 'ndx table'=. y + seq=.'' + for_n. ndx do. + seq=.seq,sym=. n{table + table=. sym,table-.sym + end. + seq +) diff --git a/Task/Move-to-front-algorithm/J/move-to-front-algorithm-2.j b/Task/Move-to-front-algorithm/J/move-to-front-algorithm-2.j new file mode 100644 index 0000000000..64abefb0ec --- /dev/null +++ b/Task/Move-to-front-algorithm/J/move-to-front-algorithm-2.j @@ -0,0 +1,6 @@ + spindizzy 'broood';'abcdefghijklmnopqrstuvwxyz' +1 17 15 0 0 5 + spindizzy 'bananaaa';'abcdefghijklmnopqrstuvwxyz' +1 1 13 1 1 1 0 0 + spindizzy 'hiphophiphop';'abcdefghijklmnopqrstuvwxyz' +7 8 15 2 15 2 2 3 2 2 3 2 diff --git a/Task/Move-to-front-algorithm/Java/move-to-front-algorithm.java b/Task/Move-to-front-algorithm/Java/move-to-front-algorithm.java new file mode 100644 index 0000000000..e16c868278 --- /dev/null +++ b/Task/Move-to-front-algorithm/Java/move-to-front-algorithm.java @@ -0,0 +1,40 @@ +import java.util.LinkedList; +import java.util.List; + +public class MTF{ + public static List encode(String msg, String symTable){ + List output = new LinkedList(); + StringBuilder s = new StringBuilder(symTable); + for(char c : msg.toCharArray()){ + int idx = s.indexOf("" + c); + output.add(idx); + s = s.deleteCharAt(idx).insert(0, c); + } + return output; + } + + public static String decode(List idxs, String symTable){ + StringBuilder output = new StringBuilder(); + StringBuilder s = new StringBuilder(symTable); + for(int idx : idxs){ + char c = s.charAt(idx); + output = output.append(c); + s = s.deleteCharAt(idx).insert(0, c); + } + return output.toString(); + } + + private static void test(String toEncode, String symTable){ + List encoded = encode(toEncode, symTable); + System.out.println(toEncode + ": " + encoded); + String decoded = decode(encoded, symTable); + System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); + } + + public static void main(String[] args){ + String symTable = "abcdefghijklmnopqrstuvwxyz"; + test("broood", symTable); + test("bananaaa", symTable); + test("hiphophiphop", symTable); + } +} diff --git a/Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js b/Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js new file mode 100644 index 0000000000..09b8e32b01 --- /dev/null +++ b/Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js @@ -0,0 +1,20 @@ +var encodeMTF = function (word) { + var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')}; + + return word.split('').reduce(function (acc, char) { + var charNum = acc.charList.indexOf(char); //get index of char + acc.wordAsNumbers.push(charNum); //add original index to acc + acc.charList.unshift(acc.charList.splice(charNum, 1)[0]); //put at beginning of list + return acc; + }, init).wordAsNumbers; //return number list +}; + +var decodeMTF = function (numList) { + var init = {word: '', charList: 'abcdefghijklmnopqrstuvwxyz'.split('')}; + + return numList.reduce(function (acc, num) { + acc.word += acc.charList[num]; + acc.charList.unshift(acc.charList.splice(num, 1)[0]); //put at beginning of list + return acc; + }, init).word; +}; diff --git a/Task/Move-to-front-algorithm/MATLAB/move-to-front-algorithm.m b/Task/Move-to-front-algorithm/MATLAB/move-to-front-algorithm.m new file mode 100644 index 0000000000..afd82837f3 --- /dev/null +++ b/Task/Move-to-front-algorithm/MATLAB/move-to-front-algorithm.m @@ -0,0 +1,30 @@ +function testMTF + symTable = 'abcdefghijklmnopqrstuvwxyz'; + inStr = {'broood' 'bananaaa' 'hiphophiphop'}; + for k = 1:length(inStr) + outArr = encodeMTF(inStr{k}, symTable); + outStr = decodeMTF(outArr, symTable); + fprintf('%s: [ %s]\n', inStr{k}, sprintf('%d ', outArr)) + fprintf('%scorrectly decoded to %s\n', char('in'.*~strcmp(outStr, inStr{k})), outStr) + end +end + +function arr = encodeMTF(str, symTable) + n = length(str); + arr = zeros(1, n); + for k = 1:n + arr(k) = find(str(k) == symTable, 1); + symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)]; + end + arr = arr-1; % Change to zero-indexed array +end + +function str = decodeMTF(arr, symTable) + arr = arr+1; % Change to one-indexed array + n = length(arr); + str = char(zeros(1, n)); + for k = 1:n + str(k) = symTable(arr(k)); + symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)]; + end +end diff --git a/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-1.math b/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-1.math new file mode 100644 index 0000000000..e280812aef --- /dev/null +++ b/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-1.math @@ -0,0 +1,8 @@ +mtf[word_]:=Module[{f,f2,p,q}, + f[{output_,symList_},next_]:=Module[{index},index=Position[symList,next][[1,1]]-1; + {output~Append~index,Prepend[Delete[symList,index+1],next]}]; + p=Fold[f,{{},CharacterRange["a","z"]},Characters[ToString[word]]][[1]]; + f2[{output_,symList_},next_]:=Module[{index},index=symList[[next+1]]; + {output~Append~index,Prepend[DeleteCases[symList,ToString[index]],index]}]; + q=Fold[f2,{{},CharacterRange["a","z"]},p][[1]]; + Print["'", word,"' encodes to: ",p, " - " ,p," decodes to: '",StringJoin@q,"' - Input equals Output: " ,word===StringJoin@q];] diff --git a/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-2.math b/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-2.math new file mode 100644 index 0000000000..c2c0475797 --- /dev/null +++ b/Task/Move-to-front-algorithm/Mathematica/move-to-front-algorithm-2.math @@ -0,0 +1 @@ +mtf /@ {"broood", "bananaaa", "hiphophiphop"} diff --git a/Task/Move-to-front-algorithm/PL-I/move-to-front-algorithm.pli b/Task/Move-to-front-algorithm/PL-I/move-to-front-algorithm.pli new file mode 100644 index 0000000000..6dfe9eccda --- /dev/null +++ b/Task/Move-to-front-algorithm/PL-I/move-to-front-algorithm.pli @@ -0,0 +1,40 @@ +*process source attributes xref or(!); + /********************************************************************* + * 25.5.2014 Walter Pachl translated from REXX + *********************************************************************/ + ed: Proc Options(main); + Call enc_dec('broood'); + Call enc_dec('bananaaa'); + Call enc_dec('hiphophiphop'); + + enc_dec: Proc(in); + Dcl in Char(*); + Dcl out Char(20) Var Init(''); + Dcl st Char(26) Init('abcdefghijklmnopqrstuvwxyz'); + Dcl sta Char(26) Init((st)); + Dcl enc(20) Bin Fixed(31); + Dcl encn Bin Fixed(31) Init(0); + Dcl (i,p.k) Bin Fixed(31); + Dcl c Char(1); + Do i=1 To length(in); + c=substr(in,i,1); + p=index(st,c); + encn+=1; + enc(encn)=p-1; + st=c!!left(st,p-1)!!substr(st,p+1); + End; + Put Skip List(' in='!!in); + Put Skip List('sta='!!sta!!' original symbol table'); + Put Skip Edit('enc=',(enc(i) do i=1 To encn))(a,20(F(3))); + Put Skip List(' st='!!st!!' symbol table after encoding'); + Do i=1 To encn; + k=enc(i)+1; + out=out!!substr(sta,k,1); + sta=substr(sta,k,1)!!left(sta,k-1)!!substr(sta,k+1); + End; + Put Skip List('out='!!out); + Put Skip List(' '); + If out=in Then; + Else + Put Skip List('all wrong!!'); + End; diff --git a/Task/Move-to-front-algorithm/Perl-6/move-to-front-algorithm.pl6 b/Task/Move-to-front-algorithm/Perl-6/move-to-front-algorithm.pl6 new file mode 100644 index 0000000000..30ea5b4a1f --- /dev/null +++ b/Task/Move-to-front-algorithm/Perl-6/move-to-front-algorithm.pl6 @@ -0,0 +1,23 @@ +sub encode ( Str $word ) { + my @sym = 'a' .. 'z'; + gather for $word.comb -> $c { + die "Symbol '$c' not found in @sym" if $c eq @sym.none; + @sym[0 .. take (Nil, @sym ... $c).end] .= rotate(-1); + } +} + +sub decode ( @enc ) { + my @sym = 'a' .. 'z'; + [~] gather for @enc -> $pos { + take @sym[$pos]; + @sym[0..$pos] .= rotate(-1); + } +} + +use Test; +plan 3; +for -> $word { + my $enc = encode($word); + my $dec = decode($enc); + is $word, $dec, "$word.fmt('%-12s') ($enc[])"; +} diff --git a/Task/Move-to-front-algorithm/Perl/move-to-front-algorithm.pl b/Task/Move-to-front-algorithm/Perl/move-to-front-algorithm.pl new file mode 100644 index 0000000000..dfc2cb1504 --- /dev/null +++ b/Task/Move-to-front-algorithm/Perl/move-to-front-algorithm.pl @@ -0,0 +1,26 @@ +use strict; +use warnings; +sub encode { + my ($str) = @_; + my $table = join '', 'a' .. 'z'; + map { + $table =~ s/(.*?)$_/$_$1/ or die; + length($1); + } split //, $str; +} + +sub decode { + my $table = join '', 'a' .. 'z'; + join "", map { + $table =~ s/(.{$_})(.)/$2$1/ or die; + $2; + } @_; +} + +for my $test ( qw(broood bananaaa hiphophiphop) ) { + my @encoded = encode($test); + print "$test: @encoded\n"; + my $decoded = decode(@encoded); + print "in" x ( $decoded ne $test ); + print "correctly decoded to $decoded\n"; +} diff --git a/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-1.py b/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-1.py new file mode 100644 index 0000000000..0a4413e7f1 --- /dev/null +++ b/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-1.py @@ -0,0 +1,28 @@ +from __future__ import print_function +from string import ascii_lowercase + +SYMBOLTABLE = list(ascii_lowercase) + +def move2front_encode(strng, symboltable): + sequence, pad = [], symboltable[::] + for char in strng: + indx = pad.index(char) + sequence.append(indx) + pad = [pad.pop(indx)] + pad + return sequence + +def move2front_decode(sequence, symboltable): + chars, pad = [], symboltable[::] + for indx in sequence: + char = pad[indx] + chars.append(char) + pad = [pad.pop(indx)] + pad + return ''.join(chars) + +if __name__ == '__main__': + for s in ['broood', 'bananaaa', 'hiphophiphop']: + encode = move2front_encode(s, SYMBOLTABLE) + print('%14r encodes to %r' % (s, encode), end=', ') + decode = move2front_decode(encode, SYMBOLTABLE) + print('which decodes back to %r' % decode) + assert s == decode, 'Whoops!' diff --git a/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-2.py b/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-2.py new file mode 100644 index 0000000000..b6dba77c62 --- /dev/null +++ b/Task/Move-to-front-algorithm/Python/move-to-front-algorithm-2.py @@ -0,0 +1,13 @@ +def m2f_e(s, st): + return [[st.index(ch), st.insert(0, st.pop(st.index(ch)))][0] for ch in s] + +def m2f_d(sq, st): + return ''.join([st[i], st.insert(0, st.pop(i))][0] for i in sq) + +ST = list('abcdefghijklmnopqrstuvwxyz') +for s in ['broood', 'bananaaa', 'hiphophiphop']: + encode = m2f_e(s, ST[::]) + print('%14r encodes to %r' % (s, encode), end=', ') + decode = m2f_d(encode, ST[::]) + print('decodes back to %r' % decode) + assert s == decode, 'Whoops!' diff --git a/Task/Move-to-front-algorithm/README b/Task/Move-to-front-algorithm/README new file mode 100644 index 0000000000..08ed381ea1 --- /dev/null +++ b/Task/Move-to-front-algorithm/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Move-to-front_algorithm diff --git a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-1.rexx b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-1.rexx new file mode 100644 index 0000000000..67dd2c11ea --- /dev/null +++ b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-1.rexx @@ -0,0 +1,35 @@ +/* REXX *************************************************************** +* 25.05.2014 Walter Pachl +* REXX strings start with position 1 +**********************************************************************/ +Call enc_dec 'broood' +Call enc_dec 'bananaaa' +Call enc_dec 'hiphophiphop' +Exit +enc_dec: Procedure +Parse Arg in +st='abcdefghijklmnopqrstuvwxyz' +sta=st /* remember this for decoding */ +enc='' +Do i=1 To length(in) + c=substr(in,i,1) + p=pos(c,st) + enc=enc (p-1) + st=c||left(st,p-1)substr(st,p+1) + End +Say ' in='in +Say 'sta='sta 'original symbol table' +Say 'enc='enc +Say ' st='st 'symbol table after encoding' +out='' +Do i=1 To words(enc) + k=word(enc,i)+1 + out=out||substr(sta,k,1) + sta=substr(sta,k,1)left(sta,k-1)substr(sta,k+1) + End +Say 'out='out +Say ' ' +If out==in Then Nop +Else + Say 'all wrong!!' +Return diff --git a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx new file mode 100644 index 0000000000..8c1ef8c50d --- /dev/null +++ b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx @@ -0,0 +1,21 @@ +/*REXX pgm demonstrates move─to─front algorithm encode/decode sym table.*/ +parse arg xxx; if xxx='' then xxx='broood bananaaa hiphophiphop' + one=1 /*for task's requirement. */ + do j=1 for words(xxx); x=word(xxx,j) /*process one word at a time*/ + @='abcdefghijklmnopqrstuvwxyz' /*sym table: lower alphabet.*/ + $= /*set decode string to null.*/ + do k=1 for length(x); z=substr(x,k,1) /*encrypt a char in word. */ + _=pos(z,@); if _==0 then iterate /*char position in sym table*/ + $=$ _-one; @=z || delstr(@,_,1) /*adjust the symbol table. */ + end /*k*/ /* [↑] move─to─front encode*/ + + @='abcdefghijklmnopqrstuvwxyz' /*sym table: lower alphabet.*/ + != /*set encode string to null.*/ + do m=1 for words($); n=word($,m)+one /*decode the sequence table.*/ + y=substr(@,n,1); !=! || y /*decode character of word. */ + @=y || delstr(@,n,1) /*rebuild the symbol table. */ + end /*m*/ /* [↑] move─to─front decode*/ + + say 'word: ' left(x,20) "encoding:" left($,35) word('wrong OK',1+(!==x)) + end /*j*/ /*done encoding/decoding words. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Move-to-front-algorithm/Racket/move-to-front-algorithm.rkt b/Task/Move-to-front-algorithm/Racket/move-to-front-algorithm.rkt new file mode 100644 index 0000000000..2da1e87207 --- /dev/null +++ b/Task/Move-to-front-algorithm/Racket/move-to-front-algorithm.rkt @@ -0,0 +1,45 @@ +#lang racket +(define default-symtab "abcdefghijklmnopqrstuvwxyz") + +(define (move-to-front:encode in (symtab default-symtab)) + (define inner-encode + (match-lambda** + [((? string? (app string->list in)) st acc) ; make input all listy + (inner-encode in st acc)] + [(in (? string? (app string->list st)) acc) ; make symtab all listy + (inner-encode in st acc)] + [((list) _ (app reverse rv)) ; nothing more to encode + rv] + [((list a tail ...) (list left ... a right ...) acc) ; encode and recur + (inner-encode tail `(,a ,@left ,@right) (cons (length left) acc))])) + (inner-encode in symtab null)) + +(define (move-to-front:decode in (symtab default-symtab)) + (define inner-decode + (match-lambda** + [(in (? string? (app string->list st)) acc) ; make symtab all listy + (inner-decode in st acc)] + [((list) _ (app (compose list->string reverse) rv)) ; nothing more to encode + rv] + [((list a tail ...) symbols acc) ; decode and recur + (match/values + (split-at symbols a) + [(l (cons ra rd)) + (inner-decode tail (cons ra (append l rd)) (cons ra acc))])])) + (inner-decode in symtab null)) + +(module+ test + ;; Test against the example in the task + (require rackunit) + (check-equal? (move-to-front:encode "broood") '(1 17 15 0 0 5)) + (check-equal? (move-to-front:decode '(1 17 15 0 0 5)) "broood") + (check-equal? (move-to-front:decode (move-to-front:encode "broood")) "broood")) + +(module+ main + (define (encode+decode-string str) + (define enc (move-to-front:encode str)) + (define dec (move-to-front:decode enc)) + (define crt (if (equal? dec str) "correctly" "incorrectly")) + (printf "~s encodes to ~s, which decodes ~s to ~s.~%" str enc crt dec)) + + (for-each encode+decode-string '("broood" "bananaaa" "hiphophiphop"))) diff --git a/Task/Move-to-front-algorithm/Ruby/move-to-front-algorithm.rb b/Task/Move-to-front-algorithm/Ruby/move-to-front-algorithm.rb new file mode 100644 index 0000000000..8433cfdbef --- /dev/null +++ b/Task/Move-to-front-algorithm/Ruby/move-to-front-algorithm.rb @@ -0,0 +1,30 @@ +module MoveToFront + + ABC = ("a".."z").to_a.freeze + + def self.encode(str) + ar = ABC.dup + str.chars.each_with_object([]) do |char, memo| + memo << (i = ar.index(char)) + ar = m2f(ar,i) + end + end + + def self.decode(indices) + ar = ABC.dup + indices.each_with_object("") do |i, str| + str << ar[i] + ar = m2f(ar,i) + end + end + + private + def self.m2f(ar,i) + [ar.delete_at(i)] + ar + end + +end + +['broood', 'bananaaa', 'hiphophiphop'].each do |word| + p word == MoveToFront.decode(p MoveToFront.encode(p word)) +end diff --git a/Task/Move-to-front-algorithm/Tcl/move-to-front-algorithm.tcl b/Task/Move-to-front-algorithm/Tcl/move-to-front-algorithm.tcl new file mode 100644 index 0000000000..37ddebd245 --- /dev/null +++ b/Task/Move-to-front-algorithm/Tcl/move-to-front-algorithm.tcl @@ -0,0 +1,39 @@ +package require Tcl 8.6 + +oo::class create MoveToFront { + variable symbolTable + constructor {symbols} { + set symbolTable [split $symbols ""] + } + + method MoveToFront {table index} { + list [lindex $table $index] {*}[lreplace $table $index $index] + } + method encode {text} { + set t $symbolTable + set r {} + foreach c [split $text ""] { + set i [lsearch -exact $t $c] + lappend r $i + set t [my MoveToFront $t $i] + } + return $r + } + method decode {numbers} { + set t $symbolTable + set r "" + foreach n $numbers { + append r [lindex $t $n] + set t [my MoveToFront $t $n] + } + return $r + } +} + +MoveToFront create mtf "abcdefghijklmnopqrstuvwxyz" +foreach tester {"broood" "bananaaa" "hiphophiphop"} { + set enc [mtf encode $tester] + set dec [mtf decode $enc] + puts [format "'%s' encodes to %s. This decodes to '%s'. %s" \ + $tester $enc $dec [expr {$tester eq $dec ? "Correct!" : "WRONG!"}]] +} diff --git a/Task/Munching-squares/00DESCRIPTION b/Task/Munching-squares/00DESCRIPTION new file mode 100644 index 0000000000..5f4d59c729 --- /dev/null +++ b/Task/Munching-squares/00DESCRIPTION @@ -0,0 +1,3 @@ +{{omit from|GUISS}} +{{omit from|Lilypond}} +Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary [[wp:color table|color table]]. diff --git a/Task/Munching-squares/00META.yaml b/Task/Munching-squares/00META.yaml new file mode 100644 index 0000000000..c4801aa5b2 --- /dev/null +++ b/Task/Munching-squares/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Graphics algorithms +note: Raster graphics operations diff --git a/Task/Munching-squares/Ada/munching-squares.ada b/Task/Munching-squares/Ada/munching-squares.ada new file mode 100644 index 0000000000..f1bd99720e --- /dev/null +++ b/Task/Munching-squares/Ada/munching-squares.ada @@ -0,0 +1,21 @@ +with Cairo; use Cairo; +with Cairo.Png; use Cairo.Png; +with Cairo.Image_Surface; use Cairo.Image_Surface; +procedure XorPattern is + type xorable is mod 256; + Surface : Cairo_Surface; + Data : RGB24_Array_Access; + Status : Cairo_Status; + Num : Byte; +begin + Data := new RGB24_Array(0..256*256-1); + for x in Natural range 0..255 loop + for y in Natural range 0..255 loop + Num := Byte(xorable(x) xor xorable(y)); + Data(x+256*y) := RGB24_Data'(Num,0,Num); + end loop; + end loop; + Surface := Create_For_Data_RGB24(Data, 256, 256); + Status := Write_To_Png (Surface, "AdaXorPattern.png"); + pragma Assert (Status = Cairo_Status_Success); +end XorPattern; diff --git a/Task/Munching-squares/Burlesque/munching-squares.blq b/Task/Munching-squares/Burlesque/munching-squares.blq new file mode 100644 index 0000000000..d6bd1b35da --- /dev/null +++ b/Task/Munching-squares/Burlesque/munching-squares.blq @@ -0,0 +1,27 @@ +blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp + 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 + 1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24 + 2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13 18 19 16 17 22 23 20 21 26 27 + 3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 19 18 17 16 23 22 21 20 27 26 + 4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11 20 21 22 23 16 17 18 19 28 29 + 5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10 21 20 23 22 17 16 19 18 29 28 + 6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9 22 23 20 21 18 19 16 17 30 31 + 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 23 22 21 20 19 18 17 16 31 30 + 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 24 25 26 27 28 29 30 31 16 17 + 9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6 25 24 27 26 29 28 31 30 17 16 +10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5 26 27 24 25 30 31 28 29 18 19 +11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4 27 26 25 24 31 30 29 28 19 18 +12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3 28 29 30 31 24 25 26 27 20 21 +13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2 29 28 31 30 25 24 27 26 21 20 +14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1 30 31 28 29 26 27 24 25 22 23 +15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 23 22 +16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9 +17 16 19 18 21 20 23 22 25 24 27 26 29 28 31 30 1 0 3 2 5 4 7 6 9 8 +18 19 16 17 22 23 20 21 26 27 24 25 30 31 28 29 2 3 0 1 6 7 4 5 10 11 +19 18 17 16 23 22 21 20 27 26 25 24 31 30 29 28 3 2 1 0 7 6 5 4 11 10 +20 21 22 23 16 17 18 19 28 29 30 31 24 25 26 27 4 5 6 7 0 1 2 3 12 13 +21 20 23 22 17 16 19 18 29 28 31 30 25 24 27 26 5 4 7 6 1 0 3 2 13 12 +22 23 20 21 18 19 16 17 30 31 28 29 26 27 24 25 6 7 4 5 2 3 0 1 14 15 +23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24 7 6 5 4 3 2 1 0 15 14 +24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1 +25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0 diff --git a/Task/Munching-squares/C++/munching-squares.cpp b/Task/Munching-squares/C++/munching-squares.cpp new file mode 100644 index 0000000000..08531cbcdc --- /dev/null +++ b/Task/Munching-squares/C++/munching-squares.cpp @@ -0,0 +1,161 @@ +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int BMP_SIZE = 512; + +//-------------------------------------------------------------------------------------------------- +class myBitmap +{ +public: + myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} + ~myBitmap() + { + DeleteObject( pen ); + DeleteObject( brush ); + DeleteDC( hdc ); + DeleteObject( bmp ); + } + + bool create( int w, int h ) + { + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; + + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; + + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + + width = w; height = h; + return true; + } + + void clear( BYTE clr = 0 ) + { + memset( pBits, clr, width * height * sizeof( DWORD ) ); + } + + void setBrushColor( DWORD bClr ) + { + if( brush ) DeleteObject( brush ); + brush = CreateSolidBrush( bClr ); + SelectObject( hdc, brush ); + } + + void setPenColor( DWORD c ) { clr = c; createPen(); } + + void setPenWidth( int w ) { wid = w; createPen(); } + + void saveBitmap( string path ) + { + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD wb; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + + HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); + + delete [] dwpBits; + } + + HDC getDC() const { return hdc; } + int getWidth() const { return width; } + int getHeight() const { return height; } + +private: + void createPen() + { + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, wid, clr ); + SelectObject( hdc, pen ); + } + + HBITMAP bmp; + HDC hdc; + HPEN pen; + HBRUSH brush; + void *pBits; + int width, height, wid; + DWORD clr; +}; +//-------------------------------------------------------------------------------------------------- +class mSquares +{ +public: + mSquares() + { + bmp.create( BMP_SIZE, BMP_SIZE ); + createPallete(); + } + + void draw() + { + HDC dc = bmp.getDC(); + for( int y = 0; y < BMP_SIZE; y++ ) + for( int x = 0; x < BMP_SIZE; x++ ) + { + int c = ( x ^ y ) % 256; + SetPixel( dc, x, y, clrs[c] ); + } + + BitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); + //bmp.saveBitmap( "f:\\rc\\msquares_cpp.bmp" ); + } + +private: + void createPallete() + { + for( int x = 0; x < 256; x++ ) + clrs[x] = RGB( x<<1, x, x<<2 );//rand() % 180 + 50, rand() % 200 + 50, rand() % 180 + 50 ); + } + + unsigned int clrs[256]; + myBitmap bmp; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); + srand( GetTickCount() ); + mSquares s; s.draw(); + return system( "pause" ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Munching-squares/C-sharp/munching-squares.cs b/Task/Munching-squares/C-sharp/munching-squares.cs new file mode 100644 index 0000000000..94f16893b2 --- /dev/null +++ b/Task/Munching-squares/C-sharp/munching-squares.cs @@ -0,0 +1,24 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Linq; + +class XORPattern +{ + static void Main() + { + var size = 0x100; + var black = Color.Black.ToArgb(); + var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray(); + using (var image = new Bitmap(size, size)) + { + for (var x = 0; x < size; x++) + { + for (var y = 0; y < size; y++) + { + image.SetPixel(x, y, palette[x ^ y]); + } + } + image.Save("XORPatternCSharp.png", ImageFormat.Png); + } + } +} diff --git a/Task/Munching-squares/C/munching-squares.c b/Task/Munching-squares/C/munching-squares.c new file mode 100644 index 0000000000..9f9d921652 --- /dev/null +++ b/Task/Munching-squares/C/munching-squares.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include + +void hue_to_rgb(double hue, double sat, unsigned char *p) +{ + double x; + int c = 255 * sat; + hue /= 60; + x = (1 - fabs(fmod(hue, 2) - 1)) * 255; + + switch((int)hue) { + case 0: p[0] = c; p[1] = x; p[2] = 0; return; + case 1: p[0] = x; p[1] = c; p[2] = 0; return; + case 2: p[0] = 0; p[1] = c; p[2] = x; return; + case 3: p[0] = 0; p[1] = x; p[2] = c; return; + case 4: p[0] = x; p[1] = 0; p[2] = c; return; + case 5: p[0] = c; p[1] = 0; p[2] = x; return; + } +} + +int main(void) +{ + const int size = 512; + int i, j; + unsigned char *colors = malloc(size * 3); + unsigned char *pix = malloc(size * size * 3), *p; + FILE *fp; + + for (i = 0; i < size; i++) + hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i); + + for (i = 0, p = pix; i < size; i++) + for (j = 0; j < size; j++, p += 3) + memcpy(p, colors + (i ^ j) * 3, 3); + + fp = fopen("xor.ppm", "wb"); + fprintf(fp, "P6\n%d %d\n255\n", size, size); + fwrite(pix, size * size * 3, 1, fp); + fclose(fp); + + return 0; +} diff --git a/Task/Munching-squares/D/munching-squares.d b/Task/Munching-squares/D/munching-squares.d new file mode 100644 index 0000000000..f3b39492ec --- /dev/null +++ b/Task/Munching-squares/D/munching-squares.d @@ -0,0 +1,14 @@ +void main() { + import std.stdio; + + enum width = 512, height = 512; + + auto f = File("xor_pattern.ppm", "wb"); + f.writefln("P6\n%d %d\n255", width, height); + foreach (immutable y; 0 .. height) + foreach (immutable x; 0 .. width) { + immutable c = (x ^ y) & ubyte.max; + immutable ubyte[3] u3 = [255 - c, c / 2, c]; + f.rawWrite(u3); + } +} diff --git a/Task/Munching-squares/Gnuplot/munching-squares.gnuplot b/Task/Munching-squares/Gnuplot/munching-squares.gnuplot new file mode 100644 index 0000000000..7032b352b6 --- /dev/null +++ b/Task/Munching-squares/Gnuplot/munching-squares.gnuplot @@ -0,0 +1,4 @@ +set pm3d map +set size square +set isosamples 255,255 +splot [0:255][0:255]-(floor(x)^floor(y)) diff --git a/Task/Munching-squares/Go/munching-squares.go b/Task/Munching-squares/Go/munching-squares.go new file mode 100644 index 0000000000..70c2d485aa --- /dev/null +++ b/Task/Munching-squares/Go/munching-squares.go @@ -0,0 +1,17 @@ +package main + +import ( + "image" + "image/png" + "os" +) + +func main() { + g := image.NewGray(image.Rect(0, 0, 256, 256)) + for i := range g.Pix { + g.Pix[i] = uint8(i>>8 ^ i) + } + f, _ := os.Create("xor.png") + png.Encode(f, g) + f.Close() +} diff --git a/Task/Munching-squares/Haskell/munching-squares.hs b/Task/Munching-squares/Haskell/munching-squares.hs new file mode 100644 index 0000000000..682da41cee --- /dev/null +++ b/Task/Munching-squares/Haskell/munching-squares.hs @@ -0,0 +1,4 @@ +import Data.ByteString +import Data.Bits + +main = Data.ByteString.writeFile "out.pgm" (pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [x `xor` y | x <- [0..255], y <- [0..255]])) diff --git a/Task/Munching-squares/Icon/munching-squares.icon b/Task/Munching-squares/Icon/munching-squares.icon new file mode 100644 index 0000000000..1a5859eb9d --- /dev/null +++ b/Task/Munching-squares/Icon/munching-squares.icon @@ -0,0 +1,18 @@ +link printf + +procedure main(A) #: XOR graphic + wsize := 512 + cmax := 32768 + wparms := ["Xmas Xor Graphic","g",sprintf("size=%d,%d",wsize),"bg=black"] + &window := open!wparms | stop("Unable to open window") + + every y := 0 to wsize - 1 do + every x := 0 to wsize - 1 do { + c := cmax/wsize * iand(wsize-1,ixor(x,y)) + Fg(sprintf("%d,%d,%d",c,cmax-c,0)) + DrawPoint(x,y) + } + + until Event() == &lpress # wait for left button to quit + close(&window) +end diff --git a/Task/Munching-squares/J/munching-squares.j b/Task/Munching-squares/J/munching-squares.j new file mode 100644 index 0000000000..d2b3291362 --- /dev/null +++ b/Task/Munching-squares/J/munching-squares.j @@ -0,0 +1,2 @@ + require 'viewmat' + viewmat ~:"1/&.#: ~ i.256 diff --git a/Task/Munching-squares/Java/munching-squares.java b/Task/Munching-squares/Java/munching-squares.java new file mode 100644 index 0000000000..eeea37c844 --- /dev/null +++ b/Task/Munching-squares/Java/munching-squares.java @@ -0,0 +1,31 @@ +import java.awt.Color; +import java.awt.Graphics; + +import javax.swing.JFrame; +import javax.swing.JPanel; + +public class XorPattern extends JFrame{ + private JPanel xorPanel; + + public XorPattern(){ + xorPanel = new JPanel(){ + @Override + public void paint(Graphics g) { + for(int y = 0; y < getHeight();y++){ + for(int x = 0; x < getWidth();x++){ + g.setColor(new Color(0, (x ^ y) % 256, 0)); + g.drawLine(x, y, x, y); + } + } + } + }; + add(xorPanel); + setSize(300, 300); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setVisible(true); + } + + public static void main(String[] args){ + new XorPattern(); + } +} diff --git a/Task/Munching-squares/Liberty-BASIC/munching-squares.liberty b/Task/Munching-squares/Liberty-BASIC/munching-squares.liberty new file mode 100644 index 0000000000..b3780b3804 --- /dev/null +++ b/Task/Munching-squares/Liberty-BASIC/munching-squares.liberty @@ -0,0 +1,31 @@ + nomainwin + + w =512 + ' allow for title bar and window border + WindowWidth =w +2 + WindowHeight =w +34 + + open "XOR Pattern" for graphics_nsb_nf as #w + + #w "trapclose quit" + + #w "down" + + for x =0 to w -1 + for y =0 to w -1 + b =( x xor y) and 255 + print b + #w "color "; 255 -b; " "; b /2; " "; b + #w "set "; x; " "; w -y -1 + scan + next y + next x + + #w "flush" + + wait + + sub quit j$ + close #w + end + end sub diff --git a/Task/Munching-squares/MATLAB/munching-squares.m b/Task/Munching-squares/MATLAB/munching-squares.m new file mode 100644 index 0000000000..3da5899f5c --- /dev/null +++ b/Task/Munching-squares/MATLAB/munching-squares.m @@ -0,0 +1,8 @@ +size = 256; +[x,y] = meshgrid([0:size-1]); + +c = bitxor(x,y); + +colormap bone(size); +image(c); +axis equal; diff --git a/Task/Munching-squares/Mathematica/munching-squares-1.math b/Task/Munching-squares/Mathematica/munching-squares-1.math new file mode 100644 index 0000000000..6b8e8e1bfd --- /dev/null +++ b/Task/Munching-squares/Mathematica/munching-squares-1.math @@ -0,0 +1,4 @@ +ListDensityPlot[ + Table[Table[ + FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], + 2], {x, 0, 255}], {y, 0, 255}]] diff --git a/Task/Munching-squares/Mathematica/munching-squares-2.math b/Task/Munching-squares/Mathematica/munching-squares-2.math new file mode 100644 index 0000000000..a1213429cc --- /dev/null +++ b/Task/Munching-squares/Mathematica/munching-squares-2.math @@ -0,0 +1 @@ +ArrayPlot[Array[BitXor, {511, 511}]] diff --git a/Task/Munching-squares/OCaml/munching-squares.ocaml b/Task/Munching-squares/OCaml/munching-squares.ocaml new file mode 100644 index 0000000000..08251ca6c0 --- /dev/null +++ b/Task/Munching-squares/OCaml/munching-squares.ocaml @@ -0,0 +1,13 @@ +open Graphics + +let () = + open_graph ""; + resize_window 256 256; + for y = 0 to pred (size_y()) do + for x = 0 to pred (size_x()) do + let v = (x lxor y) land 0xFF in + set_color (rgb v (255 - v) 0); + plot x y + done; + done; + ignore(read_key()) diff --git a/Task/Munching-squares/Octave/munching-squares.octave b/Task/Munching-squares/Octave/munching-squares.octave new file mode 100644 index 0000000000..e627a26c7b --- /dev/null +++ b/Task/Munching-squares/Octave/munching-squares.octave @@ -0,0 +1,8 @@ +size = 256; +[x,y] = meshgrid([0:size-1]); + +c = bitxor(x,y); + +colormap(jet(size)); +image(c); +axis equal; diff --git a/Task/Munching-squares/PHP/munching-squares.php b/Task/Munching-squares/PHP/munching-squares.php new file mode 100644 index 0000000000..77a989a007 --- /dev/null +++ b/Task/Munching-squares/PHP/munching-squares.php @@ -0,0 +1,24 @@ +header("Content-Type: image/png"); + +$w = 256; +$h = 256; + +$im = imagecreate($w, $h) + or die("Cannot Initialize new GD image stream"); + +$color = array(); +for($i=0;$i<256;$i++) +{ + array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i)); +} + +for($i=0;$i<$w;$i++) +{ + for($j=0;$j<$h;$j++) + { + imagesetpixel($im,$i,$j,$color[$i^$j]); + } +} + +imagepng($im); +imagedestroy($im); diff --git a/Task/Munching-squares/PL-I/munching-squares.pli b/Task/Munching-squares/PL-I/munching-squares.pli new file mode 100644 index 0000000000..e334d90cd3 --- /dev/null +++ b/Task/Munching-squares/PL-I/munching-squares.pli @@ -0,0 +1,14 @@ +munch: procedure options (main); /* 21 May 2014 */ + + declare screen (0:255, 0:255) bit(24) aligned; + declare b bit(8) aligned; + declare (x, y) unsigned fixed binary (8); + + do x = 0 upthru hbound(screen,2); + do y = 0 upthru hbound(screen,1); + b = unspec(x) ^ unspec(y); + screen(x,y) = b; + end; + end; + call writeppm(screen); +end munch; diff --git a/Task/Munching-squares/Perl-6/munching-squares-1.pl6 b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 new file mode 100644 index 0000000000..9e28bce049 --- /dev/null +++ b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 @@ -0,0 +1,18 @@ +my $ppm = open("munching.ppm", :w, :bin) or + die "Can't create munching.ppm: $!"; + +$ppm.print(q :to 'EOT'); +P3 +256 256 +255 +EOT + +for 0 .. 255 -> $row { + for 0 .. 255 -> $col { + my $color = $row +^ $col; + $ppm.print("0 $color 0 "); + } + $ppm.say(); +} + +$ppm.close(); diff --git a/Task/Munching-squares/Perl-6/munching-squares-2.pl6 b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 new file mode 100644 index 0000000000..91ffa56cde --- /dev/null +++ b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 @@ -0,0 +1,19 @@ +my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, + map -> $x { floor ($x/256) ** 3 * 256 }, + ((0...255) Z + (255...0) Z + (0,2...254),(254,252...0)); + + +my $PPM = open "munching.ppm", :w, :bin or die "Can't create munching.ppm: $!"; + +$PPM.print: qq:to/EOH/; + P6 + # munching.pgm + 256 256 + 255 + EOH + +$PPM.write: @colors[$_] for ^256 X+^ ^256; + +$PPM.close; diff --git a/Task/Munching-squares/Perl/munching-squares.pl b/Task/Munching-squares/Perl/munching-squares.pl new file mode 100644 index 0000000000..6ab75db3cb --- /dev/null +++ b/Task/Munching-squares/Perl/munching-squares.pl @@ -0,0 +1,12 @@ +use GD; + +my $img = new GD::Image(256, 256, 1); + +for my $y(0..255) { + for my $x(0..255) { + my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y)); + $img->setPixel($x, $y, $color); + } +} + +print $img->png diff --git a/Task/Munching-squares/Prolog/munching-squares.pro b/Task/Munching-squares/Prolog/munching-squares.pro new file mode 100644 index 0000000000..3c7159f439 --- /dev/null +++ b/Task/Munching-squares/Prolog/munching-squares.pro @@ -0,0 +1,18 @@ +xor_pattern :- + new(D, window('XOR Pattern')), + send(D, size, size(512,512)), + new(Img, image(@nil, width := 512, height := 512 , kind := pixmap)), + + forall(between(0,511, I), + ( forall(between(0,511, J), + ( V is I xor J, + R is (V * 1024) mod 65536, + G is (65536 - V * 1024) mod 65536, + ( V mod 2 =:= 0 + -> B is (V * 4096) mod 65536 + ; B is (65536 - (V * 4096)) mod 65536), + send(Img, pixel(I, J, colour(@default, R, G, B))))))), + + new(Bmp, bitmap(Img)), + send(D, display, Bmp, point(0,0)), + send(D, open). diff --git a/Task/Munching-squares/PureBasic/munching-squares.purebasic b/Task/Munching-squares/PureBasic/munching-squares.purebasic new file mode 100644 index 0000000000..f15c10fc4e --- /dev/null +++ b/Task/Munching-squares/PureBasic/munching-squares.purebasic @@ -0,0 +1,26 @@ +#palletteSize = 128 +Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values + Protected result = x ! y + ProcedureReturn Mod(result, #palletteSize) / #palletteSize +EndProcedure + +Procedure drawPattern() + StartDrawing(ImageOutput(0)) + DrawingMode(#PB_2DDrawing_Gradient) + CustomGradient(@XorPattern()) + ;specify a gradient pallette from which only specific indexes will be used + For i = 1 To #palletteSize + GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD + Next + Box(0, 0, ImageWidth(0), ImageHeight(0)) + StopDrawing() +EndProcedure + +If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu) + CreateImage(0, WindowWidth(0), WindowHeight(0)) + drawPattern() + ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0)) + Repeat + event = WaitWindowEvent(20) + Until event = #PB_Event_CloseWindow +EndIf diff --git a/Task/Munching-squares/Python/munching-squares.py b/Task/Munching-squares/Python/munching-squares.py new file mode 100644 index 0000000000..f4f9502b17 --- /dev/null +++ b/Task/Munching-squares/Python/munching-squares.py @@ -0,0 +1,11 @@ +import Image, ImageDraw + +image = Image.new("RGB", (256, 256)) +drawingTool = ImageDraw.Draw(image) + +for x in range(256): + for y in range(256): + drawingTool.point((x, y), (0, x^y, 0)) + +del drawingTool +image.save("xorpic.png", "PNG") diff --git a/Task/Munching-squares/README b/Task/Munching-squares/README new file mode 100644 index 0000000000..c12d22b2ad --- /dev/null +++ b/Task/Munching-squares/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Munching_squares diff --git a/Task/Munching-squares/Racket/munching-squares.rkt b/Task/Munching-squares/Racket/munching-squares.rkt new file mode 100644 index 0000000000..ed4bc3681a --- /dev/null +++ b/Task/Munching-squares/Racket/munching-squares.rkt @@ -0,0 +1,9 @@ +#lang racket +(require racket/draw) +(define palette (for/vector ([x 256]) (make-object color% 0 0 x))) +(define bm (make-object bitmap% 256 256)) +(define dc (new bitmap-dc% [bitmap bm])) +(for* ([x 256] [y 256]) + (define c (vector-ref palette (bitwise-xor x y))) + (send dc set-pixel x y c)) +bm diff --git a/Task/Munching-squares/Ruby/munching-squares.rb b/Task/Munching-squares/Ruby/munching-squares.rb new file mode 100644 index 0000000000..577a4c8287 --- /dev/null +++ b/Task/Munching-squares/Ruby/munching-squares.rb @@ -0,0 +1,25 @@ +load 'raster_graphics.rb' + +class Pixmap + def self.xor_pattern(width, height, rgb1, rgb2) + # create colour table + size = 256 + colours = Array.new(size) do |i| + RGBColour.new( + (rgb1.red + (rgb2.red - rgb1.red) * i / size), + (rgb1.green + (rgb2.green - rgb1.green) * i / size), + (rgb1.blue + (rgb2.blue - rgb1.blue) * i / size), + ) + end + + # create the image + pixmap = new(width, height) + pixmap.each_pixel do |x, y| + pixmap[x,y] = colours[(x^y)%size] + end + pixmap + end +end + +img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) +img.save_as_png('xorpattern.png') diff --git a/Task/Munching-squares/Run-BASIC/munching-squares.run b/Task/Munching-squares/Run-BASIC/munching-squares.run new file mode 100644 index 0000000000..8730771501 --- /dev/null +++ b/Task/Munching-squares/Run-BASIC/munching-squares.run @@ -0,0 +1,11 @@ +w = 100 +graphic #g, w,w +for x = 0 to w + for y = 0 to w + b = (x xor y) and 255 + #g color(255 -b,b /2,b) + #g "set "; x; " "; w -y -1 + next y +next x +render #g +#g "flush" diff --git a/Task/Munching-squares/Scala/munching-squares.scala b/Task/Munching-squares/Scala/munching-squares.scala new file mode 100644 index 0000000000..c2277df3a6 --- /dev/null +++ b/Task/Munching-squares/Scala/munching-squares.scala @@ -0,0 +1,26 @@ +import scala.swing.Swing.pair2Dimension +import scala.swing.{ Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication } + +object XorPattern extends SimpleSwingApplication { + + val ui = new Panel { + + override def paintComponent(g: Graphics2D) = { + super.paintComponent(g) + for { + y <- 0 until size.getHeight().toInt + x <- 0 until size.getWidth().toInt + } { + g.setColor(new Color(0, (x ^ y) % 256, 0)) + g.drawLine(x, y, x, y) + } + } + } + + def top = new MainFrame { + preferredSize = (300, 300) + title = "Rosetta Code >>> Task: Munching squares | Language: Scala" + contents = ui + centerOnScreen() + } +} diff --git a/Task/Munching-squares/TI-83-BASIC/munching-squares.ti-83 b/Task/Munching-squares/TI-83-BASIC/munching-squares.ti-83 new file mode 100644 index 0000000000..23aabdfa9b --- /dev/null +++ b/Task/Munching-squares/TI-83-BASIC/munching-squares.ti-83 @@ -0,0 +1,76 @@ +PROGRAM:XORPATT +" •.-,+-°-1+o*:πOX"→Str1 + +ClrHome + +{0,0,0,0}→L1 +{0,0,0,0)→L2 + +For(I,1,8,1) +For(J,1,16,1) +J→A +I→B + +If A>8 +Then +A-8→A +1→L1(1) +Else +0→L1(1) +End + +If A>4 +Then +A-4→A +1→L1(2) +Else +0→L1(2) +End + +If A>2 +Then +A-2→A +1→L1(3) +Else +0→L1(3) +End + +If A>1 +Then +1→L1(4) +Else +0→L1(4) +End + +0→L2(1) + +If B>4 +Then +B-4→B +1→L2(2) +Else +0→L2(2) +End + +If B>2 +Then +B-2→B +1→L2(3) +Else +0→L2(3) +End + +If B>1 +Then +1→L2(4) +Else +0→L2(4) +End + +L1≠L2→L3 +8L3(1)+4L3(2)+2L3(3)+L3(4)→C +Output(I,J,sub(Str1,C+1,1)) + +End +End +Pause diff --git a/Task/Munching-squares/Tcl/munching-squares.tcl b/Task/Munching-squares/Tcl/munching-squares.tcl new file mode 100644 index 0000000000..7979947127 --- /dev/null +++ b/Task/Munching-squares/Tcl/munching-squares.tcl @@ -0,0 +1,27 @@ +package require Tk + +proc xorImage {img table} { + set data {} + set h [image height $img] + set w [image width $img] + for {set y 0} {$y < $h} {incr y} { + set row {} + for {set x 0} {$x < $w} {incr x} { + lappend row [lindex $table [expr {($x^$y) % [llength $table]}]] + } + lappend data $row + } + $img put $data +} +proc inRange {i f t} {expr {$f + ($t-$f)*$i/255}} +proc mkTable {rf rt gf gt bf bt} { + for {set i 0} {$i < 256} {incr i} { + lappend tbl [format "#%02x%02x%02x" \ + [inRange $i $rf $rt] [inRange $i $gf $gt] [inRange $i $bf $bt]] + } + return $tbl +} + +set img [image create photo -width 512 -height 512] +xorImage $img [mkTable 0 255 64 192 255 0] +pack [label .l -image $img] diff --git a/Task/Munching-squares/XPL0/munching-squares.xpl0 b/Task/Munching-squares/XPL0/munching-squares.xpl0 new file mode 100644 index 0000000000..ed364c8b34 --- /dev/null +++ b/Task/Munching-squares/XPL0/munching-squares.xpl0 @@ -0,0 +1,15 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +int X, Y; +[SetVid($101); \set 640x480 graphics with 8-bit color +port($3C8):= 0; \set color registers with beautiful shades +for X:= 0 to 256-1 do + [port($3C9):= X>>1; \red + port($3C9):= X>>3; \green + port($3C9):= X; \blue + ]; +for Y:= 0 to 256-1 do \"color table" is array of 256 registers + for X:= 0 to 256-1 do + Point(X, Y, X|Y); \"|" = XOR, not OR which is "!" +X:= ChIn(1); \wait for keystroke +SetVid(3); \restore normal text mode +] diff --git a/Task/Mutex/00DESCRIPTION b/Task/Mutex/00DESCRIPTION deleted file mode 100644 index 3fc89c2711..0000000000 --- a/Task/Mutex/00DESCRIPTION +++ /dev/null @@ -1,19 +0,0 @@ -A '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. A mutex is said to be seized by a [[task]] decreasing ''k''. It is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. A [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex. - -A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. - -=Variants of mutexes= - -==Global and local mutexes== -Usually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one. - -==Reentrant mutex== -A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it. - -==Read write mutex== -A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control. - -=Deadlock prevention= -There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem. - -=Sample implementations / APIs= diff --git a/Task/Mutex/00META.yaml b/Task/Mutex/00META.yaml deleted file mode 100644 index d2f44cc2b9..0000000000 --- a/Task/Mutex/00META.yaml +++ /dev/null @@ -1,6 +0,0 @@ ---- -category: -- Encyclopedia -note: Concurrency -requires: -- Concurrency diff --git a/Task/Mutex/Ada/mutex-1.ada b/Task/Mutex/Ada/mutex-1.ada deleted file mode 100644 index cde532dc1c..0000000000 --- a/Task/Mutex/Ada/mutex-1.ada +++ /dev/null @@ -1,6 +0,0 @@ -protected type Mutex is - entry Seize; - procedure Release; -private - Owned : Boolean := False; -end Mutex; diff --git a/Task/Mutex/Ada/mutex-2.ada b/Task/Mutex/Ada/mutex-2.ada deleted file mode 100644 index 32e7b79d2d..0000000000 --- a/Task/Mutex/Ada/mutex-2.ada +++ /dev/null @@ -1,10 +0,0 @@ -protected body Mutex is - entry Seize when not Owned is - begin - Owned := True; - end Seize; - procedure Release is - begin - Owned := False; - end Release; -end Mutex; diff --git a/Task/Mutex/Ada/mutex-3.ada b/Task/Mutex/Ada/mutex-3.ada deleted file mode 100644 index 8768b13882..0000000000 --- a/Task/Mutex/Ada/mutex-3.ada +++ /dev/null @@ -1,15 +0,0 @@ -declare - M : Mutex; -begin - M.Seize; -- Wait infinitely for the mutex to be free - ... -- Critical code - M.Release; -- Release the mutex - ... - select - M.Seize; -- Wait no longer than 0.5s - or delay 0.5; - raise Timed_Out; - end select; - ... -- Critical code - M.Release; -- Release the mutex -end; diff --git a/Task/Mutex/BBC-BASIC/mutex.bbc b/Task/Mutex/BBC-BASIC/mutex.bbc deleted file mode 100644 index 85699b9436..0000000000 --- a/Task/Mutex/BBC-BASIC/mutex.bbc +++ /dev/null @@ -1,13 +0,0 @@ - REM Create mutex: - SYS "CreateMutex", 0, 0, 0 TO hMutex% - - REM Wait to acquire mutex: - REPEAT - SYS "WaitForSingleObject", hMutex%, 1 TO res% - UNTIL res% = 0 - - REM Release mutex: - SYS "ReleaseMutex", hMutex% - - REM Free mutex: - SYS "CloseHandle", hMutex% diff --git a/Task/Mutex/C/mutex-1.c b/Task/Mutex/C/mutex-1.c deleted file mode 100644 index 3f5ed4f640..0000000000 --- a/Task/Mutex/C/mutex-1.c +++ /dev/null @@ -1 +0,0 @@ -HANDLE hMutex = CreateMutex(NULL, FALSE, NULL); diff --git a/Task/Mutex/C/mutex-2.c b/Task/Mutex/C/mutex-2.c deleted file mode 100644 index c6341da5f0..0000000000 --- a/Task/Mutex/C/mutex-2.c +++ /dev/null @@ -1 +0,0 @@ -WaitForSingleObject(hMutex, INFINITE); diff --git a/Task/Mutex/C/mutex-3.c b/Task/Mutex/C/mutex-3.c deleted file mode 100644 index 053c747094..0000000000 --- a/Task/Mutex/C/mutex-3.c +++ /dev/null @@ -1 +0,0 @@ -ReleaseMutex(hMutex); diff --git a/Task/Mutex/C/mutex-4.c b/Task/Mutex/C/mutex-4.c deleted file mode 100644 index 9cf8f707bf..0000000000 --- a/Task/Mutex/C/mutex-4.c +++ /dev/null @@ -1 +0,0 @@ -CloseHandle(hMutex); diff --git a/Task/Mutex/C/mutex-5.c b/Task/Mutex/C/mutex-5.c deleted file mode 100644 index 25eaeec95b..0000000000 --- a/Task/Mutex/C/mutex-5.c +++ /dev/null @@ -1,3 +0,0 @@ -#include - -pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; diff --git a/Task/Mutex/C/mutex-6.c b/Task/Mutex/C/mutex-6.c deleted file mode 100644 index e646631245..0000000000 --- a/Task/Mutex/C/mutex-6.c +++ /dev/null @@ -1,2 +0,0 @@ -pthread_mutex_t mutex; -pthread_mutex_init(&mutex, NULL); diff --git a/Task/Mutex/C/mutex-7.c b/Task/Mutex/C/mutex-7.c deleted file mode 100644 index 2d2102e5b9..0000000000 --- a/Task/Mutex/C/mutex-7.c +++ /dev/null @@ -1 +0,0 @@ -int error = pthread_mutex_lock(&mutex); diff --git a/Task/Mutex/C/mutex-8.c b/Task/Mutex/C/mutex-8.c deleted file mode 100644 index 8b44381c99..0000000000 --- a/Task/Mutex/C/mutex-8.c +++ /dev/null @@ -1 +0,0 @@ -int error = pthread_mutex_unlock(&mutex); diff --git a/Task/Mutex/C/mutex-9.c b/Task/Mutex/C/mutex-9.c deleted file mode 100644 index 96ebdda59d..0000000000 --- a/Task/Mutex/C/mutex-9.c +++ /dev/null @@ -1 +0,0 @@ -int error = pthread_mutex_trylock(&mutex); diff --git a/Task/Mutex/D/mutex-1.d b/Task/Mutex/D/mutex-1.d deleted file mode 100644 index ca8d15cc25..0000000000 --- a/Task/Mutex/D/mutex-1.d +++ /dev/null @@ -1,11 +0,0 @@ -class Synced -{ -public: - synchronized int func (int input) - { - num += input; - return num; - } -private: - static num = 0; -} diff --git a/Task/Mutex/D/mutex-2.d b/Task/Mutex/D/mutex-2.d deleted file mode 100644 index 4b557fb12f..0000000000 --- a/Task/Mutex/D/mutex-2.d +++ /dev/null @@ -1,46 +0,0 @@ -import tango.core.Thread, tango.io.Stdout, tango.util.log.Trace; - -class Synced { - public synchronized int func (int input) { - Trace.formatln("in {} at func enter: {}", input, foo); - // stupid loop to consume some time - int arg; - for (int i = 0; i < 1000*input; ++i) { - for (int j = 0; j < 10_000; ++j) arg += j; - } - foo += input; - Trace.formatln("in {} at func exit: {}", input, foo); - return arg; - } - private static int foo; -} - -void main(char[][] args) { - SimpleThread[] ht; - Stdout.print( "Starting application..." ).newline; - - for (int i=0; i < 3; i++) { - Stdout.print( "Starting thread for: " )(i).newline; - ht ~= new SimpleThread(i+1); - ht[i].start(); - } - - // wait for all threads - foreach( s; ht ) - s.join(); -} - -class SimpleThread : Thread -{ - private int d_id; - this (int id) { - super (&run); - d_id = id; - } - - void run() { - auto tested = new Synced; - Trace.formatln ("in run() {}", d_id); - tested.func(d_id); - } -} diff --git a/Task/Mutex/D/mutex-3.d b/Task/Mutex/D/mutex-3.d deleted file mode 100644 index 3d2dae9e1a..0000000000 --- a/Task/Mutex/D/mutex-3.d +++ /dev/null @@ -1,11 +0,0 @@ -class Synced { - public int func (int input) { - synchronized(Synced.classinfo) { - // ... - foo += input; - // ... - } - return arg; - } - private static int foo; -} diff --git a/Task/Mutex/E/mutex-1.e b/Task/Mutex/E/mutex-1.e deleted file mode 100644 index 8a5a4cba1e..0000000000 --- a/Task/Mutex/E/mutex-1.e +++ /dev/null @@ -1,16 +0,0 @@ -def makeMutex() { - - # The mutex is available (released) if available is resolved, otherwise it - # has been seized/locked. The specific value of available is irrelevant. - var available := null - - # The interface to the mutex is a function, taking a function (action) - # to be executed. - def mutex(action) { - # By assigning available to our promise here, the mutex remains - # unavailable to the /next/ caller until /this/ action has gotten - # its turn /and/ resolved its returned value. - available := Ref.whenResolved(available, fn _ { action <- () }) - } - return mutex -} diff --git a/Task/Mutex/E/mutex-2.e b/Task/Mutex/E/mutex-2.e deleted file mode 100644 index 6d6033f383..0000000000 --- a/Task/Mutex/E/mutex-2.e +++ /dev/null @@ -1,39 +0,0 @@ -Creating the mutex: - -? def mutex := makeMutex() -# value: - -Creating the shared resource: - -? var value := 0 -# value: 0 - -Manipulating the shared resource non-atomically so as to show a problem: - -? for _ in 0..1 { -> when (def v := (&value) <- get()) -> { -> (&value) <- put(v + 1) -> } -> } - -? value -# value: 1 - -The value has been incremented twice, but non-atomically, and so is 1 rather -than the intended 2. - -? value := 0 -# value: 0 - -This time, we use the mutex to protect the action. - -? for _ in 0..1 { -> mutex(fn { -> when (def v := (&value) <- get()) -> { -> (&value) <- put(v + 1) -> } -> }) -> } - -? value -# value: 2 diff --git a/Task/Mutex/Erlang/mutex.erl b/Task/Mutex/Erlang/mutex.erl deleted file mode 100644 index e4044feff5..0000000000 --- a/Task/Mutex/Erlang/mutex.erl +++ /dev/null @@ -1,40 +0,0 @@ --module( mutex ). - --export( [task/0] ). - -task() -> - Mutex = erlang:spawn( fun() -> loop() end ), - [erlang:spawn(fun() -> random:seed( X, 0, 0 ), print(Mutex, X, 3) end) || X <- lists:seq(1, 3)]. - - - -loop() -> - receive - {acquire, Pid} -> - Pid ! {access, erlang:self()}, - receive - {release, Pid} -> loop() - end - end. - -mutex_acquire( Pid ) -> - Pid ! {acquire, erlang:self()}, - receive - {access, Pid} -> ok - end. - -mutex_release( Pid ) -> Pid ! {release, erlang:self()}. - -print( _Mutex, _N, 0 ) -> ok; -print( Mutex, N, M ) -> - timer:sleep( random:uniform(100) ), - mutex_acquire( Mutex ), - io:fwrite( "Print ~p: ", [N] ), - [print_slow(X) || X <- lists:seq(1, 3)], - io:nl(), - mutex_release( Mutex ), - print( Mutex, N, M - 1 ). - -print_slow( X ) -> - io:fwrite( " ~p", [X] ), - timer:sleep( 100 ). diff --git a/Task/Mutex/Go/mutex-1.go b/Task/Mutex/Go/mutex-1.go deleted file mode 100644 index ff4cfe9e4a..0000000000 --- a/Task/Mutex/Go/mutex-1.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "sync" - "time" -) - -var value int -var m sync.Mutex -var wg sync.WaitGroup - -func slowInc() { - m.Lock() - v := value - time.Sleep(1e8) - value = v+1 - m.Unlock() - wg.Done() -} - -func main() { - wg.Add(2) - go slowInc() - go slowInc() - wg.Wait() - fmt.Println(value) -} diff --git a/Task/Mutex/Go/mutex-2.go b/Task/Mutex/Go/mutex-2.go deleted file mode 100644 index 4a68ccee9a..0000000000 --- a/Task/Mutex/Go/mutex-2.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -var value int - -func slowInc(ch, done chan bool) { - // channel receive, used here to implement mutex lock. - // it will block until a value is available on the channel - <-ch - - // same as above - v := value - time.Sleep(1e8) - value = v + 1 - - // channel send, equivalent to mutex unlock. - // makes a value available on channel - ch <- true - - // channels can be used to signal completion too - done <- true -} - -func main() { - ch := make(chan bool, 1) // ch used as a mutex - done := make(chan bool) // another channel used to signal completion - go slowInc(ch, done) - go slowInc(ch, done) - // a freshly created sync.Mutex starts out unlocked, but a freshly created - // channel is empty, which for us represents "locked." sending a value on - // the channel puts the value up for grabs, thus representing "unlocked." - ch <- true - <-done - <-done - fmt.Println(value) -} diff --git a/Task/Mutex/Haskell/mutex-1.hs b/Task/Mutex/Haskell/mutex-1.hs deleted file mode 100644 index 396f23e151..0000000000 --- a/Task/Mutex/Haskell/mutex-1.hs +++ /dev/null @@ -1,4 +0,0 @@ -takeMVar :: MVar a -> IO a -putMVar :: MVar a -> a -> IO () -tryTakeMVar :: MVar a -> IO (Maybe a) -tryPutMVar :: MVar a -> a -> IO Bool diff --git a/Task/Mutex/Haskell/mutex-2.hs b/Task/Mutex/Haskell/mutex-2.hs deleted file mode 100644 index 7e5bc3a9ea..0000000000 --- a/Task/Mutex/Haskell/mutex-2.hs +++ /dev/null @@ -1,7 +0,0 @@ - x: = mutex() # create and return a mutex handle for sharing between threads needing to synchronize with each other - - lock(x) # lock mutex x - - trylock(x)) # non-blocking lock, succeeds only if there are no other thread already in the critical region - - unlock(x) # unlock mutex x diff --git a/Task/Mutex/Java/mutex-1.java b/Task/Mutex/Java/mutex-1.java deleted file mode 100644 index 4033ea69fd..0000000000 --- a/Task/Mutex/Java/mutex-1.java +++ /dev/null @@ -1,10 +0,0 @@ -import java.util.concurrent.Semaphore; - -public class VolatileClass{ - public Semaphore mutex = new Semaphore(1); //also a "fair" boolean may be passed which, - //when true, queues requests for the lock - public void needsToBeSynched(){ - //... - } - //delegate methods could be added for acquiring and releasing the mutex -} diff --git a/Task/Mutex/Java/mutex-2.java b/Task/Mutex/Java/mutex-2.java deleted file mode 100644 index f4b35d36e0..0000000000 --- a/Task/Mutex/Java/mutex-2.java +++ /dev/null @@ -1,10 +0,0 @@ -public class TestVolitileClass throws Exception{ - public static void main(String[] args){ - VolatileClass vc = new VolatileClass(); - vc.mutex.acquire(); //will wait automatically if another class has the mutex - //can be interrupted similarly to a Thread - //use acquireUninterruptibly() to avoid that - vc.needsToBeSynched(); - vc.mutex.release(); - } -} diff --git a/Task/Mutex/Java/mutex-3.java b/Task/Mutex/Java/mutex-3.java deleted file mode 100644 index d4d4ed4a6d..0000000000 --- a/Task/Mutex/Java/mutex-3.java +++ /dev/null @@ -1,35 +0,0 @@ -public class Main { - static Object mutex = new Object(); - static int i = 0; - - public void addAndPrint() - { - System.out.print("" + i + " + 1 = "); - i++; - System.out.println("" + i); - } - - public void subAndPrint() - { - System.out.print("" + i + " - 1 = "); - i--; - System.out.println("" + i); - } - - - public static void main(String[] args){ - final Main m = new Main(); - new Thread() { - public void run() - { - while (true) { synchronized(m.mutex) { m.addAndPrint(); } } - } - }.start(); - new Thread() { - public void run() - { - while (true) { synchronized(m.mutex) { m.subAndPrint(); } } - } - }.start(); - } -} diff --git a/Task/Mutex/Logtalk/mutex-1.logtalk b/Task/Mutex/Logtalk/mutex-1.logtalk deleted file mode 100644 index ae0b0e17fd..0000000000 --- a/Task/Mutex/Logtalk/mutex-1.logtalk +++ /dev/null @@ -1,33 +0,0 @@ -:- object(slow_print). - - :- threaded. - - :- public(start/0). - - :- private([slow_print_abc/0, slow_print_123/0]). - :- synchronized([slow_print_abc/0, slow_print_123/0]). - - start :- - % launch two threads, running never ending goals - threaded(( - repeat_abc, - repeat_123 - )). - - repeat_abc :- - repeat, slow_print_abc, fail. - - repeat_123 :- - repeat, slow_print_123, fail. - - slow_print_abc :- - write(a), thread_sleep(0.2), - write(b), thread_sleep(0.2), - write(c), nl. - - slow_print_123 :- - write(1), thread_sleep(0.2), - write(2), thread_sleep(0.2), - write(3), nl. - -:- end_object. diff --git a/Task/Mutex/Logtalk/mutex-2.logtalk b/Task/Mutex/Logtalk/mutex-2.logtalk deleted file mode 100644 index 844342e570..0000000000 --- a/Task/Mutex/Logtalk/mutex-2.logtalk +++ /dev/null @@ -1,11 +0,0 @@ -?- slow_print::start. -abc -123 -abc -123 -abc -123 -abc -123 -abc -... diff --git a/Task/Mutex/OCaml/mutex.ocaml b/Task/Mutex/OCaml/mutex.ocaml deleted file mode 100644 index 4081a4ee8c..0000000000 --- a/Task/Mutex/OCaml/mutex.ocaml +++ /dev/null @@ -1,8 +0,0 @@ -let m = Mutex.create() in -Mutex.lock m; (* locks in blocking mode *) - -if (Mutex.try_lock m) -then ... (* did the lock *) -else ... (* already locked, do not block *) - -Mutex.unlock m; diff --git a/Task/Mutex/Objeck/mutex.objeck b/Task/Mutex/Objeck/mutex.objeck deleted file mode 100644 index e9ee0a50ee..0000000000 --- a/Task/Mutex/Objeck/mutex.objeck +++ /dev/null @@ -1,6 +0,0 @@ -m := ThreadMutex->New("lock a"); -# section locked -critical(m) { - ... -} -# section unlocked diff --git a/Task/Mutex/Objective-C/mutex.m b/Task/Mutex/Objective-C/mutex.m deleted file mode 100644 index d29367043e..0000000000 --- a/Task/Mutex/Objective-C/mutex.m +++ /dev/null @@ -1,11 +0,0 @@ -NSLock *m = [[NSLock alloc] init]; - -[m lock]; // locks in blocking mode - -if ([m tryLock]) { // acquire a lock -- does not block if not acquired - // lock acquired -} else { - // already locked, does not block -} - -[m unlock]; diff --git a/Task/Mutex/Oz/mutex-1.oz b/Task/Mutex/Oz/mutex-1.oz deleted file mode 100644 index cd5acd705a..0000000000 --- a/Task/Mutex/Oz/mutex-1.oz +++ /dev/null @@ -1 +0,0 @@ -declare L = {Lock.new} diff --git a/Task/Mutex/Oz/mutex-2.oz b/Task/Mutex/Oz/mutex-2.oz deleted file mode 100644 index 45f7313466..0000000000 --- a/Task/Mutex/Oz/mutex-2.oz +++ /dev/null @@ -1,3 +0,0 @@ -lock L then - {System.show exclusive} -end diff --git a/Task/Mutex/Oz/mutex-3.oz b/Task/Mutex/Oz/mutex-3.oz deleted file mode 100644 index 5d9e8eb552..0000000000 --- a/Task/Mutex/Oz/mutex-3.oz +++ /dev/null @@ -1,9 +0,0 @@ -class Test - prop locking - - meth test - lock - {Show exclusive} - end - end -end diff --git a/Task/Mutex/Perl-6/mutex.pl6 b/Task/Mutex/Perl-6/mutex.pl6 deleted file mode 100644 index 1b409522aa..0000000000 --- a/Task/Mutex/Perl-6/mutex.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -my $lock = Lock.new; - -$lock.protect: { your-ad-here() } diff --git a/Task/Mutex/Perl/mutex.pl b/Task/Mutex/Perl/mutex.pl deleted file mode 100644 index c5ce057e65..0000000000 --- a/Task/Mutex/Perl/mutex.pl +++ /dev/null @@ -1,28 +0,0 @@ -use Thread qw'async'; -use threads::shared; - -my ($lock1, $lock2, $resource1, $resource2) :shared = (0) x 4; - -sub use_resource { - { # curly provides lexical scope, exiting which causes lock to release - lock $lock1; - $resource1 --; # acquire resource - sleep(int rand 3); # artifical delay to pretend real work - $resource1 ++; # release resource - print "In thread ", threads->tid(), ": "; - print "Resource1 is $resource1\n"; - } - { - lock $lock2; - $resource2 --; - sleep(int rand 3); - $resource2 ++; - print "In thread ", threads->tid(), ": "; - print "Resource2 is $resource2\n"; - } -} - -# create 9 threads and clean up each after they are done. -for ( map async{ use_resource }, 1 .. 9) { - $_->join -} diff --git a/Task/Mutex/PureBasic/mutex-1.purebasic b/Task/Mutex/PureBasic/mutex-1.purebasic deleted file mode 100644 index 9b4c278b20..0000000000 --- a/Task/Mutex/PureBasic/mutex-1.purebasic +++ /dev/null @@ -1,5 +0,0 @@ -MyMutex=CreateMutex() -Result = TryLockMutex(MyMutex) -LockMutex(MyMutex) -UnlockMutex(MyMutex) -FreeMutex(MyMutex) diff --git a/Task/Mutex/PureBasic/mutex-2.purebasic b/Task/Mutex/PureBasic/mutex-2.purebasic deleted file mode 100644 index 6224c22f75..0000000000 --- a/Task/Mutex/PureBasic/mutex-2.purebasic +++ /dev/null @@ -1,34 +0,0 @@ -Declare ThreadedTask(*MyArgument) -Define Mutex - -If OpenConsole() - Define thread1, thread2, thread3 - - Mutex = CreateMutex() - thread1 = CreateThread(@ThreadedTask(), 1): Delay(5) - thread2 = CreateThread(@ThreadedTask(), 2): Delay(5) - thread3 = CreateThread(@ThreadedTask(), 3) - WaitThread(thread1) - WaitThread(thread2) - WaitThread(thread3) - - PrintN(#CRLF$+"Press ENTER to exit"): Input() - FreeMutex(Mutex) - CloseConsole() -EndIf - -Procedure ThreadedTask(*MyArgument) - Shared Mutex - Protected a, b - For a = 1 To 3 - LockMutex(Mutex) - ; Without Lock-/UnLockMutex() here the output from the parallel threads would be all mixed. - ; Reading/Writing to shared memory resources are a common use for Mutextes i PureBasic - PrintN("Thread "+Str(*MyArgument)+": Print 3 numbers in a row:") - For b = 1 To 3 - Delay(75) - PrintN("Thread "+Str(*MyArgument)+" : "+Str(b)) - Next - UnlockMutex(Mutex) - Next -EndProcedure diff --git a/Task/Mutex/Python/mutex.py b/Task/Mutex/Python/mutex.py deleted file mode 100644 index b352a5f7e5..0000000000 --- a/Task/Mutex/Python/mutex.py +++ /dev/null @@ -1,30 +0,0 @@ -import threading -from time import sleep - -# res: max number of resources. If changed to 1, it functions -# identically to a mutex/lock object -res = 2 -sema = threading.Semaphore(res) - -class res_thread(threading.Thread): - def run(self): - global res - n = self.getName() - for i in range(1, 4): - # acquire a resource if available and work hard - # for 2 seconds. if all res are occupied, block - # and wait - sema.acquire() - res = res - 1 - print n, "+ res count", res - sleep(2) - - # after done with resource, return it to pool and flag so - res = res + 1 - print n, "- res count", res - sema.release() - -# create 4 threads, each acquire resorce and work -for i in range(1, 5): - t = res_thread() - t.start() diff --git a/Task/Mutex/README b/Task/Mutex/README deleted file mode 100644 index f59beae7d5..0000000000 --- a/Task/Mutex/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Mutex diff --git a/Task/Mutex/Racket/mutex-1.rkt b/Task/Mutex/Racket/mutex-1.rkt deleted file mode 100644 index 7a515140b9..0000000000 --- a/Task/Mutex/Racket/mutex-1.rkt +++ /dev/null @@ -1,6 +0,0 @@ -(define foo - (let ([sema (make-semaphore 1)]) - (lambda (x) - (dynamic-wind (λ() (semaphore-wait sema)) - (λ() (... do something ...)) - (λ() (semaphore-post sema)))))) diff --git a/Task/Mutex/Racket/mutex-2.rkt b/Task/Mutex/Racket/mutex-2.rkt deleted file mode 100644 index aab6e0a6aa..0000000000 --- a/Task/Mutex/Racket/mutex-2.rkt +++ /dev/null @@ -1,10 +0,0 @@ -(define-syntax-rule (define/atomic (name arg ...) E ...) - (define name - (let ([sema (make-semaphore 1)]) - (lambda (arg ...) - (dynamic-wind (λ() (semaphore-wait sema)) - (λ() E ...) - (λ() (semaphore-post sema))))))) -;; this does the same as the above now: -(define/atomic (foo x) - (... do something ...)) diff --git a/Task/Mutex/Ruby/mutex-1.rb b/Task/Mutex/Ruby/mutex-1.rb deleted file mode 100644 index bdcbd08ffe..0000000000 --- a/Task/Mutex/Ruby/mutex-1.rb +++ /dev/null @@ -1,6 +0,0 @@ -require 'mutex_m' - -class SomethingWithMutex - include Mutex_m - ... -end diff --git a/Task/Mutex/Ruby/mutex-2.rb b/Task/Mutex/Ruby/mutex-2.rb deleted file mode 100644 index acd8c8a384..0000000000 --- a/Task/Mutex/Ruby/mutex-2.rb +++ /dev/null @@ -1,2 +0,0 @@ -an_object = Object.new -an_object.extend(Mutex_m) diff --git a/Task/Mutex/Ruby/mutex-3.rb b/Task/Mutex/Ruby/mutex-3.rb deleted file mode 100644 index 6e059710e5..0000000000 --- a/Task/Mutex/Ruby/mutex-3.rb +++ /dev/null @@ -1,16 +0,0 @@ -# acquire a lock -- block execution until it becomes free -an_object.mu_lock - -# acquire a lock -- return immediately even if not acquired -got_lock = an_object.mu_try_lock - -# have a lock? -if an_object.mu_locked? then ... - -# release the lock -an_object.mu_unlock - -# wrap a lock around a block of code -- block execution until it becomes free -an_object.my_synchronize do - do critical stuff -end diff --git a/Task/Mutex/Tcl/mutex-1.tcl b/Task/Mutex/Tcl/mutex-1.tcl deleted file mode 100644 index 6a6e37a83c..0000000000 --- a/Task/Mutex/Tcl/mutex-1.tcl +++ /dev/null @@ -1,13 +0,0 @@ -package require Thread - -# How to create a mutex -set m [thread::mutex create] - -# This will block if the lock is already held unless the mutex is made recursive -thread::mutex lock $m -# Now locked... -thread::mutex unlock $m -# Unlocked again - -# Dispose of the mutex -thread::mutex destroy $m diff --git a/Task/Mutex/Tcl/mutex-2.tcl b/Task/Mutex/Tcl/mutex-2.tcl deleted file mode 100644 index 8213a35c04..0000000000 --- a/Task/Mutex/Tcl/mutex-2.tcl +++ /dev/null @@ -1,11 +0,0 @@ -set rw [thread::rwmutex create] - -# Get and drop a reader lock -thread::rwmutex rlock $rw -thread::rwmutex unlock $rw - -# Get and drop a writer lock -thread::rwmutex wlock $rw -thread::rwmutex unlock $rw - -thread::rwmutex destroy $rw diff --git a/Task/Narcissistic-decimal-number/00DESCRIPTION b/Task/Narcissistic-decimal-number/00DESCRIPTION new file mode 100644 index 0000000000..6e0acf7d98 --- /dev/null +++ b/Task/Narcissistic-decimal-number/00DESCRIPTION @@ -0,0 +1,7 @@ +A [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number] is a non-negative integer, n in which if there are m digits in its decimal representation then the sum of all the individual digits of the decimal representation raised to the power m is equal to n. + +For example, if n is 153 then m, the number of digits is 3 and we have 1^3+5^3+3^3 = 1+125+27 = 153 and so 153 is a narcissistic decimal integer number. + +The task is to generate and show here, the first 25 narcissistic integer numbers. + +Note: 0^1 = 0, the first in the series. diff --git a/Task/Narcissistic-decimal-number/AWK/narcissistic-decimal-number.awk b/Task/Narcissistic-decimal-number/AWK/narcissistic-decimal-number.awk new file mode 100644 index 0000000000..a4243fade9 --- /dev/null +++ b/Task/Narcissistic-decimal-number/AWK/narcissistic-decimal-number.awk @@ -0,0 +1,16 @@ +# syntax: GAWK -f NARCISSISTIC_DECIMAL_NUMBER.AWK +BEGIN { + for (n=0;;n++) { + leng = length(n) + sum = 0 + for (i=1; i<=leng; i++) { + c = substr(n,i,1) + sum += c ^ leng + } + if (n == sum) { + printf("%d ",n) + if (++count == 25) { break } + } + } + exit(0) +} diff --git a/Task/Narcissistic-decimal-number/Ada/narcissistic-decimal-number.ada b/Task/Narcissistic-decimal-number/Ada/narcissistic-decimal-number.ada new file mode 100644 index 0000000000..686d7cef08 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Ada/narcissistic-decimal-number.ada @@ -0,0 +1,32 @@ +with Ada.Text_IO; + +procedure Narcissistic is + + function Is_Narcissistic(N: Natural) return Boolean is + Decimals: Natural := 1; + M: Natural := N; + Sum: Natural := 0; + begin + while M >= 10 loop + M := M / 10; + Decimals := Decimals + 1; + end loop; + M := N; + while M >= 1 loop + Sum := Sum + (M mod 10) ** Decimals; + M := M/10; + end loop; + return Sum=N; + end Is_Narcissistic; + + Count, Current: Natural := 0; + +begin + while Count < 25 loop + if Is_Narcissistic(Current) then + Ada.Text_IO.Put(Integer'Image(Current)); + Count := Count + 1; + end if; + Current := Current + 1; + end loop; +end Narcissistic; diff --git a/Task/Narcissistic-decimal-number/AutoHotkey/narcissistic-decimal-number.ahk b/Task/Narcissistic-decimal-number/AutoHotkey/narcissistic-decimal-number.ahk new file mode 100644 index 0000000000..06d6111292 --- /dev/null +++ b/Task/Narcissistic-decimal-number/AutoHotkey/narcissistic-decimal-number.ahk @@ -0,0 +1,42 @@ +#NoEnv ; Do not try to use environment variables +SetBatchLines, -1 ; Execute as quickly as you can + +StartCount := A_TickCount +Narc := Narc(25) +Elapsed := A_TickCount - StartCount + +MsgBox, Finished in %Elapsed%ms`n%Narc% +return + +Narc(m) +{ + Found := 0, Lower := 0 + Progress, B2 + Loop + { + Max := 10 ** Digits:=A_Index + Loop, 10 + Index := A_Index-1, Powers%Index% := Index**Digits + While Lower < Max + { + Sum := 0 + Loop, Parse, Lower + Sum += Powers%A_LoopField% + Loop, 10 + { + + if (Lower + (Index := A_Index-1) == Sum + Powers%Index%) + { + Out .= Lower+Index . (Mod(++Found,5) ? ", " : "`n") + Progress, % Found/M*100 + if (Found >= m) + { + Progress, Off + return Out + } + } + } + Lower += 10 + } + } +} diff --git a/Task/Narcissistic-decimal-number/C++/narcissistic-decimal-number.cpp b/Task/Narcissistic-decimal-number/C++/narcissistic-decimal-number.cpp new file mode 100644 index 0000000000..98b04244d7 --- /dev/null +++ b/Task/Narcissistic-decimal-number/C++/narcissistic-decimal-number.cpp @@ -0,0 +1,67 @@ +#include +#include +using namespace std; +typedef unsigned int uint; + +class NarcissisticDecs +{ +public: + void makeList( int mx ) + { + uint st = 0, tl; int pwr = 0, len; + while( narc.size() < mx ) + { + len = getDigs( st ); + if( pwr != len ) + { + pwr = len; + fillPower( pwr ); + } + tl = 0; + for( int i = 1; i < 10; i++ ) + tl += static_cast( powr[i] * digs[i] ); + + if( tl == st ) narc.push_back( st ); + st++; + } + } + + void display() + { + for( vector::iterator i = narc.begin(); i != narc.end(); i++ ) + cout << *i << " "; + cout << "\n\n"; + } + +private: + int getDigs( uint st ) + { + memset( digs, 0, 10 * sizeof( int ) ); + int r = 0; + while( st ) + { + digs[st % 10]++; + st /= 10; + r++; + } + return r; + } + + void fillPower( int z ) + { + for( int i = 1; i < 10; i++ ) + powr[i] = pow( static_cast( i ), z ); + } + + vector narc; + uint powr[10]; + int digs[10]; +}; + +int main( int argc, char* argv[] ) +{ + NarcissisticDecs n; + n.makeList( 25 ); + n.display(); + return system( "pause" ); +} diff --git a/Task/Narcissistic-decimal-number/C/narcissistic-decimal-number.c b/Task/Narcissistic-decimal-number/C/narcissistic-decimal-number.c new file mode 100644 index 0000000000..3b6028dbae --- /dev/null +++ b/Task/Narcissistic-decimal-number/C/narcissistic-decimal-number.c @@ -0,0 +1,63 @@ +#include +#include + +#define MAX_LEN 81 + +mpz_t power[10]; +mpz_t dsum[MAX_LEN + 1]; +int cnt[10], len; + +void check_perm(void) +{ + char s[MAX_LEN + 1]; + int i, c, out[10] = { 0 }; + + mpz_get_str(s, 10, dsum[0]); + for (i = 0; s[i]; i++) { + c = s[i]-'0'; + if (++out[c] > cnt[c]) return; + } + + if (i == len) + gmp_printf(" %Zd", dsum[0]); +} + +void narc_(int pos, int d) +{ + if (!pos) { + check_perm(); + return; + } + + do { + mpz_add(dsum[pos-1], dsum[pos], power[d]); + ++cnt[d]; + narc_(pos - 1, d); + --cnt[d]; + } while (d--); +} + +void narc(int n) +{ + int i; + len = n; + for (i = 0; i < 10; i++) + mpz_ui_pow_ui(power[i], i, n); + + mpz_init_set_ui(dsum[n], 0); + + printf("length %d:", n); + narc_(n, 9); + putchar('\n'); +} + +int main(void) +{ + int i; + + for (i = 0; i <= 10; i++) + mpz_init(power[i]); + for (i = 1; i <= MAX_LEN; i++) narc(i); + + return 0; +} diff --git a/Task/Narcissistic-decimal-number/Common-Lisp/narcissistic-decimal-number.lisp b/Task/Narcissistic-decimal-number/Common-Lisp/narcissistic-decimal-number.lisp new file mode 100644 index 0000000000..9f6d1b36ea --- /dev/null +++ b/Task/Narcissistic-decimal-number/Common-Lisp/narcissistic-decimal-number.lisp @@ -0,0 +1,14 @@ +(defun integer-to-list (n) + (map 'list #'digit-char-p (prin1-to-string n))) + +(defun narcissisticp (n) + (let* ((lst (integer-to-list n)) + (e (length lst))) + (= n + (reduce #'+ (mapcar (lambda (x) (expt x e)) lst))))) + +(defun start () + (loop for c from 0 + while (< narcissistic 25) + counting (narcissisticp c) into narcissistic + do (if (narcissisticp c) (print c)))) diff --git a/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-1.d b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-1.d new file mode 100644 index 0000000000..c79fb042fb --- /dev/null +++ b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-1.d @@ -0,0 +1,8 @@ +void main() { + import std.stdio, std.algorithm, std.conv, std.range; + + immutable isNarcissistic = (in uint n) pure @safe => + n.text.map!(d => (d - '0') ^^ n.text.length).sum == n; + writefln("%(%(%d %)\n%)", + uint.max.iota.filter!isNarcissistic.take(25).chunks(5)); +} diff --git a/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-2.d b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-2.d new file mode 100644 index 0000000000..162a9f2e41 --- /dev/null +++ b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-2.d @@ -0,0 +1,29 @@ +import std.stdio, std.algorithm, std.range, std.array; + +uint[] narcissists(in uint m) pure nothrow @safe { + typeof(return) result; + + foreach (immutable uint digits; 0 .. 10) { + const digitPowers = 10.iota.map!(i => i ^^ digits).array; + + foreach (immutable uint n; 10 ^^ (digits - 1) .. 10 ^^ digits) { + uint digitPSum, div = n; + while (div) { + digitPSum += digitPowers[div % 10]; + div /= 10; + } + + if (n == digitPSum) { + result ~= n; + if (result.length >= m) + return result; + } + } + } + + assert(0); +} + +void main() { + writefln("%(%(%d %)\n%)", 25.narcissists.chunks(5)); +} diff --git a/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-3.d b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-3.d new file mode 100644 index 0000000000..a0a61e9fb8 --- /dev/null +++ b/Task/Narcissistic-decimal-number/D/narcissistic-decimal-number-3.d @@ -0,0 +1,54 @@ +import std.stdio, std.bigint, std.conv; + +struct Narcissistics(TNum, uint maxLen) { + TNum[10] power; + TNum[maxLen + 1] dsum; + uint[10] count; + uint len; + + void checkPerm() const { + uint[10] mout; + + immutable s = dsum[0].text; + foreach (immutable d; s) { + immutable c = d - '0'; + if (++mout[c] > count[c]) + return; + } + + if (s.length == len) + writef(" %d", dsum[0]); + } + + void narc2(in uint pos, uint d) { + if (!pos) { + checkPerm; + return; + } + + do { + dsum[pos - 1] = dsum[pos] + power[d]; + count[d]++; + narc2(pos - 1, d); + count[d]--; + } while (d--); + } + + void show(in uint n) { + len = n; + foreach (immutable i, ref p; power) + p = TNum(i) ^^ n; + dsum[n] = 0; + writef("length %d:", n); + narc2(n, 9); + writeln; + } +} + +void main() { + enum maxLength = 16; + Narcissistics!(ulong, maxLength) narc; + //Narcissistics!(BigInt, maxLength) narc; // For larger numbers. + foreach (immutable i; 1 .. maxLength + 1) + narc.show(i); +} diff --git a/Task/Narcissistic-decimal-number/Go/narcissistic-decimal-number.go b/Task/Narcissistic-decimal-number/Go/narcissistic-decimal-number.go new file mode 100644 index 0000000000..03fd1a35a2 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Go/narcissistic-decimal-number.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +func narc(n int) []int { + power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + limit := 10 + result := make([]int, 0, n) + for x := 0; len(result) < n; x++ { + if x >= limit { + for i := range power { + power[i] *= i // i^m + } + limit *= 10 + } + sum := 0 + for xx := x; xx > 0; xx /= 10 { + sum += power[xx%10] + } + if sum == x { + result = append(result, x) + } + } + return result +} + +func main() { + fmt.Println(narc(25)) +} diff --git a/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs new file mode 100644 index 0000000000..f2cd096994 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs @@ -0,0 +1,15 @@ +import System.IO + +digits :: (Read a, Show a) => a -> [a] +digits n = map (read . (:[])) $ show n + +isNarcissistic :: (Show a, Read a, Num a, Eq a) => a -> Bool +isNarcissistic n = + let dig = digits n + len = length dig + in n == (sum $ map (^ len) $ dig) + +main :: IO () +main = do + hSetBuffering stdout NoBuffering + putStrLn $ unwords $ map show $ take 25 $ filter isNarcissistic [(0 :: Int)..] diff --git a/Task/Narcissistic-decimal-number/Icon/narcissistic-decimal-number.icon b/Task/Narcissistic-decimal-number/Icon/narcissistic-decimal-number.icon new file mode 100644 index 0000000000..3e99d188db --- /dev/null +++ b/Task/Narcissistic-decimal-number/Icon/narcissistic-decimal-number.icon @@ -0,0 +1,11 @@ +procedure main(A) + limit := integer(A[1]) | 25 + every write(isNarcissitic(seq(0))\limit) +end + +procedure isNarcissitic(n) + sn := string(n) + m := *sn + every (sum := 0) +:= (!sn)^m + return sum = n +end diff --git a/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-1.j b/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-1.j new file mode 100644 index 0000000000..062412dc03 --- /dev/null +++ b/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-1.j @@ -0,0 +1,2 @@ +getDigits=: "."0@": NB. get digits from number +isNarc=: (= +/@(] ^ #)@getDigits)"0 NB. test numbers for Narcissism diff --git a/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-2.j b/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-2.j new file mode 100644 index 0000000000..141a36031b --- /dev/null +++ b/Task/Narcissistic-decimal-number/J/narcissistic-decimal-number-2.j @@ -0,0 +1,2 @@ + (#~ isNarc) i.1e7 NB. display Narcissistic numbers +0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 diff --git a/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java b/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java new file mode 100644 index 0000000000..5eee1ac96f --- /dev/null +++ b/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java @@ -0,0 +1,23 @@ +public class Narc{ + public static boolean isNarc(long x){ + if(x < 0) return false; + + String xStr = Long.toString(x); + int m = xStr.length(); + long sum = 0; + + for(char c : xStr.toCharArray()){ + sum += Math.pow(Character.digit(c, 10), m); + } + return sum == x; + } + + public static void main(String[] args){ + for(long x = 0, count = 0; count < 25; x++){ + if(isNarc(x)){ + System.out.print(x + " "); + count++; + } + } + } +} diff --git a/Task/Narcissistic-decimal-number/MATLAB/narcissistic-decimal-number.m b/Task/Narcissistic-decimal-number/MATLAB/narcissistic-decimal-number.m new file mode 100644 index 0000000000..5a29772610 --- /dev/null +++ b/Task/Narcissistic-decimal-number/MATLAB/narcissistic-decimal-number.m @@ -0,0 +1,17 @@ +function testNarcissism + x = 0; + c = 0; + while c < 25 + if isNarcissistic(x) + fprintf('%d ', x) + c = c+1; + end + x = x+1; + end + fprintf('\n') +end + +function tf = isNarcissistic(n) + dig = sprintf('%d', n) - '0'; + tf = n == sum(dig.^length(dig)); +end diff --git a/Task/Narcissistic-decimal-number/Pascal/narcissistic-decimal-number.pascal b/Task/Narcissistic-decimal-number/Pascal/narcissistic-decimal-number.pascal new file mode 100644 index 0000000000..aa7ad9d720 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Pascal/narcissistic-decimal-number.pascal @@ -0,0 +1,81 @@ +program NdN; +//Narcissistic decimal number +const + Base = 10; + MaxDigits = 16; +type + tDigit = 0..Base-1; + tcntDgt= 0..MaxDigits-1; +var + powDgt : array[tDigit] of NativeUint; + PotdgtPos: array[tcntDgt] of NativeUint; + UpperSum : array[tcntDgt] of NativeUint; + + tmpSum, + tmpN, + actPot : NativeUint; + +procedure InitPowDig; +var + i,j : NativeUint; +Begin + j := 1; + For i := 0 to High(tDigit) do + Begin + powDgt[i] := i; + PotdgtPos[i] := j; + j := j*Base; + end; + actPot := 0; +end; + +procedure NextPowDig; +var + i,j : NativeUint; +Begin + // Next power of digit = i ^ actPot,always 0 = 0 , 1 = 1 + For i := 2 to High(tDigit) do + powDgt[i] := powDgt[i]*i; + // number of digits times 9 ^(max number of digits) + j := powDgt[High(tDigit)]; + For i := 0 to High(UpperSum) do + UpperSum[i] := (i+1)*j; + inc(actPot); +end; +procedure OutPutNdN(n:NativeUint); +Begin + write(n,' '); +end; + +procedure NextDgtSum(dgtPos,i,sumPowDgt,n:NativeUint); +begin + //unable to reach sum + IF (sumPowDgt+UpperSum[dgtPos]) < n then + EXIT; + repeat + tmpN := n+PotdgtPos[dgtPos]*i; + tmpSum := sumPowDgt+powDgt[i]; + //unable to get smaller + if tmpSum > tmpN then + EXIT; + IF tmpSum = tmpN then + OutPutNdN(tmpSum); + IF dgtPos>0 then + NextDgtSum(dgtPos-1,0,tmpSum,tmpN); + inc(i); + until i >= Base; +end; + +var + i : NativeUint; +Begin + InitPowDig; + For i := 1 to 9 do + Begin + write(' length ',actPot+1:2,': '); + //start with 1 in front, else you got i-times 0 in front + NextDgtSum(actPot,1,0,0); + writeln; + NextPowDig; + end; +end. diff --git a/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-1.pl6 b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-1.pl6 new file mode 100644 index 0000000000..06e8de8946 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-1.pl6 @@ -0,0 +1,8 @@ +sub is-narcissistic(Int $n) { $n == [+] $n.comb »**» $n.chars } + +for 0 .. * { + if .&is-narcissistic { + .say; + last if ++state$ >= 25; + } +} diff --git a/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 new file mode 100644 index 0000000000..74cbfda7f4 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 @@ -0,0 +1,20 @@ +sub kigits($n) { + my int $i = $n; + my int $b = 1000; + gather while $i { + take $i % $b; + $i = $i div $b; + } +} + +constant narcissistic = 0, (1..*).map: -> $d { + my @t = 0..9 X** $d; + my @table = @t X+ @t X+ @t; + sub is-narcissistic(\n) { n == [+] @table[kigits(n)] } + gather take $_ if is-narcissistic($_) for 10**($d-1) ..^ 10**$d; +} + +for narcissistic { + say ++state $n, "\t", $_; + last if $n == 25; +} diff --git a/Task/Narcissistic-decimal-number/Perl/narcissistic-decimal-number.pl b/Task/Narcissistic-decimal-number/Perl/narcissistic-decimal-number.pl new file mode 100644 index 0000000000..77c8c27f2f --- /dev/null +++ b/Task/Narcissistic-decimal-number/Perl/narcissistic-decimal-number.pl @@ -0,0 +1,11 @@ +sub is_narcissistic { + my $n = shift; + my($k,$sum) = (length($n),0); + $sum += $_**$k for split(//,$n); + $n == $sum; +} +my $i = 0; +for (1..25) { + $i++ while !is_narcissistic($i); + say $i++; +} diff --git a/Task/Narcissistic-decimal-number/PicoLisp/narcissistic-decimal-number.l b/Task/Narcissistic-decimal-number/PicoLisp/narcissistic-decimal-number.l new file mode 100644 index 0000000000..a0e84a3560 --- /dev/null +++ b/Task/Narcissistic-decimal-number/PicoLisp/narcissistic-decimal-number.l @@ -0,0 +1,13 @@ +(let (C 25 N 0 L 1) + (loop + (when + (= + N + (sum ** (mapcar format (chop N)) (need L L)) ) + (println N) + (dec 'C) ) + (inc 'N) + (setq L (length N)) + (T (=0 C) 'done) ) ) + +(bye) diff --git a/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-1.py b/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-1.py new file mode 100644 index 0000000000..235d720dbe --- /dev/null +++ b/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-1.py @@ -0,0 +1,18 @@ +from __future__ import print_function +from itertools import count, islice + +def narcissists(): + for digits in count(0): + digitpowers = [i**digits for i in range(10)] + for n in range(int(10**(digits-1)), 10**digits): + div, digitpsum = n, 0 + while div: + div, mod = divmod(div, 10) + digitpsum += digitpowers[mod] + if n == digitpsum: + yield n + +for i, n in enumerate(islice(narcissists(), 25), 1): + print(n, end=' ') + if i % 5 == 0: print() +print() diff --git a/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-2.py b/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-2.py new file mode 100644 index 0000000000..8f0cf19795 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-2.py @@ -0,0 +1,58 @@ +try: + import psyco + psyco.full() +except: + pass + +class Narcissistics: + def __init__(self, max_len): + self.max_len = max_len + self.power = [0] * 10 + self.dsum = [0] * (max_len + 1) + self.count = [0] * 10 + self.len = 0 + self.ord0 = ord('0') + + def check_perm(self, out = [0] * 10): + for i in xrange(10): + out[i] = 0 + + s = str(self.dsum[0]) + for d in s: + c = ord(d) - self.ord0 + out[c] += 1 + if out[c] > self.count[c]: + return + + if len(s) == self.len: + print self.dsum[0], + + def narc2(self, pos, d): + if not pos: + self.check_perm() + return + + while True: + self.dsum[pos - 1] = self.dsum[pos] + self.power[d] + self.count[d] += 1 + self.narc2(pos - 1, d) + self.count[d] -= 1 + if d == 0: + break + d -= 1 + + def show(self, n): + self.len = n + for i in xrange(len(self.power)): + self.power[i] = i ** n + self.dsum[n] = 0 + print "length %d:" % n, + self.narc2(n, 9) + print + +def main(): + narc = Narcissistics(14) + for i in xrange(1, narc.max_len + 1): + narc.show(i) + +main() diff --git a/Task/Narcissistic-decimal-number/README b/Task/Narcissistic-decimal-number/README new file mode 100644 index 0000000000..22dfd5df05 --- /dev/null +++ b/Task/Narcissistic-decimal-number/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Narcissistic_decimal_number diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx new file mode 100644 index 0000000000..acd1771aac --- /dev/null +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx @@ -0,0 +1,15 @@ +/*REXX program to generate and display a number of narcissistic numbers.*/ +numeric digits 39 /*be able to handle the largest #*/ +parse arg N .; if N=='' then N=25 /*get number of narcissistic #'s.*/ +N=min(N,89) /*there are 89 narcissistic #s.*/ +#=0 /*number of narcissistic # so far*/ + do j=0 until #==N; L=length(j) /*get the length of the J number.*/ + s=left(j,1)**L /*1st digit in J raised to L pow.*/ + do k=2 for L-1 until s>j /*perform for each digit in J. */ + s=s + substr(j,k,1)**L /*add digit raised to pow to sum.*/ + end /*k*/ /* [↑] calculate the rest of sum*/ + if s\==j then iterate /*does sum equal to J? No ··· */ + #=#+1 /*bump the narcissistic num count*/ + say right(#,9) ' narcissistic:' j /*display index & narcissistic #.*/ + end /*j*/ /* [↑] this list starts at 0. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx new file mode 100644 index 0000000000..235a315ab5 --- /dev/null +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx @@ -0,0 +1,20 @@ +/*REXX program to generate and display a number of narcissistic numbers.*/ +numeric digits 39 /*be able to handle the largest #*/ +parse arg N .; if N=='' then N=25 /*get number of narcissistic #'s.*/ +N=min(N,89) /*there are 89 narcissistic #s.*/ + do w=1 for 39 /*generate tables: digits ^ L pow*/ + do i=0 for 10; @.w.i=i**w; end /*build table of 10 digs ^ L pow.*/ + end /*w*/ /* [↑] table is of a fixed size.*/ +#=0 /*number of narcissistic # so far*/ + do j=0 until #==N; L=length(j) /*get the length of the J number.*/ + _=left(j,1) /*select the first digit to sum. */ + s=@.L._ /*sum of the J digs ^ L (so far)*/ + do k=2 for L-1 until s>j /*perform for each digit in J. */ + _=substr(j,k,1) /*select the next digit to sum. */ + s=s+@.L._ /*add digit raised to pow to sum.*/ + end /*k*/ /* [↑] calculate the rest of sum*/ + if s\==j then iterate /*does sum equal to J? No ··· */ + #=#+1 /*bump the narcissistic num count*/ + say right(#,9) ' narcissistic:' j /*display index & narcissistic #.*/ + end /*j*/ /* [↑] this list starts at 0. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx new file mode 100644 index 0000000000..eb7faccb0c --- /dev/null +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx @@ -0,0 +1,27 @@ +/*REXX program to generate and display a number of narcissistic numbers.*/ +numeric digits 39 /*be able to handle the largest #*/ +parse arg N .; if N=='' then N=25 /*get number of narcissistic #'s.*/ +N=min(N,89) /*there are 89 narcissistic #s.*/ + do w=1 for 39 /*generate tables: digits ^ L pow*/ + do i=0 for 10; @.w.i=i**w; end /*build table of 10 digs ^ L pow.*/ + end /*w*/ /* [↑] table is of a fixed size.*/ +#=0 /*number of narcissistic # so far*/ + do low=0 for 10; call tell low; end /*handle the first one-digit nums*/ + /* [↓] skip the 2-digit numbers.*/ + do j=100; L=length(j) /*get the length of the J number.*/ + _1=left(j,1); _2=substr(j,2,1) /*select 1st & 2nd digit to sum. */ + _R=right(j,1) /*select the right digit to sum. */ + s=@.L._1 + @.L._2 + @.L._R /*sum of the J digs ^ L (so far)*/ + do k=3 for L-3 until s>j /*perform for each digit in J. */ + _=substr(j,k,1) /*select the next digit to sum. */ + s=s + @.L._ /*add digit raised to pow to sum.*/ + end /*k*/ /* [↑] calculate the rest of sum*/ + if s==j then call tell j /*does sum equal to J? Yes ···*/ + end /*j*/ /* [↑] this list starts at 0. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: parse arg y /*get narcissistic # to display. */ +#=#+1 /*bump the narcissistic # count. */ +say right(#,9) ' narcissistic:' y /*display index & narcissistic #.*/ +if #==N then exit /*stick a fork in it, we're done.*/ +return /*return and keep on truckin'. */ diff --git a/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-1.rkt b/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-1.rkt new file mode 100644 index 0000000000..6ba1a79f37 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-1.rkt @@ -0,0 +1,64 @@ +;; OEIS: A005188 defines these as positive numbers, so I will follow that definition in the function +;; definitions. +;; +;; 0: assuming it is represented as the single digit 0 (and not an empty string, which is not the +;; usual convention for 0 in decimal), is not: sum(0^0), which is 1. 0^0 is a strange one, +;; wolfram alpha calls returns 0^0 as indeterminate -- so I will defer to the brains behind OEIS +;; on the definition here, rather than copy what I'm seeing in some of the results here +#lang racket + +;; Included for the serious efficientcy gains we get from fxvectors vs. general vectors. +;; +;; We also use fx+/fx- etc. As it stands, they do a check for fixnumness, for safety. +;; We can link them in as "unsafe" operations (see the documentation on racket/fixnum); +;; but we get a result from this program quickly enough for my tastes. +(require racket/fixnum) + +; uses a precalculated (fx)vector of powers -- caller provided, please. +(define (sub-narcissitic? N powered-digits) + (let loop ((n N) (target N)) + (cond + [(fx> 0 target) #f] + [(fx= 0 target) (fx= 0 n)] + [(fx= 0 n) #f] + [else (loop (fxquotient n 10) + (fx- target (fxvector-ref powered-digits (fxremainder n 10))))]))) + +; Can be used as standalone, since it doesn't require caller to care about things like order of +; magnitude etc. However, it *is* slow, since it regenerates the powered-digits vector every time. +(define (narcissitic? n) ; n is +ve + (define oom+1 (fx+ 1 (order-of-magnitude n))) + (define powered-digits (for/fxvector ((i 10)) (expt i oom+1))) + (sub-narcissitic? n powered-digits)) + +;; next m primes > z +(define (next-narcissitics z m) ; naming convention following math/number-theory's next-primes + (let-values + ([(i l) + (for*/fold ((i (fx+ 1 z)) (l empty)) + ((oom (in-naturals)) + (dgts^oom (in-value (for/fxvector ((i 10)) (expt i (add1 oom))))) + (n (in-range (expt 10 oom) (expt 10 (add1 oom)))) + #:when (sub-narcissitic? n dgts^oom) + ; everyone else uses ^C to break... + ; that's a bit of a manual process, don't you think? + #:final (= (fx+ 1 (length l)) m)) + (values (+ i 1) (append l (list n))))]) + l)) ; we only want the list + +(module+ main + (next-narcissitics 0 25) + ; here's another list... depending on whether you believe sloane or wolfram :-) + (cons 0 (next-narcissitics 0 25))) + +(module+ test + (require rackunit) + ; example given at head of task + (check-true (narcissitic? 153)) + ; rip off the first 12 (and 0, since Armstrong numbers seem to be postivie) from + ; http://oeis.org/A005188 for testing + (check-equal? + (for/list ((i (in-range 12)) + (n (sequence-filter narcissitic? (in-naturals 1)))) n) + '(1 2 3 4 5 6 7 8 9 153 370 371)) + (check-equal? (next-narcissitics 0 12) '(1 2 3 4 5 6 7 8 9 153 370 371))) diff --git a/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-2.rkt b/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-2.rkt new file mode 100644 index 0000000000..f174a18d1a --- /dev/null +++ b/Task/Narcissistic-decimal-number/Racket/narcissistic-decimal-number-2.rkt @@ -0,0 +1,59 @@ +#lang racket +(define (non-decrementing-digital-sequences L) + (define (inr d l) + (cond + [(<= l 0) '(())] + [(= d 9) (list (make-list l d))] + [else (append (map (curry cons d) (inr d (- l 1))) (inr (+ d 1) l))])) + (inr 0 L)) + +(define (integer->digits-list n) + (let inr ((n n) (l null)) (if (zero? n) l (inr (quotient n 10) (cons (modulo n 10) l))))) + +(define (narcissitic-numbers-of-length L) + (define tail-digits (non-decrementing-digital-sequences (sub1 L))) + (define powers-v (for/fxvector #:length 10 ((i 10)) (expt i L))) + (define (powers-sum dgts) (for/sum ((d (in-list dgts))) (fxvector-ref powers-v d))) + (for*/list + ((dgt1 (in-range 1 10)) + (dgt... (in-list tail-digits)) + (sum-dgt^l (in-value (powers-sum (cons dgt1 dgt...)))) + (dgts-sum (in-value (integer->digits-list sum-dgt^l))) + #:when (= (car dgts-sum) dgt1) + ; only now is it worth sorting the digits + #:when (equal? (sort (cdr dgts-sum) <) dgt...)) + sum-dgt^l)) + +(define (narcissitic-numbers-of-length<= L) + (cons 0 ; special! + (apply append (for/list ((l (in-range 1 (+ L 1)))) (narcissitic-numbers-of-length l))))) + +(module+ main + (define all-narcissitics<10000000 + (narcissitic-numbers-of-length<= 7)) + ; conveniently, this *is* the list of 25... but I'll be a bit pedantic anyway + (take all-narcissitics<10000000 25)) + +(module+ test + (require rackunit) + (check-equal? (non-decrementing-digital-sequences 1) '((0) (1) (2) (3) (4) (5) (6) (7) (8) (9))) + (check-equal? + (non-decrementing-digital-sequences 2) + '((0 0) (0 1) (0 2) (0 3) (0 4) (0 5) (0 6) (0 7) (0 8) (0 9) + (1 1) (1 2) (1 3) (1 4) (1 5) (1 6) (1 7) (1 8) (1 9) + (2 2) (2 3) (2 4) (2 5) (2 6) (2 7) (2 8) (2 9) + (3 3) (3 4) (3 5) (3 6) (3 7) (3 8) (3 9) + (4 4) (4 5) (4 6) (4 7) (4 8) (4 9) + (5 5) (5 6) (5 7) (5 8) (5 9) (6 6) (6 7) (6 8) (6 9) + (7 7) (7 8) (7 9) (8 8) (8 9) (9 9))) + + (check-equal? (integer->digits-list 0) null) + (check-equal? (integer->digits-list 7) '(7)) + (check-equal? (integer->digits-list 10) '(1 0)) + + (check-equal? (narcissitic-numbers-of-length 1) '(1 2 3 4 5 6 7 8 9)) + (check-equal? (narcissitic-numbers-of-length 2) '()) + (check-equal? (narcissitic-numbers-of-length 3) '(153 370 371 407)) + + (check-equal? (narcissitic-numbers-of-length<= 1) '(0 1 2 3 4 5 6 7 8 9)) + (check-equal? (narcissitic-numbers-of-length<= 3) '(0 1 2 3 4 5 6 7 8 9 153 370 371 407))) diff --git a/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb b/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb new file mode 100644 index 0000000000..69d2194522 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb @@ -0,0 +1,28 @@ +class Integer + def narcissistic? + return false if self < 0 + len = to_s.size + n = self + sum = 0 + while n > 0 + n, r = n.divmod(10) + sum += r ** len + end + sum == self + end +end + +numbers = [] +n = 0 +while numbers.size < 25 + numbers << n if n.narcissistic? + n += 1 +end + +# or +# numbers = 0.step.lazy.select(&:narcissistic?).first(25) # Ruby ver 2.1 + +max = numbers.max.to_s.size +g = numbers.group_by{|n| n.to_s.size} +g.default = [] +(1..max).each{|n| puts "length #{n} : #{g[n].join(", ")}"} diff --git a/Task/Narcissistic-decimal-number/Scala/narcissistic-decimal-number.scala b/Task/Narcissistic-decimal-number/Scala/narcissistic-decimal-number.scala new file mode 100644 index 0000000000..b8e84bf057 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Scala/narcissistic-decimal-number.scala @@ -0,0 +1,8 @@ +object NDN extends App { + + val narc: Int => Int = n => (n.toString map (_.asDigit) map (math.pow(_, n.toString.size)) sum) toInt + val isNarc: Int => Boolean = i => i == narc(i) + + println((Iterator from 0 filter isNarc take 25 toList) mkString(" ")) + +} diff --git a/Task/Narcissistic-decimal-number/Tcl/narcissistic-decimal-number.tcl b/Task/Narcissistic-decimal-number/Tcl/narcissistic-decimal-number.tcl new file mode 100644 index 0000000000..f381648a2c --- /dev/null +++ b/Task/Narcissistic-decimal-number/Tcl/narcissistic-decimal-number.tcl @@ -0,0 +1,19 @@ +proc isNarcissistic {n} { + set m [string length $n] + for {set t 0; set N $n} {$N} {set N [expr {$N / 10}]} { + incr t [expr {($N%10) ** $m}] + } + return [expr {$n == $t}] +} + +proc firstNarcissists {target} { + for {set n 0; set count 0} {$count < $target} {incr n} { + if {[isNarcissistic $n]} { + incr count + lappend narcissists $n + } + } + return $narcissists +} + +puts [join [firstNarcissists 25] ","] diff --git a/Task/Narcissistic-decimal-number/UNIX-Shell/narcissistic-decimal-number.sh b/Task/Narcissistic-decimal-number/UNIX-Shell/narcissistic-decimal-number.sh new file mode 100644 index 0000000000..d54164b2ba --- /dev/null +++ b/Task/Narcissistic-decimal-number/UNIX-Shell/narcissistic-decimal-number.sh @@ -0,0 +1,14 @@ +function narcissistic { + integer n=$1 len=${#n} sum=0 i + for ((i=0; i +# Ignoring leading spaces +Text strings: +['ignore leading spaces: 2-2', ' ignore leading spaces: 2-1', ' ignore leading spaces: 2+0', ' ignore leading spaces: 2+1'] + +# Ignoring multiple adjacent spaces (m.a.s) +Text strings: +['ignore m.a.s spaces: 2-2', 'ignore m.a.s spaces: 2-1', 'ignore m.a.s spaces: 2+0', 'ignore m.a.s spaces: 2+1'] + + +# Equivalent whitespace characters +Text strings: +['Equiv. spaces: 3-3', 'Equiv.\rspaces: 3-2', 'Equiv.\x0cspaces: 3-1', 'Equiv.\x0bspaces: 3+0', 'Equiv.\nspaces: 3+1', 'Equiv.\tspaces: 3+2'] + +# Case Indepenent sort +Text strings: +['cASE INDEPENENT: 3-2', 'caSE INDEPENENT: 3-1', 'casE INDEPENENT: 3+0', 'case INDEPENENT: 3+1'] + +# Numeric fields as numerics +Text strings: +['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] + +# Title sorts +Text strings: +['The Wind in the Willows', 'The 40th step more', 'The 39 steps', 'Wanda'] + +# Equivalent accented characters (and case) +Text strings: +[u'Equiv. \xfd accents: 2-2', u'Equiv. \xdd accents: 2-1', u'Equiv. y accents: 2+0', u'Equiv. Y accents: 2+1'] + + +# Separated ligatures +Text strings: +[u'\u0132 ligatured ij', 'no ligature'] + +# Character replacements +Text strings: +[u'Start with an \u0292: 2-2', u'Start with an \u017f: 2-1', u'Start with an \xdf: 2+0', u'Start with an s: 2+1'] diff --git a/Task/Natural-sorting/C/natural-sorting-1.c b/Task/Natural-sorting/C/natural-sorting-1.c new file mode 100644 index 0000000000..64733cb2f9 --- /dev/null +++ b/Task/Natural-sorting/C/natural-sorting-1.c @@ -0,0 +1,257 @@ +#include +#include +#include +#include +#include +#include + +typedef struct wstr { + wchar_t *s; + int n, alloc; +} wstr; + +#define w_del(w) { free(w->s); free(w); } +#define forchars(i, c, w) for(i = 0, c = w->s[0]; i < w->n && c; c = w->s[++i]) +wstr *w_new() +{ + wstr *w = malloc(sizeof(wstr)); + w->alloc = 1; + w->n = 0; + w->s = malloc(sizeof(wchar_t)); + w->s[0] = 0; + return w; +} + +void w_append(wstr *w, wchar_t c) +{ + int n = w->n + 1; + if (n >= w->alloc) { + w->alloc *= 2; + w->s = realloc(w->s, w->alloc * sizeof(wchar_t)); + } + w->s[w->n++] = c; + w->s[w->n] = 0; +} + +wstr *w_make(wchar_t *s) +{ + int i, len = wcslen(s); + wstr *w = w_new(); + for (i = 0; i < len; i++) w_append(w, s[i]); + return w; +} + +typedef void (*wtrans_func)(wstr *, wstr *); +void w_transform(wstr *in, wtrans_func f) +{ + wstr t, *out = w_new(); + f(in, out); + t = *in; *in = *out; *out = t; + w_del(out); +} +#define transfunc(x) void w_##x(wstr *in, wstr *out) + +transfunc(nocase) { + int i; + wchar_t c; + forchars(i, c, in) w_append(out, towlower(c)); +} + +transfunc(despace) { + int i, gotspace = 0; + wchar_t c; + forchars(i, c, in) { + if (!iswspace(c)) { + if (gotspace && out->n) + w_append(out, L' '); + w_append(out, c); + gotspace = 0; + } else gotspace = 1; + } +} + +static const wchar_t *const tbl_accent[] = { /* copied from Perl6 code */ + L"Þ", L"TH", L"þ", L"th", L"Ð", L"TH", L"ð", L"th", L"À", L"A", + L"Á", L"A", L"Â", L"A", L"Ã", L"A", L"Ä", L"A", L"Å", L"A", L"à", + L"a", L"á", L"a", L"â", L"a", L"ã", L"a", L"ä", L"a", L"å", L"a", + L"Ç", L"C", L"ç", L"c", L"È", L"E", L"É", L"E", L"Ê", L"E", L"Ë", + L"E", L"è", L"e", L"é", L"e", L"ê", L"e", L"ë", L"e", L"Ì", + L"I", L"Í", L"I", L"Î", L"I", L"Ï", L"I", L"ì", L"i", L"í", + L"i", L"î", L"i", L"ï", L"i", L"Ò", L"O", L"Ó", L"O", L"Ô", + L"O", L"Õ", L"O", L"Ö", L"O", L"Ø", L"O", L"ò", L"o", L"ó", L"o", + L"ô", L"o", L"õ", L"o", L"ö", L"o", L"ø", L"o", L"Ñ", L"N", L"ñ", L"n", + L"Ù", L"U", L"Ú", L"U", L"Û", L"U", L"Ü", L"U", L"ù", L"u", L"ú", L"u", + L"û", L"u", L"ü", L"u", L"Ý", L"Y", L"ÿ", L"y", L"ý", L"y" }; + +static const wchar_t *const tbl_ligature[] = { + L"Æ", L"AE", L"æ", L"ae", L"ß", L"ss", + L"ffl", L"ffl", L"ffi", L"ffi", L"fi", L"fi", L"ff", L"ff", L"fl", L"fl", + L"ſ", L"s", L"ʒ", L"z", L"st", L"st", /* ... come on ... */ +}; + +void w_char_repl(wstr *in, wstr *out, const wchar_t *const *tbl, int len) +{ + int i, j, k; + wchar_t c; + forchars(i, c, in) { + for (j = k = 0; j < len; j += 2) { + if (c != tbl[j][0]) continue; + for (k = 0; tbl[j + 1][k]; k++) + w_append(out, tbl[j + 1][k]); + break; + } + if (!k) w_append(out, c); + } +} + +transfunc(noaccent) { + w_char_repl(in, out, tbl_accent, sizeof(tbl_accent)/sizeof(wchar_t*)); +} + +transfunc(noligature) { + w_char_repl(in, out, tbl_ligature, sizeof(tbl_ligature)/sizeof(wchar_t*)); +} + +static const wchar_t *const tbl_article[] = { + L"the", L"a", L"of", L"to", L"is", L"it" }; +#define N_ARTICLES sizeof(tbl_article)/sizeof(tbl_article[0]) +transfunc(noarticle) { + int i, j, n; + wchar_t c, c0 = 0; + forchars(i, c, in) { + if (!c0 || (iswalnum(c) && !iswalnum(c0))) { /* word boundary */ + for (j = N_ARTICLES - 1; j >= 0; j--) { + n = wcslen(tbl_article[j]); + if (wcsncasecmp(in->s + i, tbl_article[j], n)) + continue; + if (iswalnum(in->s[i + n])) continue; + i += n; + break; + } + if (j < 0) w_append(out, c); + } else + w_append(out, c); + c0 = c; + } +} + +enum { wi_space = 0, wi_case, wi_accent, wi_lig, wi_article, wi_numeric }; +#define WS_NOSPACE (1 << wi_space) +#define WS_NOCASE (1 << wi_case) +#define WS_ACCENT (1 << wi_accent) +#define WS_LIGATURE (1 << wi_lig) +#define WS_NOARTICLE (1 << wi_article) +#define WS_NUMERIC (1 << wi_numeric) +const wtrans_func trans_funcs[] = { + w_despace, w_nocase, w_noaccent, w_noligature, w_noarticle, 0 +}; +const char *const flagnames[] = { + "collapse spaces", + "case insensitive", + "disregard accent", + "decompose ligatures", + "discard common words", + "numeric", +}; + +typedef struct { wchar_t* s; wstr *w; } kw_t; +int w_numcmp(const void *a, const void *b) +{ + wchar_t *pa = ((const kw_t*)a)->w->s, *pb = ((const kw_t*)b)->w->s; + int sa, sb, ea, eb; + while (*pa && *pb) { + if (iswdigit(*pa) && iswdigit(*pb)) { + /* skip leading zeros */ + sa = sb = 0; + while (pa[sa] == L'0') sa++; + while (pb[sb] == L'0') sb++; + /* find end of numbers */ + ea = sa; eb = sb; + while (iswdigit(pa[ea])) ea++; + while (iswdigit(pb[eb])) eb++; + if (eb - sb > ea - sa) return -1; + if (eb - sb < ea - sa) return 1; + while (sb < eb) { + if (pa[sa] > pb[sb]) return 1; + if (pa[sa] < pb[sb]) return -1; + sa++; sb++; + } + + pa += ea; pb += eb; + } + else if (iswdigit(*pa)) return 1; + else if (iswdigit(*pb)) return -1; + else { + if (*pa > *pb) return 1; + if (*pa < *pb) return -1; + pa++; pb++; + } + } + return (!*pa && !*pb) ? 0 : *pa ? 1 : -1; +} + +int w_cmp(const void *a, const void *b) +{ + return wcscmp(((const kw_t*)a)->w->s, ((const kw_t*)b)->w->s); +} + +void natural_sort(wchar_t **strings, int len, int flags) +{ + int i, j; + kw_t *kws = malloc(sizeof(kw_t) * len); + + for (i = 0; i < len; i++) { + kws[i].s = strings[i]; + kws[i].w = w_make(strings[i]); + for (j = 0; j < wi_numeric; j++) + if (flags & (1 << j) && trans_funcs[j]) + w_transform(kws[i].w, trans_funcs[j]); + } + + qsort(kws, len, sizeof(kw_t), (flags & WS_NUMERIC) ? w_numcmp : w_cmp); + for (i = 0; i < len; i++) { + w_del(kws[i].w); + strings[i] = kws[i].s; + } + free(kws); +} + +const wchar_t *const test[] = { + L" 0000098 nina", L"100 niño", L"99 Ninja", L"100 NINA", + L" The work is so difficult to do it took ſome 100 aeons. ", + L"The work is so difficult it took some 100 aeons.", + L" The work is so difficult it took ſome 99 æons. ", +}; +#define N_STRINGS sizeof(test)/sizeof(*test) + +void test_sort(int flags) +{ + int i, j; + const wchar_t *str[N_STRINGS]; + memcpy(str, test, sizeof(test)); + + printf("Sort flags: ("); + for (i = 0, j = flags; j; i++, j >>= 1) + if ((j & 1)) + printf("%s%s", flagnames[i], j > 1 ? ", ":")\n"); + + natural_sort((wchar_t **)str, N_STRINGS, flags); + + for (i = 0; i < N_STRINGS; i++) + printf("%ls\n", str[i]); + printf("\n"); +} + +int main() +{ + setlocale(LC_CTYPE, ""); + + test_sort(WS_NOSPACE); + test_sort(WS_NOCASE); + test_sort(WS_NUMERIC); + test_sort(WS_NOARTICLE|WS_NOSPACE); + test_sort(WS_NOCASE|WS_NOSPACE|WS_ACCENT); + test_sort(WS_LIGATURE|WS_NOCASE|WS_NOSPACE|WS_NUMERIC|WS_ACCENT|WS_NOARTICLE); + + return 0; +} diff --git a/Task/Natural-sorting/C/natural-sorting-2.c b/Task/Natural-sorting/C/natural-sorting-2.c new file mode 100644 index 0000000000..e1d0532a64 --- /dev/null +++ b/Task/Natural-sorting/C/natural-sorting-2.c @@ -0,0 +1,53 @@ +Sort flags: (collapse spaces) + 0000098 nina +100 NINA +100 niño +99 Ninja +The work is so difficult it took some 100 aeons. + The work is so difficult it took ſome 99 æons. + The work is so difficult to do it took ſome 100 aeons. + +Sort flags: (case insensitive) + The work is so difficult it took ſome 99 æons. + 0000098 nina + The work is so difficult to do it took ſome 100 aeons. +100 NINA +100 niño +99 Ninja +The work is so difficult it took some 100 aeons. + +Sort flags: (numeric) + The work is so difficult it took ſome 99 æons. + The work is so difficult to do it took ſome 100 aeons. + 0000098 nina +The work is so difficult it took some 100 aeons. +99 Ninja +100 NINA +100 niño + +Sort flags: (collapse spaces, discard common words) + 0000098 nina +100 NINA +100 niño +99 Ninja +The work is so difficult it took some 100 aeons. + The work is so difficult to do it took ſome 100 aeons. + The work is so difficult it took ſome 99 æons. + +Sort flags: (collapse spaces, case insensitive, disregard accent) + 0000098 nina +100 NINA +100 niño +99 Ninja +The work is so difficult it took some 100 aeons. + The work is so difficult it took ſome 99 æons. + The work is so difficult to do it took ſome 100 aeons. + +Sort flags: (collapse spaces, case insensitive, disregard accent, decompose ligatures, discard common words, numeric) + The work is so difficult to do it took ſome 100 aeons. + The work is so difficult it took ſome 99 æons. +The work is so difficult it took some 100 aeons. + 0000098 nina +99 Ninja +100 NINA +100 niño diff --git a/Task/Natural-sorting/D/natural-sorting.d b/Task/Natural-sorting/D/natural-sorting.d new file mode 100644 index 0000000000..57853de7f6 --- /dev/null +++ b/Task/Natural-sorting/D/natural-sorting.d @@ -0,0 +1,58 @@ +import std.stdio, std.string, std.algorithm, std.array, std.conv, + std.ascii, std.range; + +string[] naturalSort(string[] arr) /*pure @safe*/ { + static struct Part { + string s; + + int opCmp(in ref Part other) const pure { + return (s[0].isDigit && other.s[0].isDigit) ? + cmp([s.to!ulong], [other.s.to!ulong]) : + cmp(s, other.s); + } + } + + static mapper(in string txt) /*pure nothrow @safe*/ { + auto r = txt + .strip + .tr(whitespace, " ", "s") + .toLower + .groupBy!isDigit + .map!(p => Part(p.text)) + .array; + return (r.length > 1 && r[0].s == "the") ? r.dropOne : r; + } + + return arr.schwartzSort!mapper.release; +} + +void main() /*@safe*/ { + auto tests = [ + // Ignoring leading spaces. + ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " + ignore leading spaces: 2+1", " ignore leading spaces: 2+0"], + + // Ignoring multiple adjacent spaces (m.a.s). + ["ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"], + + // Equivalent whitespace characters. + ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", + "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", + "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"], + + // Case Indepenent sort. + ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", + "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"], + + // Numeric fields as numerics. + ["foo100bar99baz0.txt", "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"], + + // Title sorts. + ["The Wind in the Willows", "The 40th step more", + "The 39 steps", "Wanda"]]; + + foreach (test; tests) + writeln(test, "\n", test.naturalSort, "\n"); +} diff --git a/Task/Natural-sorting/Go/natural-sorting.go b/Task/Natural-sorting/Go/natural-sorting.go new file mode 100644 index 0000000000..c15d49c5f5 --- /dev/null +++ b/Task/Natural-sorting/Go/natural-sorting.go @@ -0,0 +1,134 @@ +package main + +import ( + "fmt" + "regexp" + "sort" + "strconv" + "strings" +) + +var tests = []struct { + descr string + list []string +}{ + {"Ignoring leading spaces", []string{ + "ignore leading spaces: 2-2", + " ignore leading spaces: 2-1", + " ignore leading spaces: 2+0", + " ignore leading spaces: 2+1", + }}, + {"Ignoring multiple adjacent spaces", []string{ + "ignore m.a.s spaces: 2-2", + "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", + "ignore m.a.s spaces: 2+1", + }}, + {"Equivalent whitespace characters", []string{ + "Equiv. spaces: 3-3", + "Equiv.\rspaces: 3-2", + "Equiv.\fspaces: 3-1", + "Equiv.\bspaces: 3+0", + "Equiv.\nspaces: 3+1", + "Equiv.\tspaces: 3+2", + }}, + {"Case Indepenent sort", []string{ + "cASE INDEPENENT: 3-2", + "caSE INDEPENENT: 3-1", + "casE INDEPENENT: 3+0", + "case INDEPENENT: 3+1", + }}, + {"Numeric fields as numerics", []string{ + "foo100bar99baz0.txt", + "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", + "foo1000bar99baz9.txt", + }}, +} + +func main() { + for _, test := range tests { + fmt.Println(test.descr) + fmt.Println("Input order:") + for _, s := range test.list { + fmt.Printf(" %q\n", s) + } + fmt.Println("Natural order:") + l := make(list, len(test.list)) + for i, s := range test.list { + l[i] = newNatStr(s) + } + sort.Sort(l) + for _, s := range l { + fmt.Printf(" %q\n", s.s) + } + fmt.Println() + } +} + +// natStr associates a string with a preprocessed form +type natStr struct { + s string // original + t []tok // preprocessed "sub-fields" +} + +func newNatStr(s string) (t natStr) { + t.s = s + s = strings.ToLower(strings.Join(strings.Fields(s), " ")) + x := dx.FindAllString(s, -1) + t.t = make([]tok, len(x)) + for i, s := range x { + if n, err := strconv.Atoi(s); err == nil { + t.t[i].n = n + } else { + t.t[i].s = s + } + } + return t +} + +var dx = regexp.MustCompile(`\d+|\D+`) + +// rule is to use s unless it is empty, then use n +type tok struct { + s string + n int +} + +// rule 2 of "numeric sub-fields" from talk page +func (f1 tok) Cmp(f2 tok) int { + switch { + case f1.s == "": + switch { + case f2.s > "" || f1.n < f2.n: + return -1 + case f1.n > f2.n: + return 1 + } + case f2.s == "" || f1.s > f2.s: + return 1 + case f1.s < f2.s: + return -1 + } + return 0 +} + +type list []natStr + +func (l list) Len() int { return len(l) } +func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l list) Less(i, j int) bool { + ti := l[i].t + for k, t := range l[j].t { + if k == len(ti) { + return true + } + switch ti[k].Cmp(t) { + case -1: + return true + case 1: + return false + } + } + return false +} diff --git a/Task/Natural-sorting/J/natural-sorting-1.j b/Task/Natural-sorting/J/natural-sorting-1.j new file mode 100644 index 0000000000..651f9fdf52 --- /dev/null +++ b/Task/Natural-sorting/J/natural-sorting-1.j @@ -0,0 +1,10 @@ +require'strings regex' + +lines=: <;.2 +titleFix=: ('^\s*(the|a|an)\b';'')&rxrplc +isNum=: e.&'0123456789' +num=: ".^:(isNum@{.) +split=: <@num/.~ [:+/\1,2 ~:/\ isNum +norm=: [: split (32 9 12 13 14 15{a.) -.~ [: titleFix tolower + +natSor=: lines ;@/: norm&.>@lines diff --git a/Task/Natural-sorting/J/natural-sorting-2.j b/Task/Natural-sorting/J/natural-sorting-2.j new file mode 100644 index 0000000000..e8f6567009 --- /dev/null +++ b/Task/Natural-sorting/J/natural-sorting-2.j @@ -0,0 +1,45 @@ +IgnoringLeadingSpaces=:0 :0 +ignore leading spaces: 2-2 + ignore leading spaces: 2-1 + ignore leading spaces: 2+0 + ignore leading spaces: 2+1 +) + +IgnoringMultipleAdjacentSpaces=: 0 :0 + ignore m.a.s spaces: 2-2 + ignore m.a.s spaces: 2-1 + ignore m.a.s spaces: 2+0 + ignore m.a.s spaces: 2+1 +) + +bsSubst=: rplc&((LF;'\'),('\r';13{a.),('\x0c';12{a.),('\x0b';11{a.),('\n';LF),:'\t';TAB) + +EquivalentWhitespaceCharacters=: bsSubst 0 :0 + Equiv. spaces: 3-3 + Equiv.\rspaces: 3-2 + Equiv.\x0cspaces: 3-1 + Equiv.\x0bspaces: 3+0 + Equiv.\nspaces: 3+1 + Equiv.\tspaces: 3+2 +) + +CaseIndepenent=: 0 :0 + cASE INDEPENENT: 3-2 + caSE INDEPENENT: 3-1 + casE INDEPENENT: 3+0 + case INDEPENENT: 3+1 +) + +NumericFieldsAsNumerics=: 0 :0 + foo100bar99baz0.txt + foo100bar10baz0.txt + foo1000bar99baz10.txt + foo1000bar99baz9.txt +) + +Titles=: 0 :0 + The Wind in the Willows + The 40th step more + The 39 steps + Wanda +) diff --git a/Task/Natural-sorting/J/natural-sorting-3.j b/Task/Natural-sorting/J/natural-sorting-3.j new file mode 100644 index 0000000000..bbfcc7d129 --- /dev/null +++ b/Task/Natural-sorting/J/natural-sorting-3.j @@ -0,0 +1,33 @@ + natSor IgnoringLeadingSpaces + ignore leading spaces: 2+0 + ignore leading spaces: 2+1 + ignore leading spaces: 2-1 +ignore leading spaces: 2-2 + + natSor IgnoringMultipleAdjacentSpaces + ignore m.a.s spaces: 2+0 + ignore m.a.s spaces: 2+1 + ignore m.a.s spaces: 2-1 + ignore m.a.s spaces: 2-2 + + natSor EquivalentWhitespaceCharacters + Equiv. +spaces: 3+1\ Equiv.�spaces: 3+0\ Equiv. spaces: 3+2\ Equiv.�spaces: 3-1\ Equiv. +spaces: 3-2\ Equiv. spaces: 3-3\ + natSor CaseIndepenent + casE INDEPENENT: 3+0 + case INDEPENENT: 3+1 + caSE INDEPENENT: 3-1 + cASE INDEPENENT: 3-2 + + natSor NumericFieldsAsNumerics + foo100bar10baz0.txt + foo100bar99baz0.txt + foo1000bar99baz9.txt + foo1000bar99baz10.txt + + natSor Titles + The 39 steps + The 40th step more + Wanda + The Wind in the Willows diff --git a/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 b/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 new file mode 100644 index 0000000000..0b910c590d --- /dev/null +++ b/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 @@ -0,0 +1,27 @@ +# Sort groups of digits in number order. Sort by order of magnitude then lexically. +sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~$0.chars.chr~$0},:g) ~"\x0"~$a } + +# Collapse multiple ws characters to a single. +sub collapse ($a) { $a.subst( / ( \s ) $0+ /, -> $/ { $0 }, :g ) } + +# Convert all ws characters to a space. +sub normalize ($a) { $a.subst( / ( \s ) /, ' ', :g ) } + +# Ignore common leading articles for title sorts +sub title ($a) { $a.subst( / :i ^ ( a | an | the ) >> \s* /, '' ) } + +# Decompose ISO-Latin1 glyphs to their base character. +sub latin1_decompose ($a) { + my %tr = < + Æ AE æ ae Þ TH þ th Ð TH ð th ß ss À A Á A Â A Ã A Ä A Å A à a á a + â a ã a ä a å a Ç C ç c È E É E Ê E Ë E è e é e ê e ë e Ì I Í I Î + I Ï I ì i í i î i ï i Ò O Ó O Ô O Õ O Ö O Ø O ò o ó o ô o õ o ö o + ø o Ñ N ñ n Ù U Ú U Û U Ü U ù u ú u û u ü u Ý Y ÿ y ý y + >; + +# Would probably be better implemented as +# $a.trans( [%tr.keys] => [%tr.values] ); +# but the underlying Parrot VM leaks through in current Rakudo. + my $re = '<[' ~ %tr.keys.join('|') ~ ']>'; + $a.subst(/ (<$re>) /, -> $/ { %tr{$0} }, :g) +} diff --git a/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 b/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 new file mode 100644 index 0000000000..36ca541575 --- /dev/null +++ b/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 @@ -0,0 +1,79 @@ +my @tests = ( + [ + "Task 1a\nSort while ignoring leading spaces.", + [ + 'ignore leading spaces: 1', ' ignore leading spaces: 4', + ' ignore leading spaces: 3', ' ignore leading spaces: 2' + ], + {.trim} # builtin method. + ], + [ + "Task 1b\nSort while ignoring multiple adjacent spaces.", + [ + 'ignore m.a.s spaces: 3', 'ignore m.a.s spaces: 1', + 'ignore m.a.s spaces: 4', 'ignore m.a.s spaces: 2' + ], + {.&collapse} + ], + [ + "Task 2\nSort with all white space normalized to regular spaces.", + [ + "Normalized\tspaces: 4", "Normalized\xa0spaces: 1", + "Normalized\x20spaces: 2", "Normalized\nspaces: 3" + ], + {.&normalize} + ], + [ + "Task 3\nSort case independently.", + [ + 'caSE INDEPENDENT: 3', 'casE INDEPENDENT: 2', + 'cASE INDEPENDENT: 4', 'case INDEPENDENT: 1' + ], + {.lc} # builtin method + ], + [ + "Task 4\nSort groups of digits in natural number order.", + [ + + ], + {.&naturally} + ], + [ + "Task 5 ( mixed with 1, 2, 3 & 4 )\n" + ~ "Sort titles, normalize white space, collapse multiple spaces to\n" + ~ "single, trim leading white space, ignore common leading articles\n" + ~ 'and sort digit groups in natural order.', + [ + 'The Wind in the Willows 8', ' The 39 Steps 3', + 'The 7th Seal 1', 'Wanda 6', + 'A Fish Called Wanda 5', ' The Wind and the Lion 7', + 'Any Which Way But Loose 4', '12 Monkeys 2' + ], + {.&normalize.&collapse.trim.&title.&naturally} + ], + [ + "Task 6, 7, 8\nMap letters in Latin1 that have accents or decompose to two\n" + ~ 'characters to their base characters for sorting.', + [ + + ], + {.&latin1_decompose.&naturally} + ] +); + + +for @tests -> $case { + my $code_ref = $case.pop; + my @array = $case.pop.list; + say $case.pop, "\n"; + + say "Standard Sort:\n"; + .say for @array.sort; + + say "\nNatural Sort:\n"; + .say for @array.sort: {.$code_ref}; + + say "\n" ~ '*' x 40 ~ "\n"; +} diff --git a/Task/Natural-sorting/Perl/natural-sorting-1.pl b/Task/Natural-sorting/Perl/natural-sorting-1.pl new file mode 100644 index 0000000000..2e6d99e33e --- /dev/null +++ b/Task/Natural-sorting/Perl/natural-sorting-1.pl @@ -0,0 +1,22 @@ +use feature 'fc'; +use Unicode::Normalize; + +sub natural_sort { + my @items = map { + my $str = fc(NFKD($_)); + $str =~ s/\s+/ /; + $str =~ s/|^(?:the|a|an) \b|\p{Nonspacing_Mark}| $//g; + my @fields = $str =~ /(?!\z) ([^0-9]*+) ([0-9]*+)/gx; + [$_, \@fields] + } @_; + return map { $_->[0] } sort { + my @x = @{$a->[1]}; + my @y = @{$b->[1]}; + my $numeric; + while (@x && @y) { + my ($x, $y) = (shift @x, shift @y); + return (($numeric = !$numeric) ? $x cmp $y : $x <=> $y or next); + } + return @x <=> @y; + } @items; +} diff --git a/Task/Natural-sorting/Perl/natural-sorting-2.pl b/Task/Natural-sorting/Perl/natural-sorting-2.pl new file mode 100644 index 0000000000..1b17a615fa --- /dev/null +++ b/Task/Natural-sorting/Perl/natural-sorting-2.pl @@ -0,0 +1,30 @@ +use utf8; # interpret this script's source code as UTF8 +use Test::More; # for plan(), is_deeply() +use Data::Dump; # for dd() + +my @testcases = ( + ['Leading spaces', '%sleading spaces: %i', map {' ' x $_} 2, 3, 1, 0 ], + ['Adjacent spaces', 'adjacent%s spaces: %i', map {' ' x $_} 2, 3, 1, 0 ], + ['Different spaces', 'equiv.%sspaces: %i', split //, "\x0b\n\t\x0c\r " ], + ['Case differences', '%s INDEPENENT: %i', 'casE', 'case', 'caSE', 'cASE' ], + ['Numeric fields', 'foo%ibar%ibaz%i.txt', [100, 10, 0], [100, 99, 0], + [1000,99,9], [1000,99,10] ], + ['Title case', '%s', 'The 39 steps', 'The 40th step more', + 'Wanda', 'The Wind in the Willows' ], + ['Accents', 'Equiv. %s accents: %i', 'y', 'Y', "\x{dd}", "\x{fd}" ], + ['Ligatures', '%s', "IJ ligatured ij", 'no ligature' ], + ['Alternate forms', 'Start with an %s: %i', 's', 'ſ', 'ß' ], +); + +plan tests => scalar @testcases; + +foreach (@testcases) { + my ($name, $pattern, @args) = @$_; + my $i = 0; + my @strings = map { sprintf $pattern, ref $_ ? @$_ : $_, $i++ } @args; + + is_deeply( [natural_sort(reverse sort @strings)], \@strings, $name ); + + dd @strings; + print "\n"; +} diff --git a/Task/Natural-sorting/PicoLisp/natural-sorting-1.l b/Task/Natural-sorting/PicoLisp/natural-sorting-1.l new file mode 100644 index 0000000000..0f6d0e223b --- /dev/null +++ b/Task/Natural-sorting/PicoLisp/natural-sorting-1.l @@ -0,0 +1,29 @@ +(de parseNatural (Str) + (clip + (make + (for (L (chop Str) L) + (cond + ((sp? (car L)) + (link " ") + (while (and L (sp? (car L))) + (pop 'L) ) ) + ((>= "9" (car L) "0") + (link + (format + (make + (loop + (link (pop 'L)) + (NIL (>= "9" (car L) "0")) ) ) ) ) ) + (T + (let Word + (pack + (replace + (make + (loop + (link (lowc (pop 'L))) + (NIL L) + (T (sp? (car L))) + (T (>= "9" (car L) "0")) ) ) + "ß" "ss" "ſ" "s" "ʒ" "s" ) ) + (unless (member Word '(the it to)) + (link Word) ) ) ) ) ) ) ) ) diff --git a/Task/Natural-sorting/PicoLisp/natural-sorting-2.l b/Task/Natural-sorting/PicoLisp/natural-sorting-2.l new file mode 100644 index 0000000000..e8cc6c7457 --- /dev/null +++ b/Task/Natural-sorting/PicoLisp/natural-sorting-2.l @@ -0,0 +1,2 @@ +: (parseNatural " ^MThe abc123Defß ^I Ghi ") +-> ("abc" 123 "defss" " " "ghi") diff --git a/Task/Natural-sorting/PicoLisp/natural-sorting-3.l b/Task/Natural-sorting/PicoLisp/natural-sorting-3.l new file mode 100644 index 0000000000..5efc23ab16 --- /dev/null +++ b/Task/Natural-sorting/PicoLisp/natural-sorting-3.l @@ -0,0 +1,2 @@ +(de naturalSort (Lst) + (by parseNatural sort Lst) ) diff --git a/Task/Natural-sorting/PicoLisp/natural-sorting-4.l b/Task/Natural-sorting/PicoLisp/natural-sorting-4.l new file mode 100644 index 0000000000..11bfeca9b6 --- /dev/null +++ b/Task/Natural-sorting/PicoLisp/natural-sorting-4.l @@ -0,0 +1,42 @@ +(de *TestData + "# Ignoring leading spaces" + ("ignore leading spaces: 2-2" " ignore leading spaces: 2-1" " ignore leading spaces: 2+0" " ignore leading spaces: 2+1") + + "# Ignoring multiple adjacent spaces (m.a.s)" + ("ignore m.a.s spaces: 2-2" "ignore m.a.s spaces: 2-1" "ignore m.a.s spaces: 2+0" "ignore m.a.s spaces: 2+1") + + "# Equivalent whitespace characters" + ("Equiv. spaces: 3-3" "Equiv.^Mspaces: 3-2" "Equiv.^Acspaces: 3-1" "Equiv.^Kbspaces: 3+0" "Equiv.^Jspaces: 3+1" "Equiv.^Ispaces: 3+2") + + "# Case Indepenent sort" + ("cASE INDEPENENT: 3-2" "caSE INDEPENENT: 3-1" "casE INDEPENENT: 3+0" "case INDEPENENT: 3+1") + + "# Numeric fields as numerics" + ("foo100bar99baz0.txt" "foo100bar10baz0.txt" "foo1000bar99baz10.txt" "foo1000bar99baz9.txt") + + "# Title sorts" + ("The Wind in the Willows" "The 40th step more" "The 39 steps" "Wanda") + + "# Equivalent accented characters (and case)" + ("Equiv. ý accents: 2-2" "Equiv. Ý accents: 2-1" "Equiv. y accents: 2+0" "Equiv. Y accents: 2+1") + + # "Separated ligatures" + ### ("IJ ligatured ij" "no ligature") + + "# Character replacements" + ("Start with an ʒ: 2-2" "Start with an ſ: 2-1" "Start with an ß: 2+0" "Start with an s: 2+1") ) + +(de pythonOut (Ttl Lst) + (prinl Ttl) + (prin "['" (car Lst)) + (for S (cdr Lst) + (prin "',^J '" S) ) + (prinl "']") ) + +(for X *TestData + (if (atom X) + (prinl X) + (pythonOut "Text strings:" X) + (pythonOut "Normally sorted :" (sort (copy X))) + (pythonOut "Naturally sorted:" (naturalSort X)) + (prinl) ) ) diff --git a/Task/Natural-sorting/Python/natural-sorting.py b/Task/Natural-sorting/Python/natural-sorting.py new file mode 100644 index 0000000000..a9f0cc092e --- /dev/null +++ b/Task/Natural-sorting/Python/natural-sorting.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Not Python 3.x (Can't compare str and int) + + +from itertools import groupby +from unicodedata import decomposition, name +from pprint import pprint as pp + +commonleaders = ['the'] # lowercase leading words to ignore +replacements = {u'ß': 'ss', # Map single char to replacement string + u'ſ': 's', + u'ʒ': 's', + } + +hexdigits = set('0123456789abcdef') +decdigits = set('0123456789') # Don't use str.isnumeric + +def splitchar(c): + ' De-ligature. De-accent a char' + de = decomposition(c) + if de: + # Just the words that are also hex numbers + de = [d for d in de.split() + if all(c.lower() + in hexdigits for c in d)] + n = name(c, c).upper() + # (Gosh it's onerous) + if len(de)> 1 and 'PRECEDE' in n: + # E.g. ʼn LATIN SMALL LETTER N PRECEDED BY APOSTROPHE + de[1], de[0] = de[0], de[1] + tmp = [ unichr(int(k, 16)) for k in de] + base, others = tmp[0], tmp[1:] + if 'LIGATURE' in n: + # Assume two character ligature + base += others.pop(0) + else: + base = c + return base + + +def sortkeygen(s): + '''Generate 'natural' sort key for s + + Doctests: + >>> sortkeygen(' some extra spaces ') + [u'some extra spaces'] + >>> sortkeygen('CasE InseNsItIve') + [u'case insensitive'] + >>> sortkeygen('The Wind in the Willows') + [u'wind in the willows'] + >>> sortkeygen(u'\462 ligature') + [u'ij ligature'] + >>> sortkeygen(u'\335\375 upper/lower case Y with acute accent') + [u'yy upper/lower case y with acute accent'] + >>> sortkeygen('foo9.txt') + [u'foo', 9, u'.txt'] + >>> sortkeygen('x9y99') + [u'x', 9, u'y', 99] + ''' + # Ignore leading and trailing spaces + s = unicode(s).strip() + # All space types are equivalent + s = ' '.join(s.split()) + # case insentsitive + s = s.lower() + # Title + words = s.split() + if len(words) > 1 and words[0] in commonleaders: + s = ' '.join( words[1:]) + # accent and ligatures + s = ''.join(splitchar(c) for c in s) + # Replacements (single char replaced by one or more) + s = ''.join( replacements.get(ch, ch) for ch in s ) + # Numeric sections as numerics + s = [ int("".join(g)) if isinteger else "".join(g) + for isinteger,g in groupby(s, lambda x: x in decdigits)] + + return s + +def naturalsort(items): + ''' Naturally sort a series of strings + + Doctests: + >>> naturalsort(['The Wind in the Willows','The 40th step more', + 'The 39 steps', 'Wanda']) + ['The 39 steps', 'The 40th step more', 'Wanda', 'The Wind in the Willows'] + + ''' + return sorted(items, key=sortkeygen) + +if __name__ == '__main__': + import string + + ns = naturalsort + + print '\n# Ignoring leading spaces' + txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Ignoring multiple adjacent spaces (m.a.s)' + txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Equivalent whitespace characters' + txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3) + for i,ch in enumerate(reversed(string.whitespace))] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Case Indepenent sort' + s = 'CASE INDEPENENT' + txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Numeric fields as numerics' + txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', + 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Title sorts' + txt = ['The Wind in the Willows','The 40th step more', + 'The 39 steps', 'Wanda'] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Equivalent accented characters (and case)' + txt = ['Equiv. %s accents: 2%+i' % (ch, i-2) + for i,ch in enumerate(u'\xfd\xddyY')] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Separated ligatures' + txt = [u'\462 ligatured ij', 'no ligature',] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; pp(sorted(txt)) + print 'Naturally sorted:'; pp(ns(txt)) + + print '\n# Character replacements' + s = u'ʒſßs' # u'\u0292\u017f\xdfs' + txt = ['Start with an %s: 2%+i' % (ch, i-2) + for i,ch in enumerate(s)] + print 'Text strings:'; pp(txt) + print 'Normally sorted :'; print '\n'.join(sorted(txt)) + print 'Naturally sorted:'; print '\n'.join(ns(txt)) diff --git a/Task/Natural-sorting/README b/Task/Natural-sorting/README new file mode 100644 index 0000000000..907812aa9e --- /dev/null +++ b/Task/Natural-sorting/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Natural_sorting diff --git a/Task/Natural-sorting/Racket/natural-sorting.rkt b/Task/Natural-sorting/Racket/natural-sorting.rkt new file mode 100644 index 0000000000..c5bf47f106 --- /dev/null +++ b/Task/Natural-sorting/Racket/natural-sorting.rkt @@ -0,0 +1,21 @@ +#lang racket +(define (natural-sort l) + (define (listkeys s) + (define s* (string-normalize-spaces (string-foldcase s))) + (for/list ([x (regexp-match* #px"\\d+" s* #:gap-select? #t)] + [i (in-naturals)]) + (if (odd? i) (string->number x) x))) + (sort l listkeys #:cache-keys? #t)) + +(natural-sort + (shuffle '("foo9.txt" "foo10.txt" "x9y99" "x9y100" "x10y0" "x z" "x y"))) +;; => '("foo9.txt" "foo10.txt" "x9y99" "x9y100" "x10y0" "x y" "x z") diff --git a/Task/Natural-sorting/Ruby/natural-sorting-1.rb b/Task/Natural-sorting/Ruby/natural-sorting-1.rb new file mode 100644 index 0000000000..91751d145e --- /dev/null +++ b/Task/Natural-sorting/Ruby/natural-sorting-1.rb @@ -0,0 +1 @@ +ar.sort_by{|str| str.downcase.gsub(/\Athe |\Aa |\Aan /, "").lstrip.gsub(/\s+/, " ")} diff --git a/Task/Natural-sorting/Ruby/natural-sorting-2.rb b/Task/Natural-sorting/Ruby/natural-sorting-2.rb new file mode 100644 index 0000000000..65a024359d --- /dev/null +++ b/Task/Natural-sorting/Ruby/natural-sorting-2.rb @@ -0,0 +1,24 @@ +class NatSortString + include Comparable + attr_reader :scrubbed, :ints_and_strings, :i_s_pattern + + def initialize(str) + @str = str + @scrubbed = str.downcase.gsub(/\Athe |\Aa |\Aan /, "").lstrip.gsub(/\s+/, " ") + @ints_and_strings = @scrubbed.scan(/\d+|\D+/).map{|s| s =~ /\d/ ? s.to_i : s} + @i_s_pattern = @ints_and_strings.map{|el| el.is_a?(Integer) ? :i : :s}.join + end + + def <=> (other) + if i_s_pattern.start_with?(other.i_s_pattern) or other.i_s_pattern.start_with?(i_s_pattern) then + ints_and_strings <=> other.ints_and_strings + else + scrubbed <=> other.scrubbed + end + end + + def to_s + @str.dup + end + +end diff --git a/Task/Natural-sorting/Ruby/natural-sorting-3.rb b/Task/Natural-sorting/Ruby/natural-sorting-3.rb new file mode 100644 index 0000000000..9ad89fcd65 --- /dev/null +++ b/Task/Natural-sorting/Ruby/natural-sorting-3.rb @@ -0,0 +1,18 @@ +tests = + {"Ignoring leading spaces" => + [ "ignore leading spaces: 2-2 ", " ignore leading spaces: 2-1 ", " ignore leading spaces: 2+0 ", " ignore leading spaces: 2+1 "], + "Ignoring multiple adjacent spaces" => + [ "ignore m.a.s spaces: 2-2 ", "ignore m.a.s spaces: 2-1 ", "ignore m.a.s spaces: 2+0 ", "ignore m.a.s spaces: 2+1 "], + "Equivalent whitespace characters" => + ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"], + "Case Indepenent sort" => + [ "cASE INDEPENENT: 3-2 ", "caSE INDEPENENT: 3-1 ", "casE INDEPENENT: 3+0 ", "case INDEPENENT: 3+1 "], + "Numeric fields as numerics" => + [ "foo100bar99baz0.txt ", "foo100bar10baz0.txt ", "foo1000bar99baz10.txt ", "foo1000bar99baz9.txt "], + "Title sorts" => + [ "The Wind in the Willows ", "The 40th step more ", "The 39 steps ", "Wanda "]} + +tests.each do |title, ar| + nat_sorts = ar.map{|s| NatSortString.new(s)} + puts [title,"--input--", ar, "--normal sort--", ar.sort, "--natural sort--", nat_sorts.sort, "\n"] +end diff --git a/Task/Natural-sorting/Scala/natural-sorting.scala b/Task/Natural-sorting/Scala/natural-sorting.scala new file mode 100644 index 0000000000..28393b301b --- /dev/null +++ b/Task/Natural-sorting/Scala/natural-sorting.scala @@ -0,0 +1,53 @@ +object NaturalSorting { + implicit object ArrayOrdering extends Ordering[Array[String]] { // 4 + val INT = "([0-9]+)".r + def compare(a: Array[String], b: Array[String]) = { + val l = Math.min(a.length, b.length) + (0 until l).prefixLength(i => a(i) equals b(i)) match { + case i if i == l => Math.signum(b.length - a.length).toInt + case i => (a(i), b(i)) match { + case (INT(c), INT(d)) => Math.signum(c.toInt - d.toInt).toInt + case (c, d) => c compareTo d + } + } + } + } + + def natural(s: String) = { + val replacements = Map('\u00df' -> "ss", '\u017f' -> "s", '\u0292' -> "s").withDefault(s => s.toString) // 8 + import java.text.Normalizer + Normalizer.normalize(Normalizer.normalize( + s.trim.toLowerCase, // 1.1, 1.2, 3 + Normalizer.Form.NFKC), // 7 + Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", "") // 6 + .replaceAll("^(the|a|an) ", "") // 5 + .flatMap(replacements.apply) // 8 + .split(s"\\s+|(?=[0-9])(?<=[^0-9])|(?=[^0-9])(?<=[0-9])") // 1.3, 2 and 4 + } +} + +object NaturalSortingTest extends App { + import NaturalSorting._ + + val tests = List( + ("1 Ignoring leading spaces", List("ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"), List(" ignore leading spaces: 2+0", " ignore leading spaces: 2+1", " ignore leading spaces: 2-1", "ignore leading spaces: 2-2")), + ("1 Ignoring multiple adjacent spaces (m.a.s)", List("ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"), List("ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2-2")), + ("2 Equivalent whitespace characters", List("Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\u000cspaces: 3-1", "Equiv.\u000bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"), List("Equiv.\u000bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2", "Equiv.\u000cspaces: 3-1", "Equiv.\rspaces: 3-2", "Equiv. spaces: 3-3")), + ("3 Case Independent sort", List("cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"), List("casE INDEPENENT: 3+0", "case INDEPENENT: 3+1", "caSE INDEPENENT: 3-1", "cASE INDEPENENT: 3-2")), + ("4 Numeric fields as numerics", List("foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"), List("foo100bar10baz0.txt", "foo100bar99baz0.txt", "foo1000bar99baz9.txt", "foo1000bar99baz10.txt")), + ("5 Title sorts", List("The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"), List("The 39 steps", "The 40th step more", "Wanda", "The Wind in the Willows")), + ("6 Equivalent accented characters (and case)", List("Equiv. \u00fd accents: 2-2", "Equiv. \u00dd accents: 2-1", "Equiv. y accents: 2+0", "Equiv. Y accents: 2+1"), List("Equiv. y accents: 2+0", "Equiv. Y accents: 2+1", "Equiv. \u00dd accents: 2-1", "Equiv. \u00fd accents: 2-2")), + ("7 Separated ligatures", List("\u0132 ligatured ij", "no ligature"), List("\u0132 ligatured ij", "no ligature")), + ("8 Character replacements", List("Start with an \u0292: 2-2", "Start with an \u017f: 2-1", "Start with an \u00df: 2+0", "Start with an s: 2+1"), List("Start with an s: 2+1", "Start with an \u017f: 2-1", "Start with an \u0292: 2-2", "Start with an \u00df: 2+0")) + ) + + val width = tests.flatMap(_._2).map(_.length).max + assert(tests.forall{case (title, input, expected) => + val result = input.sortBy(natural) + val okay = result == expected + val label = if (okay) "pass" else "fail" + println(s"$label: $title".toUpperCase) + input.zip(result).foreach{case (a, b) => println(s" ${a.padTo(width, ' ')} | ${b.padTo(width, ' ')}")} + okay + }) +} diff --git a/Task/Natural-sorting/Tcl/natural-sorting.tcl b/Task/Natural-sorting/Tcl/natural-sorting.tcl new file mode 100644 index 0000000000..361608d79a --- /dev/null +++ b/Task/Natural-sorting/Tcl/natural-sorting.tcl @@ -0,0 +1,59 @@ +package require Tcl 8.5 + +proc sortWithCollationKey {keyBuilder list} { + if {![llength $list]} return + foreach value $list { + lappend toSort [{*}$keyBuilder $value] + } + foreach idx [lsort -indices $toSort] { + lappend result [lindex $list $idx] + } + return $result +} +proc normalizeSpaces {str} { + regsub -all {[ ]+} [string trim $str " "] " " +} +proc equivalentWhitespace {str} { + regsub -all {\s} $str " " +} + +proc show {description sorter strings} { + puts "Input:\n\t[join $strings \n\t]" + set sorted [lsort $strings] + puts "Normally sorted:\n\t[join $sorted \n\t]" + set sorted [{*}$sorter $strings] + puts "Naturally sorted with ${description}:\n\t[join $sorted \n\t]" +} + +# Two demonstrations of the space normalizer +show "normalized spaces" {sortWithCollationKey normalizeSpaces} { + {ignore leading spaces: 2-2} + { ignore leading spaces: 2-1} + { ignore leading spaces: 2+0} + { ignore leading spaces: 2+1}} +show "normalized spaces" {sortWithCollationKey normalizeSpaces} { + {ignore m.a.s spaces: 2-2} + {ignore m.a.s spaces: 2-1} + {ignore m.a.s spaces: 2+0} + {ignore m.a.s spaces: 2+1}} + +# Use a collation key that maps all whitespace to spaces +show "all whitespace equivalent" {sortWithCollationKey equivalentWhitespace} { + "Equiv. spaces: 3-3" + "Equiv.\rspaces: 3-2" + "Equiv.\u000cspaces: 3-1" + "Equiv.\u000bspaces: 3+0" + "Equiv.\nspaces: 3+1" + "Equiv.\tspaces: 3+2"} + +# These are built-in modes +show "(built-in) case insensitivity" {lsort -nocase} { + {cASE INDEPENENT: 3-2} + {caSE INDEPENENT: 3-1} + {casE INDEPENENT: 3+0} + {case INDEPENENT: 3+1}} +show "digit sequences as numbers" {lsort -dictionary} { + foo100bar99baz0.txt + foo100bar10baz0.txt + foo1000bar99baz10.txt + foo1000bar99baz9.txt} diff --git a/Task/Nth/00DESCRIPTION b/Task/Nth/00DESCRIPTION new file mode 100644 index 0000000000..d393576c12 --- /dev/null +++ b/Task/Nth/00DESCRIPTION @@ -0,0 +1,8 @@ +Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the [[wp:Ordinal number (linguistics)|ordinal suffix]]. +
Example returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th + +;Task: +Use your routine to show here the output for ''at least'' the following (inclusive) ranges of integer inputs: +0..25, 250..265, 1000..1025 + +'''Note:''' apostrophes are now ''optional'' to allow correct apostrophe-less English. diff --git a/Task/Nth/00META.yaml b/Task/Nth/00META.yaml new file mode 100644 index 0000000000..1536f2edf2 --- /dev/null +++ b/Task/Nth/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Ordinal numbers diff --git a/Task/Nth/ALGOL-68/nth.alg b/Task/Nth/ALGOL-68/nth.alg new file mode 100644 index 0000000000..c468135b15 --- /dev/null +++ b/Task/Nth/ALGOL-68/nth.alg @@ -0,0 +1,49 @@ +# PROC to suffix a number with st, nd, rd or th as appropriate # +PROC nth = ( INT number )STRING: +BEGIN + + INT number mod 100 = number MOD 100; + +# RESULT # + whole( number, 0 ) + + IF number mod 100 >= 10 AND number mod 100 <= 20 + THEN + # numbers in the range 10 .. 20 always have "th" # + "th" + ELSE + # not in the range 10 .. 20, suffix is st, nd, rd or th # + # depending on the final digit # + CASE number MOD 10 + IN # 1 # "st" + , # 2 # "nd" + , # 3 # "rd" + OUT "th" + ESAC + FI +END; # nth # + +# PROC to test nth, displays nth for all numbers in the range from .. to # +PROC test nth = ( INT from, INT to )VOID: +BEGIN + INT test count := 0; + FOR test value FROM from TO to + DO + STRING test result = nth( test value ); + print( ( " "[ 1 : 8 - UPB test result ], nth( test value ) ) ); + test count +:= 1; + IF test count MOD 8 = 0 + THEN + print( ( newline ) ) + FI + OD; + print( ( newline ) ) +END; # test nth # + + +main: ( + + test nth( 0, 25 ); + test nth( 250, 265 ); + test nth( 1000, 1025 ) + +) diff --git a/Task/Nth/AWK/nth.awk b/Task/Nth/AWK/nth.awk new file mode 100644 index 0000000000..33d9b8a1b0 --- /dev/null +++ b/Task/Nth/AWK/nth.awk @@ -0,0 +1,32 @@ +# syntax: GAWK -f NTH.AWK +BEGIN { + prn(0,25) + prn(250,265) + prn(1000,1025) + exit(0) +} +function prn(start,stop, i) { + printf("%d-%d: ",start,stop) + for (i=start; i<=stop; i++) { + printf("%d%s ",i,nth(i)) + } + printf("\n") +} +function nth(yearday, nthday) { + if (yearday ~ /1[1-3]$/) { # 11th,12th,13th + nthday = "th" + } + else if (yearday ~ /1$/) { # 1st,21st,31st,etc. + nthday = "st" + } + else if (yearday ~ /2$/) { # 2nd,22nd,32nd,etc. + nthday = "nd" + } + else if (yearday ~ /3$/) { # 3rd,23rd,33rd,etc. + nthday = "rd" + } + else if (yearday ~ /[0456789]$/) { # 4th-10th,20th,24th-30th,etc. + nthday = "th" + } + return(nthday) +} diff --git a/Task/Nth/Ada/nth.ada b/Task/Nth/Ada/nth.ada new file mode 100644 index 0000000000..58603f7fac --- /dev/null +++ b/Task/Nth/Ada/nth.ada @@ -0,0 +1,26 @@ +with Ada.Text_IO; + +procedure Nth is + + function Suffix(N: Natural) return String is + begin + if N mod 10 = 1 and then N mod 100 /= 11 then return "st"; + elsif N mod 10 = 2 and then N mod 100 /= 12 then return "nd"; + elsif N mod 10 = 3 and then N mod 100 /= 13 then return "rd"; + else return "th"; + end if; + end Suffix; + + procedure Print_Images(From, To: Natural) is + begin + for I in From .. To loop + Ada.Text_IO.Put(Natural'Image(I) & Suffix(I)); + end loop; + Ada.Text_IO.New_Line; + end Print_Images; + +begin + Print_Images( 0, 25); + Print_Images( 250, 265); + Print_Images(1000, 1025); +end Nth; diff --git a/Task/Nth/Applesoft-BASIC/nth.applesoft b/Task/Nth/Applesoft-BASIC/nth.applesoft new file mode 100644 index 0000000000..76e16bd93b --- /dev/null +++ b/Task/Nth/Applesoft-BASIC/nth.applesoft @@ -0,0 +1,19 @@ +0 OP = 1 +10 FOR N = 0 TO 25 : GOSUB 100 : NEXT +20 FOR N = 250 TO 265 : GOSUB 100 : NEXT +30 FOR N = 1000 TO 1025 : GOSUB 100 : NEXT +40 END + +100 GOSUB 200"NTH +110 PRINT NTH$ " "; +120 RETURN + +200 M1 = N - INT(N / 10) * 10 +210 M2 = N - INT(N / 100) * 100 +220 NTH$ = "TH" +230 IF M1 = 1 AND M2 <> 11 THEN NTH$ = "ST" +240 IF M1 = 2 AND M2 <> 12 THEN NTH$ = "ND" +250 IF M1 = 3 AND M2 <> 13 THEN NTH$ = "RD" +260 IF NOT OP THEN NTH$ = "'" + NTH$ +270 NTH$ = STR$(N) + NTH$ +280 RETURN diff --git a/Task/Nth/AutoHotkey/nth.ahk b/Task/Nth/AutoHotkey/nth.ahk new file mode 100644 index 0000000000..def866b26d --- /dev/null +++ b/Task/Nth/AutoHotkey/nth.ahk @@ -0,0 +1,16 @@ +for k, v in [[0, 25], [250, 265], [1000, 1025]] { + while v[1] <= v[2] { + Out .= Ordinal(v[1]) " " + v[1]++ + } + Out .= "`n" +} +MsgBox, % Out + +Ordinal(n) { + s2 := Mod(n, 100) + if (s2 > 10 && s2 < 14) + return n "th" + s1 := Mod(n, 10) + return n (s1 = 1 ? "st" : s1 = 2 ? "nd" : s1 = 3 ? "rd" : "th") +} diff --git a/Task/Nth/BBC-BASIC/nth.bbc b/Task/Nth/BBC-BASIC/nth.bbc new file mode 100644 index 0000000000..82889f99cd --- /dev/null +++ b/Task/Nth/BBC-BASIC/nth.bbc @@ -0,0 +1,16 @@ + PROCNth( 0, 25) + PROCNth( 250, 265) + PROCNth(1000,1025) + END + + DEF PROCNth(s%,e%) + LOCAL i%,suff$ + FOR i%=s% TO e% + suff$="th" + IF i% MOD 10 = 1 AND i% MOD 100 <> 11 suff$="st" + IF i% MOD 10 = 2 AND i% MOD 100 <> 12 suff$="nd" + IF i% MOD 10 = 3 AND i% MOD 100 <> 13 suff$="rd" + PRINT STR$i%+suff$+" "; + NEXT + PRINT + ENDPROC diff --git a/Task/Nth/Babel/nth.pb b/Task/Nth/Babel/nth.pb new file mode 100644 index 0000000000..ccdf54be2a --- /dev/null +++ b/Task/Nth/Babel/nth.pb @@ -0,0 +1,28 @@ +((irregular ("st" "nd" "rd")) + +(main + {(0 250 1000) + { test ! "\n" << } + each}) + +(test { + <- + {iter 1 - -> dup <- + ordinalify ! << + {iter 10 %} {" "} {"\n"} ifte << } + 26 times}) + +(ordinalify { + <- + {{ -> dup <- 100 % 10 cugt } ! + { -> dup <- 100 % 14 cult } ! + and not + { -> dup <- 10 % 0 cugt } ! + { -> dup <- 10 % 4 cult } ! + and + and} + { -> dup + <- %d "'" + irregular -> 10 % 1 - ith + . . } + { -> %d "'th" . } + ifte })) diff --git a/Task/Nth/C/nth.c b/Task/Nth/C/nth.c new file mode 100644 index 0000000000..330c79e8df --- /dev/null +++ b/Task/Nth/C/nth.c @@ -0,0 +1,52 @@ +#include + +char* addSuffix(int num, char* buf, size_t len) +{ + char *suffixes[4] = { "th", "st", "nd", "rd" }; + int i; + + switch (num % 10) + { + case 1 : i = (num % 100 == 11) ? 0 : 1; + break; + case 2 : i = (num % 100 == 12) ? 0 : 2; + break; + case 3 : i = (num % 100 == 13) ? 0 : 3; + break; + default: i = 0; + }; + + snprintf(buf, len, "%d%s", num, suffixes[i]); + return buf; +} + +int main(void) +{ + int i; + + printf("Set [0,25]:\n"); + for (i = 0; i < 26; i++) + { + char s[5]; + printf("%s ", addSuffix(i, s, 5)); + } + putchar('\n'); + + printf("Set [250,265]:\n"); + for (i = 250; i < 266; i++) + { + char s[6]; + printf("%s ", addSuffix(i, s, 6)); + } + putchar('\n'); + + printf("Set [1000,1025]:\n"); + for (i = 1000; i < 1026; i++) + { + char s[7]; + printf("%s ", addSuffix(i, s, 7)); + } + putchar('\n'); + + return 0; +} diff --git a/Task/Nth/Clojure/nth-1.clj b/Task/Nth/Clojure/nth-1.clj new file mode 100644 index 0000000000..133e0d47e8 --- /dev/null +++ b/Task/Nth/Clojure/nth-1.clj @@ -0,0 +1,14 @@ +(defn n-th [n] + (str n + (let [rem (mod n 100)] + (if (and (>= rem 11) (<= rem 13)) + "th" + (condp = (mod n 10) + 1 "st" + 2 "nd" + 3 "rd" + "th"))))) + +(apply str (interpose " " (map n-th (range 0 26)))) +(apply str (interpose " " (map n-th (range 250 266)))) +(apply str (interpose " " (map n-th (range 1000 1026)))) diff --git a/Task/Nth/Clojure/nth-2.clj b/Task/Nth/Clojure/nth-2.clj new file mode 100644 index 0000000000..d3cdae9919 --- /dev/null +++ b/Task/Nth/Clojure/nth-2.clj @@ -0,0 +1 @@ +(apply str (interpose " " (map #(clojure.pprint/cl-format nil "~:R" %) (range 0 26)))) diff --git a/Task/Nth/Common-Lisp/nth.lisp b/Task/Nth/Common-Lisp/nth.lisp new file mode 100644 index 0000000000..7207c53347 --- /dev/null +++ b/Task/Nth/Common-Lisp/nth.lisp @@ -0,0 +1,15 @@ +(defun add-suffix (number) + (let* ((suffixes #10("th" "st" "nd" "rd" "th")) + (last2 (mod number 100)) + (last-digit (mod number 10)) + (suffix (if (< 10 last2 20) + "th" + (svref suffixes last-digit)))) + (format nil "~a~a" number suffix))) + +(loop for (low high) in '((0 25) (250 265) (1000 1025)) + do (progn + (format t "~a to ~a: " low high) + (loop for n from low to high + do (format t "~a " (add-suffix n)) + finally (terpri)))) diff --git a/Task/Nth/D/nth.d b/Task/Nth/D/nth.d new file mode 100644 index 0000000000..de0374c188 --- /dev/null +++ b/Task/Nth/D/nth.d @@ -0,0 +1,12 @@ +import std.stdio, std.string, std.range, std.algorithm; + +string nth(in uint n) pure { + static immutable suffix = "th st nd rd th th th th th th".split; + return "%d'%s".format(n, (n % 100 <= 10 || n % 100 > 20) ? + suffix[n % 10] : "th"); +} + +void main() { + foreach (r; [iota(26), iota(250, 266), iota(1000, 1026)]) + writefln("%-(%s %)", r.map!nth); +} diff --git a/Task/Nth/Forth/nth.fth b/Task/Nth/Forth/nth.fth new file mode 100644 index 0000000000..e78d076a18 --- /dev/null +++ b/Task/Nth/Forth/nth.fth @@ -0,0 +1,10 @@ +: 'nth ( -- c-addr ) s" th st nd rd th th th th th th " drop ; +: .nth ( n -- ) + dup 10 20 within if 0 .r ." th " exit then + dup 0 .r 10 mod 3 * 'nth + 3 type ; + +: test ( n n -- ) cr do i 5 mod 0= if cr then i .nth loop ; +: tests ( -- ) + 26 0 test 266 250 test 1026 1000 test ; + +tests diff --git a/Task/Nth/Fortran/nth.f b/Task/Nth/Fortran/nth.f new file mode 100644 index 0000000000..c39ebae344 --- /dev/null +++ b/Task/Nth/Fortran/nth.f @@ -0,0 +1,89 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Fri Jun 6 15:40:18 +! +!a=./f && make -k $a && echo 0 25 | $a && echo 250 265 | $a && echo 1000 1025 | $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f +! 0'th 1'st 2'nd +! 3'rd 4'th 5'th +! 6'th 7'th 8'th +! 9'th 10'th 11'th +! 12'th 13'th 14'th +! 15'th 16'th 17'th +! 18'th 19'th 20'th +! 21'st 22'nd 23'rd +! 24'th 25'th +! 250'th 251'st +! 252'nd 253'rd 254'th +! 255'th 256'th 257'th +! 258'th 259'th 260'th +! 261'st 262'nd 263'rd +! 264'th 265'th +! 1000th 1001st +! 1002nd 1003rd 1004th +! 1005th 1006th 1007th +! 1008th 1009th 1010th +! 1011th 1012th 1013th +! 1014th 1015th 1016th +! 1017th 1018th 1019th +! 1020th 1021st 1022nd +! 1023rd 1024th 1025th +! +!Compilation finished at Fri Jun 6 15:40:18 + +program nth + implicit none + logical :: need + integer :: here, there, n, i, iostat + read(5,*,iostat=iostat) here, there + if (iostat .ne. 0) then + write(6,*)'such bad input never before seen.' + write(6,*)'I AYE EYE QUIT!' + call exit(1) + end if + need = .false. + n = abs(there - here) + 1 + i = 0 + do while (0 /= mod(3+mod(here-i, 3), 3)) + write(6,'(a22)',advance='no') '' + i = i+1 + end do + do i = here, there, sign(1, there-here) + write(6,'(a22)',advance='no') ordinate(i) + if (2 /= mod(i,3)) then + need = .true. + else + write(6,'(a)')'' + need = .false. + end if + end do + if (need) write(6,'(a)')'' + +contains + + character(len=22) function ordinate(n) + character(len=19) :: a + character(len=20), parameter :: & + &a09 = "thstndrdthththththth",& + &ateen = "thththththththththth" + integer :: ones, tens, ones_index + integer, intent(in) :: n + write(a,'(i19)') n + ones = mod(n,10) + tens = mod(n,100) + ones_index = ones*2+1 + if (n < 1000) then + if ((10 .le. tens) .and. (tens .lt. 20)) then + ordinate = a // "'" // ateen(ones_index:ones_index+1) + else + ordinate = a // "'" // a09(ones_index:ones_index+1) + end if + else + if ((10 .le. tens) .and. (tens .lt. 20)) then + ordinate = a // ateen(ones_index:ones_index+1) + else + ordinate = a // a09(ones_index:ones_index+1) + end if + end if + end function ordinate + +end program nth diff --git a/Task/Nth/Go/nth.go b/Task/Nth/Go/nth.go new file mode 100644 index 0000000000..0185ee21b2 --- /dev/null +++ b/Task/Nth/Go/nth.go @@ -0,0 +1,37 @@ +package main + +import "fmt" + +func ord(n int) string { + s := "th" + switch c := n % 10; c { + case 1, 2, 3: + if n%100/10 == 1 { + break + } + switch c { + case 1: + s = "st" + case 2: + s = "nd" + case 3: + s = "rd" + } + } + return fmt.Sprintf("%d%s", n, s) +} + +func main() { + for n := 0; n <= 25; n++ { + fmt.Printf("%s ", ord(n)) + } + fmt.Println() + for n := 250; n <= 265; n++ { + fmt.Printf("%s ", ord(n)) + } + fmt.Println() + for n := 1000; n <= 1025; n++ { + fmt.Printf("%s ", ord(n)) + } + fmt.Println() +} diff --git a/Task/Nth/Haskell/nth.hs b/Task/Nth/Haskell/nth.hs new file mode 100644 index 0000000000..1d558ebcb0 --- /dev/null +++ b/Task/Nth/Haskell/nth.hs @@ -0,0 +1,19 @@ +import Data.Array + +ordSuffs :: Array Integer String +ordSuffs = listArray (0,9) ["th", "st", "nd", "rd", "th", + "th", "th", "th", "th", "th"] + +ordSuff :: Integer -> String +ordSuff n = show n ++ suff n + where suff m | (m `rem` 100) >= 11 && (m `rem` 100) <= 13 = "th" + | otherwise = ordSuffs ! (m `rem` 10) + +printOrdSuffs :: [Integer] -> IO () +printOrdSuffs = putStrLn . unwords . map ordSuff + +main :: IO () +main = do + printOrdSuffs [ 0.. 25] + printOrdSuffs [ 250.. 265] + printOrdSuffs [1000..1025] diff --git a/Task/Nth/Icon/nth.icon b/Task/Nth/Icon/nth.icon new file mode 100644 index 0000000000..4bc17481c7 --- /dev/null +++ b/Task/Nth/Icon/nth.icon @@ -0,0 +1,11 @@ +procedure main(A) + every writes(" ",nth(0 to 25) | "\n") + every writes(" ",nth(250 to 265) | "\n") + every writes(" ",nth(1000 to 1025) | "\n") +end + +procedure nth(n) + return n || ((n%10 = 1, n%100 ~= 11, "st") | + (n%10 = 2, n%100 ~= 12, "nd") | + (n%10 = 3, n%100 ~= 13, "rd") | "th") +end diff --git a/Task/Nth/J/nth-1.j b/Task/Nth/J/nth-1.j new file mode 100644 index 0000000000..5105f8989a --- /dev/null +++ b/Task/Nth/J/nth-1.j @@ -0,0 +1,3 @@ +suf=: (;:'th st nd rd th'){::~4<.10 10(* 1&~:)~/@#:] + +nth=: [:;:inv (":,suf)each diff --git a/Task/Nth/J/nth-2.j b/Task/Nth/J/nth-2.j new file mode 100644 index 0000000000..a5f45154dd --- /dev/null +++ b/Task/Nth/J/nth-2.j @@ -0,0 +1,7 @@ + thru=: <./ + i.@(+ *)@-~ + nth 0 thru 25 +0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th + nth 250 thru 265 +250th 251st 252nd 253rd 254th 255th 256th 257th 258th 259th 260th 261st 262nd 263rd 264th 265th + nth 1000 thru 1025 +1000th 1001st 1002nd 1003rd 1004th 1005th 1006th 1007th 1008th 1009th 1010th 1011th 1012th 1013th 1014th 1015th 1016th 1017th 1018th 1019th 1020th 1021st 1022nd 1023rd 1024th 1025th diff --git a/Task/Nth/Java/nth-1.java b/Task/Nth/Java/nth-1.java new file mode 100644 index 0000000000..05caa9dd27 --- /dev/null +++ b/Task/Nth/Java/nth-1.java @@ -0,0 +1,26 @@ +public class Nth { + public static String ordinalAbbrev(int n){ + String ans = "th"; //most of the time it should be "th" + if(n % 100 / 10 == 1) return ans; //teens are all "th" + switch(n % 10){ + case 1: ans = "st"; break; + case 2: ans = "nd"; break; + case 3: ans = "rd"; break; + } + return ans; + } + + public static void main(String[] args){ + for(int i = 0; i <= 25;i++){ + System.out.print(i + ordinalAbbrev(i) + " "); + } + System.out.println(); + for(int i = 250; i <= 265;i++){ + System.out.print(i + ordinalAbbrev(i) + " "); + } + System.out.println(); + for(int i = 1000; i <= 1025;i++){ + System.out.print(i + ordinalAbbrev(i) + " "); + } + } +} diff --git a/Task/Nth/Java/nth-2.java b/Task/Nth/Java/nth-2.java new file mode 100644 index 0000000000..faa66d1856 --- /dev/null +++ b/Task/Nth/Java/nth-2.java @@ -0,0 +1,48 @@ +package nth; + +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public interface Nth { + public static String suffix(int n){ + if(n % 100 / 10 == 1){ + return "th"; //teens are all "th" + } + switch(n % 10){ + case 1: return "st"; + case 2: return "nd"; + case 3: return "rd"; + default: return "th"; //most of the time it should be "th" + } + } + + public static void print(int start, int end) { + IntStream.rangeClosed(start, end) + .parallel() + .mapToObj(i -> i + suffix(i) + " ") + .reduce(String::concat) + .ifPresent(System.out::println) + ; + } + + public static void print(int[] startAndEnd) { + print(startAndEnd[0], startAndEnd[1]); + } + + public static int[] startAndEnd(int start, int end) { + return new int[] { + start, + end + }; + } + + public static void main(String... arguments){ + Stream.of( + startAndEnd(0, 25), + startAndEnd(250, 265), + startAndEnd(1000, 1025) + ) + .forEach(Nth::print) + ; + } +} diff --git a/Task/Nth/MATLAB/nth.m b/Task/Nth/MATLAB/nth.m new file mode 100644 index 0000000000..5c2a344d80 --- /dev/null +++ b/Task/Nth/MATLAB/nth.m @@ -0,0 +1,18 @@ +function s = nth(n) + tens = mod(n, 100); + if tens > 9 && tens < 20 + suf = 'th'; + else + switch mod(n, 10) + case 1 + suf = 'st'; + case 2 + suf = 'nd'; + case 3 + suf = 'rd'; + otherwise + suf = 'th'; + end + end + s = sprintf('%d%s', n, suf); +end diff --git a/Task/Nth/Mathematica/nth.math b/Task/Nth/Mathematica/nth.math new file mode 100644 index 0000000000..adfe07e373 --- /dev/null +++ b/Task/Nth/Mathematica/nth.math @@ -0,0 +1,12 @@ +suffixlist = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th","th"}; +addsuffix[n_] := Module[{suffix}, + suffix = Which[ + Mod[n, 100] <= 10, suffixlist[[Mod[n, 10] + 1]], + Mod[n, 100] > 20, suffixlist[[Mod[n, 10] + 1]], + True, "th" + ]; + ToString[n] <> suffix + ] +addsuffix[#] & /@ Range[0, 25] (* test 1 *) +addsuffix[#] & /@ Range[250, 265] (* test 2 *) +addsuffix[#] & /@ Range[1000, 1025] (* test 3 *) diff --git a/Task/Nth/PARI-GP/nth.pari b/Task/Nth/PARI-GP/nth.pari new file mode 100644 index 0000000000..4f18ba0b63 --- /dev/null +++ b/Task/Nth/PARI-GP/nth.pari @@ -0,0 +1,5 @@ +ordinal(n)=my(k=n%10,m=n%100); Str(n,if(m<21&&m>3,"th",k==1,"st",k==2,"nd",k==3,"rd","th")); +apply(ordinal, [0..25]) +apply(ordinal, [250..265]) +apply(ordinal, [1000..1025]) +apply(ordinal, [111, 1012]) diff --git a/Task/Nth/PHP/nth.php b/Task/Nth/PHP/nth.php new file mode 100644 index 0000000000..6f116fd949 --- /dev/null +++ b/Task/Nth/PHP/nth.php @@ -0,0 +1,25 @@ +function nth($num) { + $os = "th"; + if ($num % 100 <= 10 or $num % 100 > 20) { + switch ($num % 10) { + case 1: + $os = "st"; + break; + case 2: + $os = "nd"; + break; + case 3: + $os = "rd"; + break; + } + } + return $num . $os; +} + +foreach ([[0,25], [250,265], [1000,1025]] as $i) { + while ($i[0] <= $i[1]) { + echo nth($i[0]) . " "; + $i[0]++; + } + echo "\n"; +} diff --git a/Task/Nth/PL-I/nth.pli b/Task/Nth/PL-I/nth.pli new file mode 100644 index 0000000000..31b791ab82 --- /dev/null +++ b/Task/Nth/PL-I/nth.pli @@ -0,0 +1,26 @@ +Nth: procedure options (main); /* 1 June 2014 */ + declare i fixed (10); + + do i = 0 to 25, 250 to 265, 1000 to 1025; + if i = 250 | i = 1000 then put skip (2); + put edit (enth(i)) (x(1), a); + end; + +enth: procedure (i) returns (character (25) varying); + declare i fixed (10); + declare suffix character (2); + + select (mod(i, 10)); + when (1) suffix = 'st'; + when (2) suffix = 'nd'; + when (3) suffix = 'rd'; + otherwise suffix = 'th'; + end; + select (mod(i, 100)); + when (11, 12, 13) suffix = 'th'; + otherwise ; + end; + return ( trim(i) || suffix ); +end enth; + +end Nth; diff --git a/Task/Nth/Perl-6/nth-1.pl6 b/Task/Nth/Perl-6/nth-1.pl6 new file mode 100644 index 0000000000..f5d860e3b7 --- /dev/null +++ b/Task/Nth/Perl-6/nth-1.pl6 @@ -0,0 +1,5 @@ +my %irregulars = <1 st 2 nd 3 rd>, (11..13 X=> 'th'); + +sub nth ($n) { $n ~ ( %irregulars{$n % 100} // %irregulars{$n % 10} // 'th' ) } + +say .list».&nth for [^26], [250..265], [1000..1025]; diff --git a/Task/Nth/Perl-6/nth-2.pl6 b/Task/Nth/Perl-6/nth-2.pl6 new file mode 100644 index 0000000000..c8ac7e8ca8 --- /dev/null +++ b/Task/Nth/Perl-6/nth-2.pl6 @@ -0,0 +1,5 @@ +my %irregulars = <1 ˢᵗ 2 ⁿᵈ 3 ʳᵈ>, (11..13 X=> 'ᵗʰ'); + +sub nth ($n) { $n ~ ( %irregulars{$n % 100} // %irregulars{$n % 10} // 'ᵗʰ' ) } + +say .list».&nth for [^26], [250..265], [1000..1025]; diff --git a/Task/Nth/Perl/nth-1.pl b/Task/Nth/Perl/nth-1.pl new file mode 100644 index 0000000000..81905d48f3 --- /dev/null +++ b/Task/Nth/Perl/nth-1.pl @@ -0,0 +1,15 @@ +my %irregulars = ( 1 => 'st', + 2 => 'nd', + 3 => 'rd', + 11 => 'th', + 12 => 'th', + 13 => 'th'); +sub nth +{ + my $n = shift; + $n . # q(') . # Uncomment this to add apostrophes to output + ($irregulars{$n % 100} // $irregulars{$n % 10} // 'th'); +} + +sub range { join ' ', map { nth($_) } @{$_[0]} } +print range($_), "\n" for ([0..25], [250..265], [1000..1025]); diff --git a/Task/Nth/Perl/nth-2.pl b/Task/Nth/Perl/nth-2.pl new file mode 100644 index 0000000000..bfc80e7319 --- /dev/null +++ b/Task/Nth/Perl/nth-2.pl @@ -0,0 +1,4 @@ +use Lingua::EN::Numbers::Ordinate 'ordinate'; +foreach my $i (0..25, 250..265, 1000..1025) { + print ordinate($i),"\n"; +} diff --git a/Task/Nth/PicoLisp/nth.l b/Task/Nth/PicoLisp/nth.l new file mode 100644 index 0000000000..f78d3e7959 --- /dev/null +++ b/Task/Nth/PicoLisp/nth.l @@ -0,0 +1,18 @@ +(de rangeth (A B) + (mapcar + '((I) + (pack I + (if (member (% I 100) (11 12 13)) + 'th + (case (% I 10) + (1 'st) + (2 'nd) + (3 'rd) + (T 'th) ) ) ) ) + (range A B) ) ) + +(prinl (glue " " (rangeth 0 25))) +(prinl (glue " " (rangeth 250 265))) +(prinl (glue " " (rangeth 1000 1025))) + +(bye) diff --git a/Task/Nth/Prolog/nth.pro b/Task/Nth/Prolog/nth.pro new file mode 100644 index 0000000000..e87fbce0a5 --- /dev/null +++ b/Task/Nth/Prolog/nth.pro @@ -0,0 +1,16 @@ +nth(N, N_Th) :- + ( tween(N) -> Th = "th" + ; 1 is N mod 10 -> Th = "st" + ; 2 is N mod 10 -> Th = "nd" + ; 3 is N mod 10 -> Th = "rd" + ; Th = "th" ), + string_concat(N, Th, N_Th). + +tween(N) :- Tween is N mod 100, between(11, 13, Tween). + +test :- + forall( between(0,25, N), (nth(N, N_Th), format('~w, ', N_Th)) ), + nl, nl, + forall( between(250,265,N), (nth(N, N_Th), format('~w, ', N_Th)) ), + nl, nl, + forall( between(1000,1025,N), (nth(N, N_Th), format('~w, ', N_Th)) ). diff --git a/Task/Nth/Python/nth.py b/Task/Nth/Python/nth.py new file mode 100644 index 0000000000..0925ae04ee --- /dev/null +++ b/Task/Nth/Python/nth.py @@ -0,0 +1,8 @@ +_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'] + +def nth(n): + return "%i'%s" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th') + +if __name__ == '__main__': + for j in range(0,1001, 250): + print(' '.join(nth(i) for i in list(range(j, j+25)))) diff --git a/Task/Nth/R/nth.r b/Task/Nth/R/nth.r new file mode 100644 index 0000000000..5722ce2fc3 --- /dev/null +++ b/Task/Nth/R/nth.r @@ -0,0 +1,18 @@ +nth <- function(n) +{ + if (length(n) > 1) return(sapply(n, nth)) + + mod <- function(m, n) ifelse(!(m%%n), n, m%%n) + suffices <- c("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th") + + if (n %% 100 <= 10 || n %% 100 > 20) + suffix <- suffices[mod(n+1, 10)] + else + suffix <- 'th' + + paste(n, "'", suffix, sep="") +} + +range <- list(0:25, 250:275, 500:525, 750:775, 1000:1025) + +sapply(range, nth) diff --git a/Task/Nth/README b/Task/Nth/README new file mode 100644 index 0000000000..33660bad6b --- /dev/null +++ b/Task/Nth/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/N'th diff --git a/Task/Nth/REXX/nth.rexx b/Task/Nth/REXX/nth.rexx new file mode 100644 index 0000000000..79d5dca18e --- /dev/null +++ b/Task/Nth/REXX/nth.rexx @@ -0,0 +1,17 @@ +/*REXX pgm shows ranges of numbers with ordinal (st/nd/rd/th) suffixes.*/ +call tell 0, 25 /*show the 1st range of numbers. */ +call tell 250, 265 /* " " 2nd " " " */ +call tell 1000, 1025 /* " " 3rd " " " */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: procedure; parse arg L,H; $= /*get Low & High #s, nullify list*/ + do j=L to H /*process the range, low───►high.*/ + $=$ j || th(j) /*append the Nth number to list*/ + end /*j*/ /* [↑] $ has a leading blank. */ +say 'numbers from ' L " to " H ' (inclusive):' /*display the title.*/ +say strip($) /*display the list. */ +say /*display blank line*/ +return /*return to invoker.*/ +/*──────────────────────────────────TH subroutine───────────────────────*/ +th: procedure; parse arg x; x=abs(x) /*just use ABS value*/ +return word('th st nd rd', 1 + x//10 * (x//100%10 \== 1) * (x//10 < 4) ) diff --git a/Task/Nth/Racket/nth.rkt b/Task/Nth/Racket/nth.rkt new file mode 100644 index 0000000000..e48b4f2c71 --- /dev/null +++ b/Task/Nth/Racket/nth.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (teen? n) (<= 11 (modulo n 100) 19)) +(define (Nth n) + (format + "~a'~a" n + (match* ((modulo n 10) n) + [((or 1 2 3) (? teen?)) 'th] [(1 _) 'st] [(2 _) 'nd] [(3 _) 'rd] [(_ _) 'th]))) + +(for ((range (list (in-range 26) (in-range 250 266) (in-range 1000 1026)))) + (displayln (string-join (for/list ((nth (sequence-map Nth range))) nth) " "))) diff --git a/Task/Nth/Ruby/nth.rb b/Task/Nth/Ruby/nth.rb new file mode 100644 index 0000000000..343d0c1e89 --- /dev/null +++ b/Task/Nth/Ruby/nth.rb @@ -0,0 +1,18 @@ +class Integer + def ordinalize + num = self.abs + ordinal = if (11..13).include?(num % 100) + "th" + else + case num % 10 + when 1; "st" + when 2; "nd" + when 3; "rd" + else "th" + end + end + "#{self}#{ordinal}" + end +end + +[(0..25),(250..265),(1000..1025)].each{|r| puts r.map(&:ordinalize).join(", "); puts} diff --git a/Task/Nth/Rust/nth.rust b/Task/Nth/Rust/nth.rust new file mode 100644 index 0000000000..68905617d0 --- /dev/null +++ b/Task/Nth/Rust/nth.rust @@ -0,0 +1,26 @@ +fn nth(num: int) -> String { + format!("{}{}", num, match (num % 10, num % 100) { + (1, 11) => "th", + (1, _) => "st", + (2, 12) => "th", + (2, _) => "nd", + (3, 13) => "th", + (3, _) => "rd", + _ => "th" + }) +} + +fn main() { + let ranges = vec![ + (0i, 26i), + (250i, 266i), + (1000i, 1026i) + ]; + for &(s, e) in ranges.iter() { + println!("[{}, {}) :", s, e); + for i in range(s, e) { + print!("{}, ", nth(i)); + } + println!(""); + } +} diff --git a/Task/Nth/Scala/nth.scala b/Task/Nth/Scala/nth.scala new file mode 100644 index 0000000000..01b06a5df4 --- /dev/null +++ b/Task/Nth/Scala/nth.scala @@ -0,0 +1,20 @@ +object Nth extends App { + def abbrevNumber(i: Int) = print(s"$i${ordinalAbbrev(i)} ") + + def ordinalAbbrev(n: Int) = { + val ans = "th" //most of the time it should be "th" + if (n % 100 / 10 == 1) ans //teens are all "th" + else (n % 10) match { + case 1 => "st" + case 2 => "nd" + case 3 => "rd" + case _ => ans + } + } + + (0 to 25).foreach(abbrevNumber) + println() + (250 to 265).foreach(abbrevNumber) + println(); + (1000 to 1025).foreach(abbrevNumber) +} diff --git a/Task/Nth/Seed7/nth.seed7 b/Task/Nth/Seed7/nth.seed7 new file mode 100644 index 0000000000..2978335483 --- /dev/null +++ b/Task/Nth/Seed7/nth.seed7 @@ -0,0 +1,29 @@ +$ include "seed7_05.s7i"; + +const func string: suffix (in integer: num) is func + result + var string: suffix is ""; + begin + if num rem 10 = 1 and num rem 100 <> 11 then suffix := "st"; + elsif num rem 10 = 2 and num rem 100 <> 12 then suffix := "nd"; + elsif num rem 10 = 3 and num rem 100 <> 13 then suffix := "rd"; + else suffix := "th"; + end if; + end func; + +const proc: printImages (in integer: start, in integer: stop) is func + local + var integer: num is 0; + begin + for num range start to stop do + write(num <& suffix(num) <& " "); + end for; + writeln; + end func; + +const proc: main is func + begin + printImages( 0, 25); + printImages( 250, 265); + printImages(1000, 1025); + end func; diff --git a/Task/Nth/Tcl/nth.tcl b/Task/Nth/Tcl/nth.tcl new file mode 100644 index 0000000000..83c0ba28eb --- /dev/null +++ b/Task/Nth/Tcl/nth.tcl @@ -0,0 +1,15 @@ +proc ordinal {n} { + if {$n%100<10 || $n%100>20} { + set suff [lindex {th st nd rd th th th th th th} [expr {$n % 10}]] + } else { + set suff th + } + return "$n'$suff" +} + +foreach start {0 250 1000} { + for {set n $start; set l {}} {$n<=$start+25} {incr n} { + lappend l [ordinal $n] + } + puts $l +} diff --git a/Task/Odd-word-problem/00DESCRIPTION b/Task/Odd-word-problem/00DESCRIPTION new file mode 100644 index 0000000000..4ae9f0f876 --- /dev/null +++ b/Task/Odd-word-problem/00DESCRIPTION @@ -0,0 +1,14 @@ +Write a program that solves the [http://c2.com/cgi/wiki?OddWordProblem odd word problem] with the restrictions given below. + +'''Description''': You are promised an input stream consisting of English letters and punctuations. It is guaranteed that +* the words (sequence of consecutive letters) are delimited by one and only one punctuation; that +* the stream will begin with a word; that +* the words will be at least one letter long; and that +* a full stop (.) appears after, and only after, the last word. + +For example, what,is,the;meaning,of:life. is such a stream with six words. Your task is to reverse the letters in every other word while leaving punctuations intact, producing e.g. "what,si,the;gninaem,of:efil.", while observing the following restrictions: +# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; +# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; +# You '''are''' allowed to use recursions, closures, continuations, threads, coroutines, etc., even if their use implies the storage of multiple characters. + +'''Test case''': work on both the "life" example given above, and the text we,are;not,in,kansas;any,more. diff --git a/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg b/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg new file mode 100644 index 0000000000..8e1260cbd0 --- /dev/null +++ b/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg @@ -0,0 +1,75 @@ +# recursively reverses the current word in the input and returns the # +# the character that followed it # +# "ch" should contain the first letter of the word on entry and will be # +# updated to the punctuation following the word on exit # +PROC reverse word = ( REF CHAR ch )VOID: +BEGIN + + CHAR next ch; + + read( ( next ch ) ); + + IF ( next ch <= "Z" AND next ch >= "A" ) + OR ( next ch <= "z" AND next ch >= "a" ) + THEN + reverse word( next ch ) + FI; + + print( ( ch ) ); + + ch := next ch + +END; # reverse word # + + + +# recursively prints the current word in the input and returns the # +# character that followed it # +# "ch" should contain the first letter of the word on entry and will be # +# updated to the punctuation following the word on exit # +PROC normal word = ( REF CHAR ch )VOID: +BEGIN + + print( ( ch ) ); + read ( ( ch ) ); + + IF ( ch <= "Z" AND ch >= "A" ) + OR ( ch <= "z" AND ch >= "a" ) + THEN + normal word( ch ) + FI + +END; # normal word # + + + +# read and print words and punctuation from the input stream, reversing # +# every second word # +PROC reverse every other word = VOID: +BEGIN + + CHAR ch; + + read( ( ch ) ); + + WHILE + ch /= "." + DO + normal word( ch ); + IF ch /= "." + THEN + print( ( ch ) ); + read ( ( ch ) ); + reverse word( ch ) + FI + OD; + + print( ( ch ) ) + +END; # reverse every other word # + + + +main: ( + reverse every other word +) diff --git a/Task/Odd-word-problem/Ada/odd-word-problem.ada b/Task/Odd-word-problem/Ada/odd-word-problem.ada new file mode 100644 index 0000000000..3eda582675 --- /dev/null +++ b/Task/Odd-word-problem/Ada/odd-word-problem.ada @@ -0,0 +1,55 @@ +with Ada.Text_IO; + +procedure Odd_Word_Problem is + + use Ada.Text_IO; -- Get, Put, and Look_Ahead + + function Current return Character is + -- reads the current input character, without consuming it + End_Of_Line: Boolean; + C: Character; + begin + Look_Ahead(C, End_Of_Line); + if End_Of_Line then + raise Constraint_Error with "end of line before the terminating '.'"; + end if; + return C; + end Current; + + procedure Skip is + -- consumes the current input character + C: Character; + begin + Get(C); + end Skip; + + function Is_Alpha(Ch: Character) return Boolean is + begin + return (Ch in 'a' .. 'z') or (Ch in 'A' .. 'Z'); + end Is_Alpha; + + procedure Odd_Word(C: Character) is + begin + if Is_Alpha(C) then + Skip; + Odd_Word(Current); + Put(C); + end if; + end Odd_Word; + +begin -- Odd_Word_Problem + Put(Current); + while Is_Alpha(Current) loop -- read an even word + Skip; + Put(Current); + end loop; + if Current /= '.' then -- read an odd word + Skip; + Odd_Word(Current); + Put(Current); + if Current /= '.' then -- read the remaining words + Skip; + Odd_Word_Problem; + end if; + end if; +end Odd_Word_Problem; diff --git a/Task/Odd-word-problem/Bracmat/odd-word-problem.bracmat b/Task/Odd-word-problem/Bracmat/odd-word-problem.bracmat new file mode 100644 index 0000000000..2add3bf7d7 --- /dev/null +++ b/Task/Odd-word-problem/Bracmat/odd-word-problem.bracmat @@ -0,0 +1,33 @@ +( ( odd-word + = dothis doother forward backward + . ( forward + = ch + . fil$:?ch + & put$!ch + & ( low$!ch:~z&forward$ + | !ch:~"." + ) + ) + & ( backward + = ch + . fil$:?ch + & ( low$!ch:~z + & backward$() (put$!ch&) { This reduces to the return value of backwards$()} + | '(.put$($ch)&$ch:~".") { Macro, evaluates to a function with actual ch. } + ) + ) + & fil$(!arg,r) + & ((=forward$).(=(backward$)$)) + : (?dothis.?doother) + & whl + ' ( !(dothis.) + & (!doother.!dothis):(?dothis.?doother) + ) + & (fil$(,SET,-1)|) { This is how a file is closed: seek the impossible. } + ) +& put$("what,is,the;meaning,of:life.","life.txt",NEW) +& put$("we,are;not,in,kansas;any,more.","kansas.txt",NEW) +& odd-word$"life.txt" +& put$\n +& odd-word$"kansas.txt" { Real file, as Bracmat cannot read a single character from stdin. } +); diff --git a/Task/Odd-word-problem/C++/odd-word-problem.cpp b/Task/Odd-word-problem/C++/odd-word-problem.cpp new file mode 100644 index 0000000000..b28c96afcc --- /dev/null +++ b/Task/Odd-word-problem/C++/odd-word-problem.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +using namespace std; + +bool odd() +{ + function prev = []{}; + while(true) { + int c = cin.get(); + if (!isalpha(c)) { + prev(); + cout.put(c); + return c != '.'; + } + prev = [=] { cout.put(c); prev(); }; + } +} + +bool even() +{ + while(true) { + int c; + cout.put(c = cin.get()); + if (!isalpha(c)) return c != '.'; + } +} + + +int main() +{ + bool e = false; + while( e ? odd() : even() ) e = !e; + return 0; +} diff --git a/Task/Odd-word-problem/C/odd-word-problem.c b/Task/Odd-word-problem/C/odd-word-problem.c new file mode 100644 index 0000000000..f54377eafc --- /dev/null +++ b/Task/Odd-word-problem/C/odd-word-problem.c @@ -0,0 +1,32 @@ +#include +#include + +int do_char(int odd, void (*f)(void)) +{ + int c = getchar(); + + void write_out(void) { + putchar(c); + if (f) f(); + } + + if (!odd) putchar(c); + + if (isalpha(c)) + return do_char(odd, write_out); + + if (odd) { + if (f) f(); + putchar(c); + } + + return c != '.'; +} + +int main() +{ + int i = 1; + while (do_char(i = !i, 0)); + + return 0; +} diff --git a/Task/Odd-word-problem/Clojure/odd-word-problem-1.clj b/Task/Odd-word-problem/Clojure/odd-word-problem-1.clj new file mode 100644 index 0000000000..a2fe657df5 --- /dev/null +++ b/Task/Odd-word-problem/Clojure/odd-word-problem-1.clj @@ -0,0 +1,26 @@ +(defn next-char [] + (char (.read *in*))) + +(defn forward [] + (let [ch (next-char)] + (print ch) + (if (Character/isLetter ch) + (forward) + (not= ch \.)))) + +(defn backward [] + (let [ch (next-char)] + (if (Character/isLetter ch) + (let [result (backward)] + (print ch) + result) + (fn [] (print ch) (not= ch \.)))) ) + +(defn odd-word [s] + (with-in-str s + (loop [forward? true] + (when (if forward? + (forward) + ((backward))) + (recur (not forward?)))) ) + (println)) diff --git a/Task/Odd-word-problem/Clojure/odd-word-problem-2.clj b/Task/Odd-word-problem/Clojure/odd-word-problem-2.clj new file mode 100644 index 0000000000..d85c713993 --- /dev/null +++ b/Task/Odd-word-problem/Clojure/odd-word-problem-2.clj @@ -0,0 +1,6 @@ +user=> (odd-word "what,is,the;meaning,of:life.") +what,si,the;gninaem,of:efil. +nil +user=> (odd-word "we,are;not,in,kansas;any,more.") +we,era;not,ni,kansas;yna,more. +nil diff --git a/Task/Odd-word-problem/CoffeeScript/odd-word-problem-1.coffee b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-1.coffee new file mode 100644 index 0000000000..4b1175d85c --- /dev/null +++ b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-1.coffee @@ -0,0 +1,36 @@ +isWordChar = (c) -> /^\w/.test c +isLastChar = (c) -> c is '.' + +# Pass a function that returns an input character and one that outputs a +# character. JS platforms' ideas of single-character I/O vary widely, but this +# abstraction is adaptable to most or all. +oddWord = (get, put) -> + forwardWord = -> + loop + # No magic here; buffer then immediately output. + c = get() + put(c) + unless isWordChar(c) + return not isLastChar(c) + + # NB: (->) is a CoffeeScript idiom for no-op. + reverseWord = (outputPending = (->)) -> + c = get() + if isWordChar(c) + # Continue word. + # Tell recursive call to output this character, then any previously + # pending characters, after the next word character, if any, has + # been output. + reverseWord -> + put(c) + outputPending() + else + # Word is done. + # Output previously pending characters, then this punctuation. + outputPending() + put(c) + return not isLastChar(c) + + # Alternate between forward and reverse until one or the other reports that + # the end-of-input mark has been reached (causing a return of false). + continue while forwardWord() and reverseWord() diff --git a/Task/Odd-word-problem/CoffeeScript/odd-word-problem-2.coffee b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-2.coffee new file mode 100644 index 0000000000..0f4aef78cd --- /dev/null +++ b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-2.coffee @@ -0,0 +1,23 @@ +isWordChar = (c) -> /^\w/.test c +isLastChar = (c) -> c is '.' + +oddWord = (get, put) -> + forwardWord = -> + loop + c = get() + put(c) + unless isWordChar(c) + return not isLastChar(c) + + reverseWord = (outputPending = (->)) -> + c = get() + if isWordChar(c) + reverseWord -> + put(c) + outputPending() + else + outputPending() + put(c) + return not isLastChar(c) + + continue while forwardWord() and reverseWord() diff --git a/Task/Odd-word-problem/CoffeeScript/odd-word-problem-3.coffee b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-3.coffee new file mode 100644 index 0000000000..59fbae3309 --- /dev/null +++ b/Task/Odd-word-problem/CoffeeScript/odd-word-problem-3.coffee @@ -0,0 +1,27 @@ +# Redefine as necessary for target platform. +println = (z) -> console.log z + +testData = [ + [ + "what,is,the;meaning,of:life." + "what,si,the;gninaem,of:efil." + ] + [ + "we,are;not,in,kansas;any,more." + "we,era;not,ni,kansas;yna,more." + ] +] + +results = for [testString, expectedResult] in testData + # This test machinery uses string buffers for input and output. If your JS + # platform sports single-character I/O, by all means, adapt to taste. + getCursor = 0 + putBuffer = "" + get = -> + testString.charAt getCursor++ + put = (c) -> + putBuffer += c + oddWord(get,put) + [testString, expectedResult, putBuffer, putBuffer is expectedResult] + +println result for result in results diff --git a/Task/Odd-word-problem/Common-Lisp/odd-word-problem-1.lisp b/Task/Odd-word-problem/Common-Lisp/odd-word-problem-1.lisp new file mode 100644 index 0000000000..5cb8daec2f --- /dev/null +++ b/Task/Odd-word-problem/Common-Lisp/odd-word-problem-1.lisp @@ -0,0 +1,19 @@ +(defun odd-word (s) + (let ((stream (make-string-input-stream s))) + (loop for forwardp = t then (not forwardp) + while (if forwardp + (forward stream) + (funcall (backward stream)))) )) + +(defun forward (stream) + (let ((ch (read-char stream))) + (write-char ch) + (if (alpha-char-p ch) + (forward stream) + (char/= ch #\.)))) + +(defun backward (stream) + (let ((ch (read-char stream))) + (if (alpha-char-p ch) + (prog1 (backward stream) (write-char ch)) + #'(lambda () (write-char ch) (char/= ch #\.)))) ) diff --git a/Task/Odd-word-problem/Common-Lisp/odd-word-problem-2.lisp b/Task/Odd-word-problem/Common-Lisp/odd-word-problem-2.lisp new file mode 100644 index 0000000000..213a6c79e9 --- /dev/null +++ b/Task/Odd-word-problem/Common-Lisp/odd-word-problem-2.lisp @@ -0,0 +1,6 @@ +? (odd-word "what,is,the;meaning,of:life.") +what,si,the;gninaem,of:efil. +NIL +? (odd-word "we,are;not,in,kansas;any,more.") +we,era;not,ni,kansas;yna,more. +NIL diff --git a/Task/Odd-word-problem/D/odd-word-problem.d b/Task/Odd-word-problem/D/odd-word-problem.d new file mode 100644 index 0000000000..ae0ff8647f --- /dev/null +++ b/Task/Odd-word-problem/D/odd-word-problem.d @@ -0,0 +1,19 @@ +bool doChar(in bool odd, in void delegate() nothrow f=null) nothrow { + import core.stdc.stdio, std.ascii; + + immutable int c = getchar; + if (!odd) + c.putchar; + if (c.isAlpha) + return doChar(odd, { c.putchar; if (f) f(); }); + if (odd) { + if (f) f(); + c.putchar; + } + return c != '.'; +} + +void main() { + bool i = true; + while (doChar(i = !i)) {} +} diff --git a/Task/Odd-word-problem/Erlang/odd-word-problem.erl b/Task/Odd-word-problem/Erlang/odd-word-problem.erl new file mode 100644 index 0000000000..967929d404 --- /dev/null +++ b/Task/Odd-word-problem/Erlang/odd-word-problem.erl @@ -0,0 +1,16 @@ +handle(S, false, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) -> + O(S), + handle(I(), false, I, O); +handle(S, T, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) -> + D = handle(I(), rec, I, O), + O(S), + case T of true -> handle(D, T, I, O); _ -> D end; +handle(S, rec, _, _) -> S; +handle($., _, _, O) -> O($.), done; +handle(eof, _, _, _) -> done; +handle(S, T, I, O) -> O(S), handle(I(), not T, I, O). + +main([]) -> + I = fun() -> hd(io:get_chars([], 1)) end, + O = fun(S) -> io:put_chars([S]) end, + handle(I(), false, I, O). diff --git a/Task/Odd-word-problem/FALSE/odd-word-problem.false b/Task/Odd-word-problem/FALSE/odd-word-problem.false new file mode 100644 index 0000000000..b0fdcfc4a9 --- /dev/null +++ b/Task/Odd-word-problem/FALSE/odd-word-problem.false @@ -0,0 +1,4 @@ +[$$$$'.=\',=|\';=|\':=|~[^s;!\,]?]s: {recursive reading} +[s;!$'.=~[,^f;!]?]r: {reverse words} +[[$$$$'.=\',=|\';=|\':=|~][,^]#$'.=~[,^r;!]?]f: {forward words} +^f;!, {start} diff --git a/Task/Odd-word-problem/Factor/odd-word-problem.factor b/Task/Odd-word-problem/Factor/odd-word-problem.factor new file mode 100644 index 0000000000..d88df9c9ad --- /dev/null +++ b/Task/Odd-word-problem/Factor/odd-word-problem.factor @@ -0,0 +1,62 @@ +USING: continuations kernel io io.streams.string locals unicode.categories ; +IN: rosetta.odd-word + + + +:: read-odd-word ( -- ) + f :> first-continuation! + f :> last-continuation! + f :> reverse! + ! Read characters. Loop until end of stream. + [ read1 dup ] [ + dup Letter? [ + ! This character is a letter. + reverse [ + ! Odd word: Write letters in reverse order. + last-continuation savecc dup [ + last-continuation! + 2drop ! Drop letter and previous continuation. + ] [ + ! After jump: print letters in reverse. + drop ! Drop f. + swap write1 ! Write letter. + jump-back ! Follow chain of continuations. + ] if + ] [ + ! Even word: Write letters immediately. + write1 + ] if + ] [ + ! This character is punctuation. + reverse [ + ! End odd word. Fix trampoline, follow chain of continuations + ! (to print letters in reverse), then bounce off trampoline. + savecc dup [ + first-continuation! + last-continuation jump-back + ] [ drop ] if + write1 ! Write punctuation. + f reverse! ! Begin even word. + ] [ + write1 ! Write punctuation. + t reverse! ! Begin odd word. + ! Create trampoline to bounce to (future) first-continuation. + savecc dup [ + last-continuation! + ] [ drop first-continuation jump-back ] if + ] if + ] if + ] while + ! Drop f from read1. Then print a cosmetic newline. + drop nl ; + +: odd-word ( string -- ) + [ read-odd-word ] with-string-reader ; diff --git a/Task/Odd-word-problem/Forth/odd-word-problem.fth b/Task/Odd-word-problem/Forth/odd-word-problem.fth new file mode 100644 index 0000000000..607154a585 --- /dev/null +++ b/Task/Odd-word-problem/Forth/odd-word-problem.fth @@ -0,0 +1,6 @@ +: word? dup [char] . <> over bl <> and ; +: ?quit dup [char] . = if emit quit then ; +: eatbl begin dup bl = while drop key repeat ?quit ; +: even begin word? while emit key repeat ; +: odd word? if key recurse swap emit then ; +: main cr key eatbl begin even eatbl space odd eatbl space again ; diff --git a/Task/Odd-word-problem/Go/odd-word-problem-1.go b/Task/Odd-word-problem/Go/odd-word-problem-1.go new file mode 100644 index 0000000000..1e13b7a926 --- /dev/null +++ b/Task/Odd-word-problem/Go/odd-word-problem-1.go @@ -0,0 +1,52 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "os" + "unicode" +) + +func main() { + owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) + fmt.Println() + owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) + fmt.Println() +} + +func owp(dst io.Writer, src io.Reader) { + byte_in := func () byte { + bs := make([]byte, 1) + src.Read(bs) + return bs[0] + } + byte_out := func (b byte) { dst.Write([]byte{b}) } + var odd func() byte + odd = func() byte { + s := byte_in() + if unicode.IsPunct(rune(s)) { + return s + } + b := odd() + byte_out(s) + return b + } + for { + for { + b := byte_in() + byte_out(b) + if b == '.' { + return + } + if unicode.IsPunct(rune(b)) { + break + } + } + b := odd() + byte_out(b) + if b == '.' { + return + } + } +} diff --git a/Task/Odd-word-problem/Go/odd-word-problem-2.go b/Task/Odd-word-problem/Go/odd-word-problem-2.go new file mode 100644 index 0000000000..b7946a76d7 --- /dev/null +++ b/Task/Odd-word-problem/Go/odd-word-problem-2.go @@ -0,0 +1,52 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "os" + "unicode" +) + +func main() { + owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) + fmt.Println() + owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) + fmt.Println() +} + +func owp(dst io.Writer, src io.Reader) { + byte_in := func () byte { + bs := make([]byte, 1) + src.Read(bs) + return bs[0] + } + byte_out := func (b byte) { dst.Write([]byte{b}) } + odd := func() byte { + for { + b := byte_in() + if unicode.IsPunct(int(b)) { + return b + } + defer byte_out(b) + } + panic("impossible") + } + for { + for { + b := byte_in() + byte_out(b) + if b == '.' { + return + } + if unicode.IsPunct(rune(b)) { + break + } + } + b := odd() + byte_out(b) + if b == '.' { + return + } + } +} diff --git a/Task/Odd-word-problem/Go/odd-word-problem-3.go b/Task/Odd-word-problem/Go/odd-word-problem-3.go new file mode 100644 index 0000000000..3692eb0a7f --- /dev/null +++ b/Task/Odd-word-problem/Go/odd-word-problem-3.go @@ -0,0 +1,89 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "os" + "unicode" +) + +func main() { + owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) + fmt.Println() + owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) + fmt.Println() +} + +type Coroutine struct { + out <-chan Coroutine + in chan<- byte +} + +func owp(dst io.Writer, src io.Reader) { + byte_in := func () (byte, error) { + bs := make([]byte, 1) + _, err := src.Read(bs) + return bs[0], err + } + byte_out := func (b byte) { dst.Write([]byte{b}) } + + var f, r Coroutine + + f = func () Coroutine { + out := make(chan Coroutine) + in := make(chan byte) + var fwd func (byte) byte + fwd = func (c byte) (z byte) { + if unicode.IsLetter(rune(c)) { + byte_out(c) + out <- f + z = fwd(<- in) + } else { + z = c + } + return + } + go func () { + for { + x, ok := <- in + if !ok { break } + byte_out(fwd(x)) + out <- r + } + } () + return Coroutine{ out, in } + } () + r = func () Coroutine { + out := make(chan Coroutine) + in := make(chan byte) + var rev func (byte) byte + rev = func (c byte) (z byte) { + if unicode.IsLetter(rune(c)) { + out <- r + z = rev(<- in) + byte_out(c) + } else { + z = c + } + return + } + go func () { + for { + x, ok := <- in + if !ok { break } + byte_out(rev(x)) + out <- f + } + } () + return Coroutine{ out, in } + } () + + for coro := f; ; coro = <- coro.out { + c, err := byte_in() + if err != nil { break } + coro.in <- c + } + close(f.in) + close(r.in) +} diff --git a/Task/Odd-word-problem/Haskell/odd-word-problem-1.hs b/Task/Odd-word-problem/Haskell/odd-word-problem-1.hs new file mode 100644 index 0000000000..4b9af060f6 --- /dev/null +++ b/Task/Odd-word-problem/Haskell/odd-word-problem-1.hs @@ -0,0 +1,20 @@ +import System.IO + +isAlpha :: Char -> Bool +isAlpha = flip elem $ ['a'..'z'] ++ ['A'..'Z'] + +split :: String -> (String, String) +split = break $ not . isAlpha + +parse :: String -> String +parse [] = [] +parse l = + let (a, w) = split l + (b, x) = splitAt 1 w + (c, y) = split x + (d, z) = splitAt 1 y + in a ++ b ++ reverse c ++ d ++ parse z + +main :: IO () +main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> + getContents >>= putStr . (takeWhile (/= '.')) . parse >> putStrLn "." diff --git a/Task/Odd-word-problem/Haskell/odd-word-problem-2.hs b/Task/Odd-word-problem/Haskell/odd-word-problem-2.hs new file mode 100644 index 0000000000..573b02877a --- /dev/null +++ b/Task/Odd-word-problem/Haskell/odd-word-problem-2.hs @@ -0,0 +1,31 @@ +isAlpha :: Char -> Bool +isAlpha = flip elem $ ['a'..'z'] ++ ['A'..'Z'] + +parse :: IO () +parse = do + x <- getChar + putChar x + case () of + _ | x == '.' -> return () + | isAlpha x -> parse + | otherwise -> do + c <- revParse + putChar c + if c == '.' + then return () + else parse + +revParse :: IO Char +revParse = do + x <- getChar + case () of + _ | x == '.' -> return x + | isAlpha x -> do + c <- revParse + putChar x + return c + | otherwise -> return x + +main :: IO () +main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> + parse >> putStrLn "" diff --git a/Task/Odd-word-problem/Icon/odd-word-problem-1.icon b/Task/Odd-word-problem/Icon/odd-word-problem-1.icon new file mode 100644 index 0000000000..1d8da52440 --- /dev/null +++ b/Task/Odd-word-problem/Icon/odd-word-problem-1.icon @@ -0,0 +1,22 @@ +procedure main() +every OddWord(!["what,is,the;meaning,of:life.", + "we,are;not,in,kansas;any,more."]) +end + +procedure OddWord(stream) #: wrapper for demonstration + write("Input stream: ",stream) + writes("Output stream: ") & eWord(create !stream,'.,;:') & write() +end + +procedure eWord(stream,marks) #: handle even words + repeat { + repeat + writes(@stream) ? if ="." then return else if any(marks) then break + if writes(oWord(stream,marks)) == '.' then return + } +end + +procedure oWord(stream,marks) #: handle odd words (reverse) + if any(marks,s := @stream) then return s + return 1(oWord(stream,marks), writes(s)) +end diff --git a/Task/Odd-word-problem/Icon/odd-word-problem-2.icon b/Task/Odd-word-problem/Icon/odd-word-problem-2.icon new file mode 100644 index 0000000000..7628b31362 --- /dev/null +++ b/Task/Odd-word-problem/Icon/odd-word-problem-2.icon @@ -0,0 +1,10 @@ +procedure main(A) + repeat (while writes((any(&letters, c := reads(&input,1)),c))) | + (writes(c) ~== "." ~== writes(rWord())) | break write() +end + +procedure rWord(c) + c1 := rWord((any(&letters, c1 := reads(&input,1)),c1)) + writes(\c) + return c1 +end diff --git a/Task/Odd-word-problem/J/odd-word-problem-1.j b/Task/Odd-word-problem/J/odd-word-problem-1.j new file mode 100644 index 0000000000..fcfb4380cd --- /dev/null +++ b/Task/Odd-word-problem/J/odd-word-problem-1.j @@ -0,0 +1,26 @@ +putch=: 4 :0 NB. coroutine verb + outch y + return x +) + +isletter=: toupper ~: tolower + +do_char=: 3 :0 NB. coroutine verb + ch=. getch'' + if. isletter ch do. + if. odd do. + putch&ch yield do_char '' return. + end. + else. + odd=: -. odd + end. + return ch +) + +evenodd=: 3 :0 + clear_outstream begin_instream y + odd=: 0 + whilst. '.'~:char do. + outch char=. do_char coroutine '' + end. +) diff --git a/Task/Odd-word-problem/J/odd-word-problem-2.j b/Task/Odd-word-problem/J/odd-word-problem-2.j new file mode 100644 index 0000000000..b60be3776e --- /dev/null +++ b/Task/Odd-word-problem/J/odd-word-problem-2.j @@ -0,0 +1,4 @@ + evenodd 'what,is,the;meaning,of:life.' +what,si,the;gninaem,of:efil. + evenodd 'we,are;not,in,kansas;any,more.' +we,era;not,ni,kansas;yna,more. diff --git a/Task/Odd-word-problem/Java/odd-word-problem.java b/Task/Odd-word-problem/Java/odd-word-problem.java new file mode 100644 index 0000000000..31bb11e16f --- /dev/null +++ b/Task/Odd-word-problem/Java/odd-word-problem.java @@ -0,0 +1,57 @@ +public class OddWord { + interface CharHandler { + CharHandler handle(char c) throws Exception; + } + final CharHandler fwd = new CharHandler() { + public CharHandler handle(char c) { + System.out.print(c); + return (Character.isLetter(c) ? fwd : rev); + } + }; + class Reverser extends Thread implements CharHandler { + Reverser() { + setDaemon(true); + start(); + } + private Character ch; // For inter-thread comms + private char recur() throws Exception { + notify(); + while (ch == null) wait(); + char c = ch, ret = c; + ch = null; + if (Character.isLetter(c)) { + ret = recur(); + System.out.print(c); + } + return ret; + } + public synchronized void run() { + try { + while (true) { + System.out.print(recur()); + notify(); + } + } catch (Exception e) {} + } + public synchronized CharHandler handle(char c) throws Exception { + while (ch != null) wait(); + ch = c; + notify(); + while (ch != null) wait(); + return (Character.isLetter(c) ? rev : fwd); + } + } + final CharHandler rev = new Reverser(); + + public void loop() throws Exception { + CharHandler handler = fwd; + int c; + while ((c = System.in.read()) >= 0) { + handler = handler.handle((char) c); + } + } + + public static void main(String[] args) throws Exception { + new OddWord().loop(); + } +} diff --git a/Task/Odd-word-problem/OCaml/odd-word-problem.ocaml b/Task/Odd-word-problem/OCaml/odd-word-problem.ocaml new file mode 100644 index 0000000000..09fc99bac8 --- /dev/null +++ b/Task/Odd-word-problem/OCaml/odd-word-problem.ocaml @@ -0,0 +1,25 @@ +let is_alpha c = + c >= 'a' && c <= 'z' || + c >= 'A' && c <= 'Z' + +let rec odd () = + let c = input_char stdin in + if is_alpha c + then (let e = odd () in print_char c; e) + else (c) + +let rec even () = + let c = input_char stdin in + if is_alpha c + then (print_char c; even ()) + else print_char c + +let rev_odd_words () = + while true do + even (); + print_char (odd ()) + done + +let () = + try rev_odd_words () + with End_of_file -> () diff --git a/Task/Odd-word-problem/PHP/odd-word-problem.php b/Task/Odd-word-problem/PHP/odd-word-problem.php new file mode 100644 index 0000000000..3476009715 --- /dev/null +++ b/Task/Odd-word-problem/PHP/odd-word-problem.php @@ -0,0 +1,27 @@ +$odd = function ($prev) use ( &$odd ) { + $a = fgetc(STDIN); + if (!ctype_alpha($a)) { + $prev(); + fwrite(STDOUT, $a); + return $a != '.'; + } + $clos = function () use ($a , $prev) { + fwrite(STDOUT, $a); + $prev(); + }; + return $odd($clos); +}; +$even = function () { + while (true) { + $c = fgetc(STDIN); + fwrite(STDOUT, $c); + if (!ctype_alpha($c)) { + return $c != "."; + } + } +}; +$prev = function(){}; +$e = false; +while ($e ? $odd($prev) : $even()) { + $e = !$e; +} diff --git a/Task/Odd-word-problem/PL-I/odd-word-problem.pli b/Task/Odd-word-problem/PL-I/odd-word-problem.pli new file mode 100644 index 0000000000..4065a8356c --- /dev/null +++ b/Task/Odd-word-problem/PL-I/odd-word-problem.pli @@ -0,0 +1,25 @@ +test: procedure options (main); /* 2 August 2014 */ + declare (ch, ech) character (1); + declare odd file; + +get_word: procedure recursive; + declare ch character (1); + + get file (odd) edit (ch) (a(1)); + if index('abcdefghijklmnopqrstuvwxyz', ch) > 0 then call get_word; + if index('abcdefghijklmnopqrstuvwxyz', ch) > 0 then + put edit (ch) (a); + else ech = ch; +end get_word; + + open file (odd) input title ('/ODDWORD.DAT,TYPE(text),recsize(100)'); + do forever; + do until (index('abcdefghijklmnopqrstuvwxyz', ch) = 0 ); + get file (odd) edit (ch) (a(1)); put edit (ch) (a); + end; + if ch = '.' then leave; + call get_word; + put edit (ech) (a); + if ech = '.' then leave; + end; +end test; diff --git a/Task/Odd-word-problem/Perl-6/odd-word-problem.pl6 b/Task/Odd-word-problem/Perl-6/odd-word-problem.pl6 new file mode 100644 index 0000000000..719030ded3 --- /dev/null +++ b/Task/Odd-word-problem/Perl-6/odd-word-problem.pl6 @@ -0,0 +1,12 @@ +my &in = { $*IN.getc // last } + +loop { + ew(in); + ow(in).print; +} + +multi ew ($_ where /\w/) { .print; ew(in); } +multi ew ($_) { .print; next when "\n"; } + +multi ow ($_ where /\w/) { ow(in) x .print; } +multi ow ($_) { $_; } diff --git a/Task/Odd-word-problem/Perl/odd-word-problem-1.pl b/Task/Odd-word-problem/Perl/odd-word-problem-1.pl new file mode 100644 index 0000000000..ec657a138f --- /dev/null +++ b/Task/Odd-word-problem/Perl/odd-word-problem-1.pl @@ -0,0 +1,20 @@ +sub r +{ + my ($f, $c) = @_; + return sub { print $c; $f->(); }; +} + +$r = sub {}; + +while (read STDIN, $_, 1) { + $w = /^[a-zA-Z]$/; + $n++ if ($w && !$l); + $l = $w; + if ($n & 1 || !$w) { + $r->(); $r = sub{}; + print; + } else { + $r = r($r, $_); + } +} +$r->(); diff --git a/Task/Odd-word-problem/Perl/odd-word-problem-2.pl b/Task/Odd-word-problem/Perl/odd-word-problem-2.pl new file mode 100644 index 0000000000..9d95376814 --- /dev/null +++ b/Task/Odd-word-problem/Perl/odd-word-problem-2.pl @@ -0,0 +1,26 @@ +sub rev +{ + my $c; + read STDIN, $c, 1; + if ($c =~ /^[a-zA-Z]$/) { + my $r = rev(); + print $c; + return $r; + } else { + return $c; + } +} + +while (read STDIN, $_, 1) { + $w = /^[a-zA-Z]$/; + $n++ if ($w && !$l); + $l = $w; + if ($n & 1) { + print; + } else { + my $r = rev(); + print $_; + print $r; + $n = 0; $l = 0; + } +} diff --git a/Task/Odd-word-problem/Perl/odd-word-problem-3.pl b/Task/Odd-word-problem/Perl/odd-word-problem-3.pl new file mode 100644 index 0000000000..b7b3b515bc --- /dev/null +++ b/Task/Odd-word-problem/Perl/odd-word-problem-3.pl @@ -0,0 +1,24 @@ +$|=1; + +while (read STDIN, $_, 1) { + $w = /^[a-zA-Z]$/; + $n++ if ($w && !$l); + $l = $w; + if ($n & 1 || !$w) { + close W; while(wait()!=-1){} + print; + } else { + open W0, ">&", \*W; + close W; + pipe R,W; + if (!fork()) { + close W; + ; + print $_; + close W0; + exit; + } + close W0; + close R; + } +} diff --git a/Task/Odd-word-problem/PicoLisp/odd-word-problem-1.l b/Task/Odd-word-problem/PicoLisp/odd-word-problem-1.l new file mode 100644 index 0000000000..2fbe37ca20 --- /dev/null +++ b/Task/Odd-word-problem/PicoLisp/odd-word-problem-1.l @@ -0,0 +1,14 @@ +(de oddWords () + (use C + (loop + (until (sub? (prin (setq C (char))) "!,.:;?")) + (T (= "." C)) + (setq C (char)) + (T + (= "." + (prin + (recur (C) + (if (sub? C "!,.:;?") + C + (prog1 (recurse (char)) (prin C)) ) ) ) ) ) ) + (prinl) ) ) diff --git a/Task/Odd-word-problem/PicoLisp/odd-word-problem-2.l b/Task/Odd-word-problem/PicoLisp/odd-word-problem-2.l new file mode 100644 index 0000000000..0fcd2de18f --- /dev/null +++ b/Task/Odd-word-problem/PicoLisp/odd-word-problem-2.l @@ -0,0 +1,2 @@ +(in "txt1" (oddWords)) +(in "txt2" (oddWords)) diff --git a/Task/Odd-word-problem/Prolog/odd-word-problem.pro b/Task/Odd-word-problem/Prolog/odd-word-problem.pro new file mode 100644 index 0000000000..e65c766e9a --- /dev/null +++ b/Task/Odd-word-problem/Prolog/odd-word-problem.pro @@ -0,0 +1,27 @@ +odd_word_problem :- + read_line_to_codes(user_input, L), + even_word(L, Out, []), + string_to_list(Str, Out), + writeln(Str). + +even_word(".") --> ".". + +even_word([H | T]) --> + {char_type(H,alnum)}, + [H], + even_word(T). + +even_word([H | T]) --> + [H], + odd_word(T, []). + +odd_word(".", R) --> R, ".". + +odd_word([H|T], R) --> + {char_type(H,alnum)}, + odd_word(T, [H | R]). + +odd_word([H|T], R) --> + R, + [H], + even_word(T). diff --git a/Task/Odd-word-problem/PureBasic/odd-word-problem.purebasic b/Task/Odd-word-problem/PureBasic/odd-word-problem.purebasic new file mode 100644 index 0000000000..252452e2ed --- /dev/null +++ b/Task/Odd-word-problem/PureBasic/odd-word-problem.purebasic @@ -0,0 +1,58 @@ +#False = 0 +#True = 1 + +Global *inputPtr.Character + +Macro nextChar() + *inputPtr + SizeOf(Character) +EndMacro + +Procedure isPunctuation(c.s) + If FindString("!?()[]{},.;:-'" + #DQUOTE$, c) + ProcedureReturn #True + EndIf + ProcedureReturn #False +EndProcedure + +Procedure oddWord() + Protected c.c + c = *inputPtr\c + If isPunctuation(Chr(*inputPtr\c)) + ProcedureReturn + Else + nextChar() + oddWord() + EndIf + Print(Chr(c)) +EndProcedure + +Procedure oddWordProblem(inputStream.s) + *inputPtr = @inputStream + Define isOdd = #False + While *inputPtr\c + If isOdd + oddWord() + Else + Repeat + Print(Chr(*inputPtr\c)) + nextChar() + Until isPunctuation(Chr(*inputPtr\c)) + EndIf + Print(Chr(*inputPtr\c)) + isOdd ! 1 ;toggle word indicator + nextChar() + Wend +EndProcedure + +Define inputStream.s +If OpenConsole() + Repeat + PrintN(#CRLF$ + #CRLF$ + "Enter a series of words consisting only of English letters (i.e. a-z, A-Z)") + PrintN("and that are separated by a punctuation mark (i.e. !?()[]{},.;:-' or " + #DQUOTE$ + ").") + inputStream = Input() + oddWordProblem(inputStream) ;assume input is correct + Until inputStream = "" + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Odd-word-problem/Python/odd-word-problem-1.py b/Task/Odd-word-problem/Python/odd-word-problem-1.py new file mode 100644 index 0000000000..4bfc12abef --- /dev/null +++ b/Task/Odd-word-problem/Python/odd-word-problem-1.py @@ -0,0 +1,28 @@ +from sys import stdin, stdout + +def char_in(): return stdin.read(1) +def char_out(c): stdout.write(c) + +def odd(prev = lambda: None): + a = char_in() + if not a.isalpha(): + prev() + char_out(a) + return a != '.' + + # delay action until later, in the shape of a closure + def clos(): + char_out(a) + prev() + + return odd(clos) + +def even(): + while True: + c = char_in() + char_out(c) + if not c.isalpha(): return c != '.' + +e = False +while odd() if e else even(): + e = not e diff --git a/Task/Odd-word-problem/Python/odd-word-problem-2.py b/Task/Odd-word-problem/Python/odd-word-problem-2.py new file mode 100644 index 0000000000..4534a4e120 --- /dev/null +++ b/Task/Odd-word-problem/Python/odd-word-problem-2.py @@ -0,0 +1,4 @@ +$ echo "what,is,the;meaning,of:life." | python odd.py +what,si,the;gninaem,of:efil. +$ echo "we,are;not,in,kansas;any,more." | python odd.py +we,era;not,ni,kansas;yna,more. diff --git a/Task/Odd-word-problem/Python/odd-word-problem-3.py b/Task/Odd-word-problem/Python/odd-word-problem-3.py new file mode 100644 index 0000000000..c708662d7a --- /dev/null +++ b/Task/Odd-word-problem/Python/odd-word-problem-3.py @@ -0,0 +1,28 @@ +from sys import stdin, stdout + +def char_in(): return stdin.read(1) +def char_out(c): stdout.write(c) + +def odd(): + a = char_in() + if a.isalpha(): + r = odd() + char_out(a) + return r + + # delay printing terminator until later, in the shape of a closure + def clos(): + char_out(a) + return a != '.' + + return clos + +def even(): + while True: + c = char_in() + char_out(c) + if not c.isalpha(): return c != '.' + +e = False +while odd()() if e else even(): + e = not e diff --git a/Task/Odd-word-problem/Python/odd-word-problem-4.py b/Task/Odd-word-problem/Python/odd-word-problem-4.py new file mode 100644 index 0000000000..b7846e9221 --- /dev/null +++ b/Task/Odd-word-problem/Python/odd-word-problem-4.py @@ -0,0 +1,33 @@ +from sys import stdin, stdout + +def fwd(c): + if c.isalpha(): + return [stdout.write(c), (yield from fwd((yield f)))][1] + else: + return c + +def rev(c): + if c.isalpha(): + return [(yield from rev((yield r))), stdout.write(c)][0] + else: + return c + +def fw(): + while True: + stdout.write((yield from fwd((yield r)))) + +def re(): + while True: + stdout.write((yield from rev((yield f)))) + +f = fw() +r = re() +next(f) +next(r) + +coro = f +while True: + c = stdin.read(1) + if not c: + break + coro = coro.send(c) diff --git a/Task/Odd-word-problem/README b/Task/Odd-word-problem/README new file mode 100644 index 0000000000..4d514d9aa0 --- /dev/null +++ b/Task/Odd-word-problem/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Odd_word_problem diff --git a/Task/Odd-word-problem/REXX/odd-word-problem.rexx b/Task/Odd-word-problem/REXX/odd-word-problem.rexx new file mode 100644 index 0000000000..f2e823f2a5 --- /dev/null +++ b/Task/Odd-word-problem/REXX/odd-word-problem.rexx @@ -0,0 +1,35 @@ +/*REXX program solves the odd word problem by just using byte I/O. */ +iFID_ = 'ODDWORD.IN' /*numeric suffix is added later. */ +oFID_ = 'ODDWORD.' /* " " " " " */ + + do case=1 for 2; #=0 /*#: number of characters read.*/ + iFID=ifid_ || case /*read ODDWORD.IN1 or ODDWORD.IN2*/ + oFID=ofid_ || case /*write ODDWORD.1 or ODDWORD.2 */ + say; say; say '──────── reading file: ' iFID "────────" + + do until x=='.' /* [↓] perform for odd words. */ + + do until \datatype(x,'M') + call readChar; call writeChar + end /*until \datatype···*/ + + if x=='.' then leave /*end─of─sentence? (full stop) */ + call readLetters; punctuation_loc=# + /* [↓] perform for even words.*/ + do j=#-1 by -1; call readChar j + if \datatype(x,'M') then leave; call writeChar + end /*j*/ + + call readLetters; call writeChar; #=punctuation_loc + end /*until x ···*/ + end /*case*/ /* [↑] process both input files.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines───────────────*/ +readLetters: do until \datatype(x,'M'); call readChar; end; return +writeChar: call charout ,x; call charout oFID,x; return +serr: say; say '***error!***' arg(1); say; exit 13 /*oops─ay.*/ +/*──────────────────────────────────readChar subroutine─────────────────*/ +readChar: if lines(iFID)==0 then call serr 'EOF reached.' /*no file.*/ +if arg(1)=='' then do; x=charin(ifid); #=#+1; end /*read the next char*/ + else x=charin(ifid, arg(1)) /* " specific " */ +return diff --git a/Task/Odd-word-problem/Racket/odd-word-problem.rkt b/Task/Odd-word-problem/Racket/odd-word-problem.rkt new file mode 100644 index 0000000000..e16ef90d41 --- /dev/null +++ b/Task/Odd-word-problem/Racket/odd-word-problem.rkt @@ -0,0 +1,26 @@ +#!/bin/sh +#| +exec racket -tm- "$0" "$@" +|# + +#lang racket + +(define (even k) + (define c (read-char)) + (cond [(eq? c eof) (k)] + [(not (char-alphabetic? c)) (k) (write-char c) (odd)] + [else (even (λ() (write-char c) (k)))])) + +(define (odd) + (define c (read-char)) + (unless (eq? c eof) + (write-char c) + (if (char-alphabetic? c) (odd) (even void)))) + +(provide main) +(define (main) (odd) (newline)) + +;; (with-input-from-string "what,is,the;meaning,of:life." main) +;; ;; -> what,si,the;gninaem,of:efil. +;; (with-input-from-string "we,are;not,in,kansas;any,more." main) +;; ;; -> we,era;not,ni,kansas;yna,more. diff --git a/Task/Odd-word-problem/Ruby/odd-word-problem-1.rb b/Task/Odd-word-problem/Ruby/odd-word-problem-1.rb new file mode 100644 index 0000000000..c064de9dca --- /dev/null +++ b/Task/Odd-word-problem/Ruby/odd-word-problem-1.rb @@ -0,0 +1,13 @@ +f, r = nil +fwd = proc {|c| + c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c } +rev = proc {|c| + c =~ /[[:alpha:]]/ ? [rev[Fiber.yield r], (print c)][0] : c } + +(f = Fiber.new { loop { print fwd[Fiber.yield r] }}).resume +(r = Fiber.new { loop { print rev[Fiber.yield f] }}).resume + +coro = f +until $stdin.eof? + coro = coro.resume($stdin.getc) +end diff --git a/Task/Odd-word-problem/Ruby/odd-word-problem-2.rb b/Task/Odd-word-problem/Ruby/odd-word-problem-2.rb new file mode 100644 index 0000000000..4c43fc235d --- /dev/null +++ b/Task/Odd-word-problem/Ruby/odd-word-problem-2.rb @@ -0,0 +1,71 @@ +require 'continuation' unless defined? Continuation +require 'stringio' + +# Save current continuation. +def savecc(*data) + # With MRI 1.8 (but not 1.9), the array literal + # [callcc {|cc| cc}, *data] + # used the wrong return value from callcc. The workaround is to + # put callcc outside the array literal. + continuation = callcc {|cc| cc} + [continuation, *data] +end + +# Jump back to continuation, where savecc will return [nil, *data]. +def jump_back(continuation) + continuation[nil] +end + +def read_odd_word(input, output) + first_continuation, last_continuation = nil + reverse = false + # Read characters. Loop until end of stream. + while c = input.getc + c = c.chr # For Ruby 1.8, convert Integer to String. + if c =~ /[[:alpha:]]/ + # This character is a letter. + if reverse + # Odd word: Write letters in reverse order. + saving, last_continuation, c = savecc(last_continuation, c) + if saving + last_continuation = saving + else + # After jump: print letters in reverse. + output.print c + jump_back last_continuation + end + else + # Even word: Write letters immediately. + output.print c + end + else + # This character is punctuation. + if reverse + # End odd word. Fix trampoline, follow chain of continuations + # (to print letters in reverse), then bounce off trampoline. + first_continuation, c = savecc(c) + if first_continuation + jump_back last_continuation + end + output.print c # Write punctuation. + reverse = false # Begin even word. + else + output.print c # Write punctuation. + reverse = true # Begin odd word. + # Create trampoline to bounce to (future) first_continuation. + last_continuation, = savecc + unless last_continuation + jump_back first_continuation + end + end + end + end + output.puts # Print a cosmetic newline. +end + +def odd_word(string) + read_odd_word StringIO.new(string), $stdout +end + +odd_word "what,is,the;meaning,of:life." +odd_word "we,are;not,in,kansas;any,more." diff --git a/Task/Odd-word-problem/Run-BASIC/odd-word-problem.run b/Task/Odd-word-problem/Run-BASIC/odd-word-problem.run new file mode 100644 index 0000000000..37ac8f74a1 --- /dev/null +++ b/Task/Odd-word-problem/Run-BASIC/odd-word-problem.run @@ -0,0 +1,31 @@ +open "oddWord.txt" for input as #f ' read input stream +while not(eof(#f)) +line input #f, a$ +oddW$ = "" ' begin the result oddW with blank +px = 0 ' begin word search location with 0 +count = 0 ' begin the word count to 0 +while x < len(a$) ' look at each character + x = instr(a$,",",px) ' search for comma (,) + if x = 0 then x = len(a$) ' no more commas? + x1 = instr(a$,";",px) ' search for (;) + x2 = instr(a$,":",px) ' search for (:) + if x1 <> 0 then x = min(x,x1) ' what came first the , ; or : + if x2 <> 0 then x = min(x,x2) + + w$ = mid$(a$,px,x - px) ' get the word seperated by , ; or : + + if count and 1 then ' is it the odd word + w1$ = "" + for i = len(w$) to 1 step -1 + w1$ = w1$ + mid$(w$,i,1) ' reverse odd words + next i + w$ = w1$ + end if + oddW$ = oddW$ + w$ + mid$(a$,x,1) ' add the word to the end of oddW$ + px = x + 1 ' bump word search location for next while + count = count + 1 ' count the words +wend +print a$;" -> ";oddW$ ' print the original and result +next ii +wend +close #f diff --git a/Task/Odd-word-problem/Scala/odd-word-problem.scala b/Task/Odd-word-problem/Scala/odd-word-problem.scala new file mode 100644 index 0000000000..622ceede26 --- /dev/null +++ b/Task/Odd-word-problem/Scala/odd-word-problem.scala @@ -0,0 +1,17 @@ +import scala.io.Source +import java.io.PrintStream + +def process(s: Source, p: PrintStream, w: Int = 0): Unit = if (s.hasNext) s.next match { + case '.' => p append '.' + case c if !Character.isAlphabetic(c) => p append c; reverse(s, p, w + 1) + case c => p append c; process(s, p, w) +} + +def reverse(s: Source, p: PrintStream, w: Int = 0, x: Char = '.'): Char = s.next match { + case c if !Character.isAlphabetic(c) => p append x; c + case c => val n = reverse(s, p, w, c); + if (x == '.') {p append n; process(s, p, w + 1)} else p append x; n +} + +process(Source.fromString("what,is,the;meaning,of:life."), System.out); println +process(Source.fromString("we,are;not,in,kansas;any,more."), System.out); println diff --git a/Task/Odd-word-problem/Scheme/odd-word-problem.ss b/Task/Odd-word-problem/Scheme/odd-word-problem.ss new file mode 100644 index 0000000000..6da0ada4b6 --- /dev/null +++ b/Task/Odd-word-problem/Scheme/odd-word-problem.ss @@ -0,0 +1,19 @@ +(define (odd) + (let ((c (read-char))) + (if (char-alphabetic? c) + (let ((r (odd))) + (write-char c) + r) + (lambda () (write-char c) (char=? c #\.))))) + +(define (even) + (let ((c (read-char))) + (write-char c) + (if (char-alphabetic? c) + (even) + (char=? c #\.)))) + +(let loop ((i #f)) + (if (if i ((odd)) (even)) + (exit) + (loop (not i)))) diff --git a/Task/Odd-word-problem/Seed7/odd-word-problem.seed7 b/Task/Odd-word-problem/Seed7/odd-word-problem.seed7 new file mode 100644 index 0000000000..674909706f --- /dev/null +++ b/Task/Odd-word-problem/Seed7/odd-word-problem.seed7 @@ -0,0 +1,35 @@ +$ include "seed7_05.s7i"; + include "chartype.s7i"; + +const func char: doChar (in boolean: doReverse) is func + result + var char: delimiter is ' '; + local + var char: ch is ' '; + begin + ch := getc(IN); + if ch in letter_char then + if doReverse then + delimiter := doChar(doReverse); + write(ch); + else + write(ch); + delimiter := doChar(doReverse); + end if; + else + delimiter := ch; + end if; + end func; + +const proc: main is func + local + var char: delimiter is ' '; + var boolean: doReverse is FALSE; + begin + repeat + delimiter := doChar(doReverse); + write(delimiter); + doReverse := not doReverse; + until delimiter = '.'; + writeln; + end func; diff --git a/Task/Odd-word-problem/TUSCRIPT/odd-word-problem.tu b/Task/Odd-word-problem/TUSCRIPT/odd-word-problem.tu new file mode 100644 index 0000000000..9eb47ddae1 --- /dev/null +++ b/Task/Odd-word-problem/TUSCRIPT/odd-word-problem.tu @@ -0,0 +1,18 @@ +$$ MODE TUSCRIPT +inputstring=* +DATA what,is,the;meaning,of:life. +DATA we,are;not,in,kansas;any,more. + +BUILD C_GROUP >[pu]=".,;:-" + +LOOP i=inputstring +pu=STRINGS (i,"|>[pu]|") +wo=STRINGS (i,"|<> 1 THEN + printf(($g$,co,wot+".",$l$)) + FI; + IF count prev NE UPB prev THEN + prev[count prev+:=1]:=wot; + FOR i FROM count prev BY -1 TO 2 DO + printf(($gl$,"She"+swd+"the"+prev[i]+" to catch the"+prev[i-1]+".")) + OD; + printf(($gl$,"I don't know why she"+swd+"the fly.", + "Perhaps she'll die.", $l$)) + FI +); + +vs("fly",()); +vs("spider","That wriggled and jiggled and tickled inside her."); +vs("Bird",("Quite absurd",tsa)); +vs("Cat",("Fancy that",tsa)); +vs("Dog",("What a hog",tsa)); +vs("Pig",("Her mouth was so big",tsa)); +vs("Goat",("She just opened her throat",tsa)); +vs("Cow",("I don't know how",tsa)); +vs("Donkey",("It was rather wonky",tsa)); +vs("Horse","She's dead, of course!") diff --git a/Task/Old-lady-swallowed-a-fly/ALGOL-68/old-lady-swallowed-a-fly-2.alg b/Task/Old-lady-swallowed-a-fly/ALGOL-68/old-lady-swallowed-a-fly-2.alg new file mode 100644 index 0000000000..87f72edf6b --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/ALGOL-68/old-lady-swallowed-a-fly-2.alg @@ -0,0 +1,39 @@ +#!/usr/local/bin/a68g --script # + +STRING a="WBXAY",b="WCXBY",c="WDXCY",d="WEXDY", + e="WFXEY",f="WGXFY",g="WHXGY",h="WIXHY", + k="K",z="Z",l=""; + +[]STRING + w=( # Assuming ASCII ordering # + "fly","spider","Bird","Cat","Dog","Pig","Goat","Cow","Donkey","Horse", + + "I don't know why she swallowed the fly.", + "That wriggled and jiggled and tickled inside her.", + "Quite absurd","Fancy that","What a hog", + "Her mouth was so big","She just opened her throat", + "I don't know how","It was rather wonky", + "She's dead, of course!", + + "I know an old lady who swallowed a ", + ". To swallow a ", + "She swallowed the "," to catch the ",".", + "Perhaps she'll die."), + v=( + "UAY",k,z,l, + "UBY","L",a,k,z,l, + "UCY","MVCY",b,a,k,z,l, + "UDY","NVDY",c,b,a,k,z,l, + "UEY","OVEY",d,c,b,a,k,z,l, + "UFY","PVFY",e,d,c,b,a,k,z,l, + "UGY","QVGY",f,e,d,c,b,a,k,z,l, + "UHY","RVHY",g,f,e,d,c,b,a,k,z,l, + "UIY","SVIY",h,g,f,e,d,c,b,a,k,z,l, + "UJY","T"); + +FOR i TO UPB v DO + FOR j TO UPB v[i] DO + print(w[ABS v[i][j] - ABS "A" + 1]) + OD; + print(new line) +OD diff --git a/Task/Old-lady-swallowed-a-fly/AWK/old-lady-swallowed-a-fly.awk b/Task/Old-lady-swallowed-a-fly/AWK/old-lady-swallowed-a-fly.awk new file mode 100644 index 0000000000..1ced8dfa17 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/AWK/old-lady-swallowed-a-fly.awk @@ -0,0 +1,33 @@ +# syntax: GAWK -f OLD_LADY_SWALLOWED_A_FLY.AWK +BEGIN { + arr[++i] = "fly/" + arr[++i] = "spider/That wriggled and jiggled and tickled inside her" + arr[++i] = "bird/Quite absurd@" + arr[++i] = "cat/Fancy that@" + arr[++i] = "dog/What a hog@" + arr[++i] = "pig/Her mouth was so big@" + arr[++i] = "goat/Opened her throat and down went the goat" + arr[++i] = "cow/I don't know how@" + arr[++i] = "donkey/It was rather wonkey@" + arr[++i] = "horse/She's dead of course" + leng = i # array length + for (i=1; i<=leng; i++) { + s = arr[i] + A[i] = substr(s,1,index(s,"/")-1) # critter name + text = substr(s,index(s,"/")+1) + sub(/@/," to swallow a "A[i],text) + printf("I know an old lady who swallowed a %s.\n",A[i]) + if (text != "") { + printf("%s.\n",text) + } + if (i == leng) { + break + } + for (j=i; j>1; j--) { + printf("She swallowed the %s to catch the %s.\n",A[j],A[j-1]) + } + printf("I don't know why she swallowed the fly.\n") + printf("Perhaps she'll die.\n\n") + } + exit(0) +} diff --git a/Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada b/Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada new file mode 100644 index 0000000000..8c0827ff2b --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada @@ -0,0 +1,58 @@ +with Ada.Text_IO, Ada.Containers.Indefinite_Doubly_Linked_Lists; use Ada.Text_IO; + +procedure Swallow_Fly is + + package Strings is new Ada.Containers.Indefinite_Doubly_Linked_Lists(String); + + Lines, Animals: Strings.List; + + procedure Swallow(Animal: String; + Second_Line: String; + Permanent_Second_Line: Boolean := True) is + + procedure Print(C: Strings.Cursor) is + begin + Put_Line(Strings.Element(C)); + end Print; + + begin + Put_Line("There was an old lady who swallowed a " & Animal & ","); + Put_Line(Second_Line); + if not Animals.Is_Empty then + Lines.Prepend("She swallowed the " & Animal & " to catch the " & + Animals.Last_Element & ","); + end if; + Lines.Iterate(Print'Access); + New_Line; + if Permanent_Second_Line then + Lines.Prepend(Second_Line); + end if; + Animals.Append(Animal); -- you need "to catch the " most recent animal + end Swallow; + + procedure Swallow_TSA(Animal: String; Part_Of_Line_2: String) is + begin + Swallow(Animal, Part_Of_Line_2 &", to swallow a " & Animal & ";", False); + end Swallow_TSA; + + procedure Swallow_SSA(Animal: String; Part_Of_Line_2: String) is + begin + Swallow(Animal, Part_Of_Line_2 &" she swallowed a " & Animal & ";", False); + end Swallow_SSA; + +begin + Lines.Append("Perhaps she'll die!"); + + Swallow("fly", "But I don't know why she swallowed the fly,"); + Swallow("spider", "That wriggled and jiggled and tickled inside her;"); + Swallow_TSA("bird", "Quite absurd"); + Swallow_TSA("cat", "Fancy that"); + Swallow_TSA("dog", "What a hog"); + Swallow_TSA("pig", "Her mouth was so big"); + Swallow_TSA("goat","She just opened her throat"); + Swallow_SSA("cow", "I don't know how"); + Swallow_TSA("donkey", "It was rather wonky"); + + Put_Line("There was an old lady who swallowed a horse ..."); + Put_Line("She's dead, of course!"); +end Swallow_Fly; diff --git a/Task/Old-lady-swallowed-a-fly/AutoHotkey/old-lady-swallowed-a-fly.ahk b/Task/Old-lady-swallowed-a-fly/AutoHotkey/old-lady-swallowed-a-fly.ahk new file mode 100644 index 0000000000..9815a2746c --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/AutoHotkey/old-lady-swallowed-a-fly.ahk @@ -0,0 +1,19 @@ +Animals := [["fly", "I don't know why she swallowed the "] + , ["spider", "That wriggled and jiggled and tickled inside her"] + , ["bird", "Quite absurd"] + , ["cat", "Fancy that"] + , ["dog", "What a hog"] + , ["pig", "Her mouth was so big"] + , ["goat", "She just opened her throat"] + , ["cow", "I don't know how"] + , ["donkey", "It was rather wonky"] + , ["horse", "She's dead, of course!"]] + +for i, V in Animals { + Output .= "I know an old lady who swallowed a " V.1 ".`n" + . (i = 1 ? Saved := V.2 V.1 ".`nPerhaps she'll die.`n`n" + : V.2 (i = Animals.MaxIndex() ? "" : (i = 2 ? "" : ". To swallow a " V.1) ".`n" + . (Saved := "She swallowed the " V.1 " to catch the " Animals[i - 1].1 ".`n" Saved))) +} + +MsgBox, % Output diff --git a/Task/Old-lady-swallowed-a-fly/Babel/old-lady-swallowed-a-fly.pb b/Task/Old-lady-swallowed-a-fly/Babel/old-lady-swallowed-a-fly.pb new file mode 100644 index 0000000000..b148aaf59a --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Babel/old-lady-swallowed-a-fly.pb @@ -0,0 +1,44 @@ +((main {fly !}) + +(fly + {{"There was an old lady who swallowed a " << + iter 1 - dup + <- 0 animal ! nl << -> + 1 animal ! << + {iter 10 ~=}{ + " " << + {iter 1 =}{last}{fnord} ifte + iter 1 - 0 animal ! nl << + {"She swallowed the " << + this_iter ! 0 animal ! << + " to catch the " << + next_iter ! 0 animal ! nl << + {iter 2 =} + {8 1 animal ! nl <<} + {fnord} + ifte} + 11 iter - 1 - + times} + {fnord} + ifte + "But I don't know why she swallowed the fly\nPerhaps she'll die\n\n" <<} + animals len + times}) + +(next_iter {10 iter - }) +(this_iter {next_iter ! 1 -}) + +(animal { <- <- animals -> ith -> ith}) + +-- There are 10 animals +(animals + (("horse" "She's dead of course...\n") + ("donkey" "It was rather wonkey! To swallow a") + ("cow" "I don't know how she swallowed a") + ("goat" "She just opened her throat! And swallowed the") + ("pig" "Her mouth was so big, to swallow a") + ("dog" "What a hog! To swallow a") + ("cat" "Fancy that! She swallowed a") + ("bird" "Quite absurd to swallow a") + ("spider" "That wriggled and jiggled and tickled inside her") + ("fly" " ")))) diff --git a/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c b/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c new file mode 100644 index 0000000000..85e395f4fc --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c @@ -0,0 +1,29 @@ +#include + +const char *dict[] = { +"_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog" +"_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_" +"r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.." +"./She's dead, of course!/","_a_p_b_e ","/S_t "," to catch the ","fly,/Bu" +"t _mwhy s_t fly,/Perhaps she'll die!//_ha","_apig_bdog,_l`","spider,/Tha" +"t wr_nj_ntickled inside her;_aspider_b_c",", to_s a ","_sed ","There_qan" +" old lady who_g","_a_r_bpig,_d","_acat_b_p,_","_acow_b_r,_i","_adog_bcat" +",_j","I don't know ","iggled and ","donkey","bird"," was ","goat"," swal" +"low","he_gthe" +}; + +int print(const char *c, int s) +{ + do { + if (s) s = print(dict[*c - 95], 0); + else if (*c == '_') s = 1; + else putchar(*c == '/' ? '\n' : *c); + } while (*++c); + return s; +} + +int main() +{ + print(dict[0], 0); + return 0; +} diff --git a/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-1.d b/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-1.d new file mode 100644 index 0000000000..9941a3cb8b --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-1.d @@ -0,0 +1,29 @@ +import core.stdc.stdio; + +immutable data = [ +"_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog"~ +"_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_"~ +"r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.."~ +"./She's dead, of course!/","_a_p_b_e ","/S_t "," to catch the ","fly,/Bu"~ +"t _mwhy s_t fly,/Perhaps she'll die!//_ha","_apig_bdog,_l`","spider,/Tha"~ +"t wr_nj_ntickled inside her;_aspider_b_c",", to_s a ","_sed ","There_qan"~ +" old lady who_g","_a_r_bpig,_d","_acat_b_p,_","_acow_b_r,_i","_adog_bcat"~ +",_j","I don't know ","iggled and ","donkey","bird"," was ","goat"," swal"~ +"low","he_gthe"]; + +bool oldLady(in string part, bool s=false) nothrow @nogc { + foreach (immutable ch; part) { + if (s) + s = oldLady(data[ch - '_'], false); + else if (ch == '_') + s = true; + else + putchar(ch == '/' ? '\n' : ch); + } + + return s; +} + +void main() { + data[0].oldLady; +} diff --git a/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-2.d b/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-2.d new file mode 100644 index 0000000000..ddcbffc8cc --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/D/old-lady-swallowed-a-fly-2.d @@ -0,0 +1,41 @@ +enum Action { once, every, die } + +immutable struct T { + string anim; + Action act; + string phrase; +} + +immutable T[10] animals = [ + T("horse", Action.die, "She's dead, of course!"), + T("donkey", Action.once, "It was rather wonky. To swallow a donkey."), + T("cow", Action.once, "I don't know how. To swallow a cow."), + T("goat", Action.once, "She just opened her throat. To swallow a goat."), + T("pig", Action.once, "Her mouth was so big. To swallow a pig."), + T("dog", Action.once, "What a hog. To swallow a dog."), + T("cat", Action.once, "Fancy that. To swallow a cat."), + T("bird", Action.once, "Quite absurd. To swallow a bird."), + T("spider", Action.once, "That wriggled and jiggled and tickled inside her."), + T("fly", Action.every, "I don't know why she swallowed the fly.")]; + +void main() { + import std.stdio; + + foreach_reverse (immutable i; 0 .. animals.length) { + writeln("I know an old lady who swallowed a ", + animals[i].anim, "."); + animals[i].phrase.writeln; + + if (animals[i].act == Action.die) + break; + + foreach (immutable j, immutable r; animals[i + 1 .. $]) { + writeln("She swallowed the ", animals[i + j].anim, + " to catch the ", r.anim, "."); + if (r.act == Action.every) + r.phrase.writeln; + } + + "Perhaps she'll die.\n".writeln; + } +} diff --git a/Task/Old-lady-swallowed-a-fly/Factor/old-lady-swallowed-a-fly.factor b/Task/Old-lady-swallowed-a-fly/Factor/old-lady-swallowed-a-fly.factor new file mode 100644 index 0000000000..21530d3bd1 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Factor/old-lady-swallowed-a-fly.factor @@ -0,0 +1,10 @@ +USING: base85 compression.zlib ; + +"c%1E4%WlIU5WMphn^P`UexSD=s^-?Jk$NVE7-Gs=fQ9_`T}Y~ggi4hvMSb{SX}vpQXJ;^Yqok7%xd(0 +mjR3>N1W_UQ$c@1$1#sAzsbTkHfHerT%K*K_NT>e5yCRDAFrgX{pAnt$DPGHxt*E9$RMRBPeRcoXvT{6xN%o=~9@t{fLM`G}XV^A6Hk!HSBn{YM +ylrFhv&t_M?=}Lzm^6W<+00(I)uM#EY@ah;z@Y)zDUk;J&o^8C<;g7LlMIS{^*(al_mjFQv=BG_DyZn +<}rUt#FCDtKB9S`Y4jg+0PuB?Qt-&(11p?caq^S=1C`$D1fa 3215 uncompress >string print diff --git a/Task/Old-lady-swallowed-a-fly/Forth/old-lady-swallowed-a-fly.fth b/Task/Old-lady-swallowed-a-fly/Forth/old-lady-swallowed-a-fly.fth new file mode 100644 index 0000000000..681cf48624 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Forth/old-lady-swallowed-a-fly.fth @@ -0,0 +1,54 @@ +: string, ( c-addr u -- ) \ store string at HERE , with a count + dup c, here swap dup allot move ; + +\ doubly linked list: (0|prev, 0|next, aside?, cstr animal; cstr aside) +\ aside? is true if the aside is always displayed. +variable swallowed +variable first +: >next ( swallow-addr -- swallow-addr' ) + cell+ @ ; +: >aside? ( swallow-addr -- f ) + 2 cells + @ ; +: >animal ( swallow-addr -- c-addr u ) + 3 cells + count ; +: >aside ( swallow-addr -- c-addr u ) + >animal + count ; + +: swallow ( "animal" -- ) + align swallowed @ if here swallowed @ cell+ ! else here first ! then + here swallowed @ , swallowed ! + 0 , 0 , parse-word string, ; \ data structure still needs the aside +: always ( -- ) \ set aside? of last-defined swallow to true + swallowed @ 2 cells + on ; +: aside ( "aside" -- ) + 0 parse string, ; + +swallow fly always aside But I don't know why she swallowed the fly, +swallow spider always aside That wriggled and jiggled and tickled inside her; +swallow bird aside Quite absurd, she swallowed the bird; +swallow cat aside Fancy that, she swallowed the cat; +swallow dog aside What a hog, she swallowed the dog; +swallow pig aside Her mouth was so big, she swallowed the pig; +swallow goat aside She just opened her throat, she swallowed the goat; +swallow cow aside I don't know how, she swallowed the cow; +swallow donkey aside It was rather wonky, she swallowed the donkey; + +: ?aside ( swallow-addr -- ) \ print aside if aside? is true + dup >aside? if >aside cr type else drop then ; + +: reasons ( swallow-addr -- ) \ print reasons she swallowed something + begin dup @ while + dup cr ." She swallowed the " >animal type ." to catch the " + @ dup >animal type ." ," dup ?aside + repeat drop ; + +: verse ( swallow-addr -- ) + cr ." There was an old lady who swallowed a " dup >animal type ." ," + dup >aside cr type + reasons + cr ." Perhaps she'll die!" ; + +: song ( -- ) + first @ begin dup verse cr >next dup 0= until drop + cr ." There was an old lady who swallowed a horse..." + cr ." She's dead, of course!" ; diff --git a/Task/Old-lady-swallowed-a-fly/Frege/old-lady-swallowed-a-fly.frege b/Task/Old-lady-swallowed-a-fly/Frege/old-lady-swallowed-a-fly.frege new file mode 100644 index 0000000000..9f0d8e10ae --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Frege/old-lady-swallowed-a-fly.frege @@ -0,0 +1,41 @@ +module OldLady where + +import Data.List + +-- Once means the phrase is only printed in the verse about that animal. +-- Every means the phrase is printed for every verse. It is used for "fly", +-- and could optionally be used for "spider", in the version of the song where +-- "wriggled and jiggled..." is repeated every verse. +-- Die is only used for the horse, and means the chain of animals won't be +-- included in the verse. +data AnimalAction = Once | Every | Die + +animals = [("horse", Die, "She's dead, of course!"), + ("donkey", Once, "It was rather wonky. To swallow a donkey."), + ("cow", Once, "I don't know how. To swallow a cow."), + ("goat", Once, "She just opened her throat. To swallow a goat."), + ("pig", Once, "Her mouth was so big. To swallow a pig."), + ("dog", Once, "What a hog. To swallow a dog."), + ("cat", Once, "Fancy that. To swallow a cat."), + ("bird", Once, "Quite absurd. To swallow a bird."), + ("spider", Once, "That wriggled and jiggled and tickled inside her."), + ("fly", Every, "I don't know why she swallowed the fly.")] + +verse :: [(String, AnimalAction, String)] -> [String] +verse ((anim, act, phrase):restAnims) = + let lns = ["I know an old lady who swallowed a " ++ anim ++ ".", phrase] + in case act of Die -> lns + _ -> lns ++ verse' restAnims anim + +verse' :: [(String, AnimalAction, String)] -> String -> [String] +verse' [] _ = ["Perhaps she'll die."] +verse' ((anim, act, phrase):restAnims) prevAnim = + let why = "She swallowed the " ++ prevAnim ++ " to catch the " ++ anim ++ "." + lns = case act of Every -> [why, phrase] + _ -> [why] + in lns ++ verse' restAnims anim + +song :: [String] +song = intercalate [""] $ map verse $ tail $ reverse $ tails animals + +main _ = printStr $ unlines song diff --git a/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs new file mode 100644 index 0000000000..277f54a613 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs @@ -0,0 +1,41 @@ +#!/usr/bin/runhaskell + +import Data.List + +-- Once means the phrase is only printed in the verse about that animal. +-- Every means the phrase is printed for every verse. It is used for "fly", +-- and could optionally be used for "spider", in the version of the song where +-- "wriggled and jiggled..." is repeated every verse. +-- Die is only used for the horse, and means the chain of animals won't be +-- included in the verse. +data AnimalAction = Once | Every | Die + +animals = [("horse", Die, "She's dead, of course!"), + ("donkey", Once, "It was rather wonky. To swallow a donkey."), + ("cow", Once, "I don't know how. To swallow a cow."), + ("goat", Once, "She just opened her throat. To swallow a goat."), + ("pig", Once, "Her mouth was so big. To swallow a pig."), + ("dog", Once, "What a hog. To swallow a dog."), + ("cat", Once, "Fancy that. To swallow a cat."), + ("bird", Once, "Quite absurd. To swallow a bird."), + ("spider", Once, "That wriggled and jiggled and tickled inside her."), + ("fly", Every, "I don't know why she swallowed the fly.")] + +verse :: [(String, AnimalAction, String)] -> [String] +verse ((anim, act, phrase):restAnims) = + let lns = ["I know an old lady who swallowed a " ++ anim ++ ".", phrase] + in case act of Die -> lns + _ -> lns ++ verse' restAnims anim + +verse' :: [(String, AnimalAction, String)] -> String -> [String] +verse' [] _ = ["Perhaps she'll die."] +verse' ((anim, act, phrase):restAnims) prevAnim = + let why = "She swallowed the " ++ prevAnim ++ " to catch the " ++ anim ++ "." + lns = case act of Every -> [why, phrase] + _ -> [why] + in lns ++ verse' restAnims anim + +song :: [String] +song = intercalate [""] $ map verse $ tail $ reverse $ tails animals + +main = putStr $ unlines song diff --git a/Task/Old-lady-swallowed-a-fly/Icon/old-lady-swallowed-a-fly.icon b/Task/Old-lady-swallowed-a-fly/Icon/old-lady-swallowed-a-fly.icon new file mode 100644 index 0000000000..52902c8004 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Icon/old-lady-swallowed-a-fly.icon @@ -0,0 +1,32 @@ +procedure main() #: There Was An Old Lady Lyrics + +verse := table() # arglists for printf - [1] long asides and [2] terse joiners +verse["bird"] := [["%s,\nQuite absurd, %s %s;\n",1,2,1],["%s,\n",1]] +verse["cat"] := [["%s,\nFancy that, %s %s;\n",1,2,1],["%s,\n",1]] +verse["dog"] := [["%s,\nWhat a hog, %s %s;\n",1,2,1],["%s,\n",1]] +verse["pig"] := [["%s,\nHer mouth was so big, %s %s;\n",1,2,1],["%s,\n",1]] +verse["goat"] := [["%s,\nShe just opened her throat, %s %s;\n",1,2,1],["%s,\n",1]] +verse["cow"] := [["%s,\nI don't know how, %s %s;\n",1,2,1],["%s,\n",1]] +verse["donkey"] := [["%s,\nIt was rather wonky, %s %s;\n",1,2,1],["%s,\n",1]] + + # just long versions of these +verse["fly"] := [["%s,\nBut I don't know why %s %s,\nPerhaps she'll die!\n\n",1,2,1]] +verse["spider"] := [["%s,\nThat wriggled and jiggled and tickled inside her;\n",1]] +verse["horse"] := [["%s...\nShe's dead, of course!\n",1]] + +every (f := verse[k := key(verse)][1|2])[i := 1 to *f] do # fix every printf args + f[i] := case f[i] of { 1 : k ; 2 : "she swallowed the"; default : f[i]} + +zoofilo := [] +"fly,spider,bird,cat,dog,pig,goat,cow,donkey,horse," ? # order + while push(zoofilo,tab(find(","))) & move(1) do { + printf("There was an old lady who swallowed a ") + every critter := !zoofilo do { + printf!verse[critter,(critter == (zoofilo[1] | "spider" | "fly"),1)|2] + if critter == "horse" then stop() # dead + printf("She swallowed the %s to catch the ","fly" ~== critter) + } + } +end + +link printf diff --git a/Task/Old-lady-swallowed-a-fly/J/old-lady-swallowed-a-fly.j b/Task/Old-lady-swallowed-a-fly/J/old-lady-swallowed-a-fly.j new file mode 100644 index 0000000000..c3b5c2361a --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/J/old-lady-swallowed-a-fly.j @@ -0,0 +1,24 @@ +T=:'' +e=:3 :'T=:T,y,LF' +E=:e@,&'.' +O=:'I know an old lady who swallowed a 'E@,] +I=:e bind('I don''t know why she swallowed the fly.',LF,'Perhaps she''ll die.',LF) +I O 'fly' +O P=:'spider' +E 'That wriggled and jiggled and tickled inside her' +I E A=:'She swallowed the spider to catch the fly' +N=:4 :0 + O x + E y,'. To swallow a ',x + I E A=:'She swallowed the ',x,' to catch the ',P,'.',LF,A + P=:x +) +'Bird'N'Quite absurd' +'Cat'N'Fancy that' +'Dog'N'What a hog' +'Pig'N'Her mouth was so big' +'Goat'N'She just opened her throat' +'Cow'N'I don''t know how' +'Donkey'N'It was rather wonky' +O'Horse' +e'She''s dead, of course!' diff --git a/Task/Old-lady-swallowed-a-fly/Java/old-lady-swallowed-a-fly.java b/Task/Old-lady-swallowed-a-fly/Java/old-lady-swallowed-a-fly.java new file mode 100644 index 0000000000..9596b1100d --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Java/old-lady-swallowed-a-fly.java @@ -0,0 +1,29 @@ +public class OldLadySwallowedAFly { + + final static String[] data = { + "_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog" + + "_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_" + + "r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.." + + "./She's dead, of course!/", "_a_p_b_e ", "/S_t ", " to catch the ", "fly,/Bu" + + "t _mwhy s_t fly,/Perhaps she'll die!//_ha", "_apig_bdog,_l`", "spider,/Tha" + + "t wr_nj_ntickled inside her;_aspider_b_c", ", to_s a ", "_sed ", "There_qan" + + " old lady who_g", "_a_r_bpig,_d", "_acat_b_p,_", "_acow_b_r,_i", "_adog_bcat" + + ",_j", "I don't know ", "iggled and ", "donkey", "bird", " was ", "goat", " swal" + + "low", "he_gthe"}; + + static boolean oldLady(String part, boolean s) { + for (char c : part.toCharArray()) { + if (s) + s = oldLady(data[c - '_'], false); + else if (c == '_') + s = true; + else + System.out.print(c == '/' ? '\n' : c); + } + return s; + } + + public static void main(String[] args) { + oldLady(data[0], false); + } +} diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml new file mode 100644 index 0000000000..a59de72874 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml @@ -0,0 +1,32 @@ +let d = [| + "I know an old lady who swallowed a "; "fly"; ".\n"; + "I don't know why she swallowed the fly.\nPerhaps she'll die.\n\n"; + "spider"; "That wriggled and jiggled and tickled inside her"; + "She swallowed the "; " to catch the "; "Bird"; "Quite absurd"; + ". To swallow a "; "Cat"; "Fancy that"; "Dog"; "What a hog"; "Pig"; + "Her mouth was so big"; "Goat"; "She just opened her throat"; "Cow"; + "I don't know how"; "Donkey"; "It was rather wonky"; + "I know an old lady who swallowed a Horse.\nShe's dead, of course!\n"; +|] + +let s0 = [6;4;7;1;2;3] +let s1 = [6;8;7;4;2] @ s0 +let s2 = [6;11;7;8;2] @ s1 +let s3 = [6;13;7;11;2] @ s2 +let s4 = [6;15;7;13;2] @ s3 +let s5 = [6;17;7;15;2] @ s4 +let s6 = [6;19;7;17;2] @ s5 +let s7 = [6;21;7;19;2] @ s6 + +let s = + [0;1;2;3;0;4;2;5;2] @ s0 @ + [0;8;2;9;10;8;2] @ s1 @ + [0;11;2;12;10;11;2] @ s2 @ + [0;13;2;14;10;13;2] @ s3 @ + [0;15;2;16;10;15;2] @ s4 @ + [0;17;2;18;10;17;2] @ s5 @ + [0;19;2;20;10;19;2] @ s6 @ + [0;21;2;22;10;21;2] @ s7 @ + [23] ;; + +List.iter (fun i -> print_string d.(i)) s diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml new file mode 100644 index 0000000000..4721e804e8 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml @@ -0,0 +1,19 @@ +let dict = [| + "_ha _c _e _p,\nQuite absurd_f_p;_`cat,\nFancy that_fcat;_j`dog,\nWhat a hog_\ + fdog;_l`pig,\nHer mouth_qso big_fpig;_d_r,\nShe just opened her throat_f_r;_i\ + cow,\n_mhow she_ga cow;_k_o,\nIt_qrather wonky_f_o;_a_o_bcow,_khorse...\nShe'\ + s dead, of course!\n";"_a_p_b_e ";"\nS_t ";" to catch the ";"fly,\nBut _mwhy \ + s_t fly,\nPerhaps she'll die!\n\n_ha";"_apig_bdog,_l`";"spider,\nThat wr_nj_n\ + tickled inside her;_aspider_b_c";", to_s a ";"_sed ";"There_qan old lady who_\ + g";"_a_r_bpig,_d";"_acat_b_p,_";"_acow_b_r,_i";"_adog_bcat,_j";"I don't know \ + ";"iggled and ";"donkey";"bird";" was ";"goat";" swallow";"he_gthe" |] + +let rec old_lady part s = + ExtString.String.fold_left (fun s c -> + if s then old_lady dict.(Char.code c - 95) false + else if c = '_' then true + else (print_char c; s) + ) s part + +let _ = + old_lady dict.(0) false diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml new file mode 100644 index 0000000000..35fc337797 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml @@ -0,0 +1,32 @@ +let an = + [| "fly"; "spider"; "bird"; "cat"; "dog"; "pig"; "goat"; "cow"; "donkey" |] + +let cm = + [| "Quite absurd"; + "Fancy that"; + "What a hog"; + "Her mouth was so big"; + "She just opened her throat"; + "I don't know how"; + "It was rather wonky"; |] + +let p = Printf.printf + +let h n = + for i = n downto 1 do + if i = 1 then + p "That wriggled and jiggled and tickled inside her;\n"; + p "She swallowed the %s to catch the %s,\n" an.(i) an.(i-1) + done + +let g n = + if n >= 2 then p "%s, to swallow a %s;\n" cm.(n-2) an.(n) + +let f n = + p "There was an old lady who swallowed a %s,\n" an.(n); g n; h n; + p "But I don't know why she swallowed the fly,\nPerhaps she'll die!\n\n" + +let () = + for i = 0 to 8 do f i done; + p "There was an old lady who swallowed a horse...\n\ + She's dead, of course!" diff --git a/Task/Old-lady-swallowed-a-fly/PHP/old-lady-swallowed-a-fly.php b/Task/Old-lady-swallowed-a-fly/PHP/old-lady-swallowed-a-fly.php new file mode 100644 index 0000000000..0141ab57e8 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/PHP/old-lady-swallowed-a-fly.php @@ -0,0 +1,40 @@ + 'fly.', + 'reason' => "I don't know why she swallowed the fly."), + array('swallowed' => 'spider,', + 'aside' => "which wiggled and jiggled and tickled inside her.", + 'reason' => "She swallowed the spider to catch the fly"), + array('swallowed' => 'bird.', + 'aside' => "How absurd! To swallow a bird!", + 'reason' => "She swallowed the bird to catch the spider,"), + array('swallowed' => 'cat.', + 'aside' => "Imagine that! To swallow a cat!", + 'reason' => "She swallowed the cat to catch the bird."), + array('swallowed' => 'dog.', + 'aside' => "What a hog! To swallow a dog!", + 'reason' => "She swallowed the dog to catch the cat."), + array('swallowed' => 'horse', + 'aside' => "She's dead, of course. She swallowed a horse!", + 'reason' => "She swallowed the horse to catch the dog.")); + +foreach($swallowed as $creature) +{ + print "I knew an old lady who swallowed a " . $creature['swallowed'] . "\n"; + if(array_key_exists('aside', $creature)) + print $creature['aside'] . "\n"; + + $reversed = array_reverse($swallowed); + $history = array_slice($reversed, array_search($creature, $reversed)); + + foreach($history as $note) + { + print $note['reason'] . "\n"; + } + + if($swallowed[count($swallowed) - 1] == $creature) + print "But she sure died!\n"; + else + print "Perhaps she'll die." . "\n\n"; +} diff --git a/Task/Old-lady-swallowed-a-fly/Perl-6/old-lady-swallowed-a-fly.pl6 b/Task/Old-lady-swallowed-a-fly/Perl-6/old-lady-swallowed-a-fly.pl6 new file mode 100644 index 0000000000..d967810325 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Perl-6/old-lady-swallowed-a-fly.pl6 @@ -0,0 +1,25 @@ +my @victims = + fly => " I don't know why S—", + spider => " That wriggled and jiggled and tickled inside her.", + bird => " How absurd, T!", + cat => " Fancy that, S!", + dog => " What a hog, T!", + goat => " She just opened her throat, and in walked the goat!", + cow => " I don't know how S!", + horse => " She's dead, of course..."; + +my @history = "I guess she'll die...\n"; + +for @victims».kv -> $victim, $_ is copy { + say "There was an old lady who swallowed a $victim..."; + + s/ «S» /she swallowed the $victim/; + s/ «T» /to swallow a $victim!/; + .say; + last when /dead/; + + @history[0] ~~ s/^X/She swallowed the $victim/; + .say for @history; + @history.unshift($_) if @history < 5; + @history.unshift("X to catch the $victim,"); +} diff --git a/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-1.pl b/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-1.pl new file mode 100644 index 0000000000..7d70df0f63 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-1.pl @@ -0,0 +1,32 @@ +my @animals = ( + "fly", + "spider/That wriggled and jiggled and tickled inside her.\n", + "bird//Quite absurd!", + "cat//Fancy that!", + "dog//What a hog!", + "pig//Her mouth was so big!", + "goat//She just opened her throat!", + "cow//I don't know how;", + "donkey//It was rather wonkey!", + "horse:", +); + +my $s = "swallow"; +my $e = $s."ed"; +my $t = "There was an old lady who $e a "; +my $_ = $t."But I don't know why she $e the fly;\nPerhaps she'll die!\n\n"; + +my ($a, $b, $c, $d); +while (my $x = shift @animals) { + s/$c//; + ($a, $b, $c) = split('/', $x); + $d = " the $a"; + + $c =~ s/;/ she $e$d;\n/; + $c =~ s/!/, to $s$d;\n/; + + s/$t/"$t$a,\n$c".(($b||$c) && "${b}She $e$d to catch the ")/e; + + s/:.*/--\nShe's dead, of course!\n/s; + print; +} diff --git a/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-2.pl b/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-2.pl new file mode 100644 index 0000000000..8b3ec0c73a --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Perl/old-lady-swallowed-a-fly-2.pl @@ -0,0 +1,18 @@ +open OUT, "| uudecode | bunzip2" and +print OUT and +close OUT; + +__DATA__ +begin-base64 644 - +QlpoOTFBWSZTWUSbX/0AAZRfgAAQYIUACBFgbIA//96gQAK9oAAAxhMTQYIx +DIwmDEoAAAAAAxhMTQYIxDIwmBSkiNIaJtCCAzJPU1G4ueVmGZMsMzBz0N5v +hr4j29SRSSCZgyv8BDAAdOE3oFIFIhMAQMtm2Zy/MbRs9U1pgzCzGcaGnTYN +u5NJ+/D4TfkcZZ39PmNJuN8rxjMrJTfvr8rFkxmTDMGFjDLBleGh3L8zlhuO +9vcq6rom3TonOONxyJ1TlG3dz2Tu3xZNtzTLgZu21y1r0dOW/HLntrgdi9ow +hlHTsnRVbJ98DxjYs/K87Q1rJjWazCO7kHbIXUj9DS7dSMHVNSmhwrjHMc8D +INk476V5jJDmnOPXZM38aeAd+DUp/39ccxmDEf3H7u30Rk6zDLGZkPYNq9CP +Pzj39xsVe+KeupMjKsjONsG6dk1bajByHYPOMHxneP2Og3q+dR9ryGk19o0n +onYPUfEfhVc1V+kcbJwmQ/nRwn3Hp6pP4TqvTO/2TfNJkvrrbt8+a9N92oy2 +FeXUOI8486Wvor1zajqPDfpwnrn2jOzvo8hkOPrpVajlwnjqPfIry5c0TbKL +559fx8xqpsquRaFYV9I9fT6p7RrI/Gv/F3JFOFCQRJtf/Q== +==== diff --git a/Task/Old-lady-swallowed-a-fly/PicoLisp/old-lady-swallowed-a-fly.l b/Task/Old-lady-swallowed-a-fly/PicoLisp/old-lady-swallowed-a-fly.l new file mode 100644 index 0000000000..ba0d30dc5c --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/PicoLisp/old-lady-swallowed-a-fly.l @@ -0,0 +1,42 @@ +(de *Dict + `(chop + "_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,\ + /What a hog_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just \ + opened her throat_f_r;_icow,/_mhow she_ga cow;_k_o,/It_qrather \ + wonky_f_o;_a_o_bcow,_khorse.../She's dead, of course!/" ) + `(chop "_a_p_b_e ") + `(chop "/S_t ") + `(chop " to catch the ") + `(chop "fly,/But _mwhy s_t fly,/Perhaps she'll die!//_ha") + `(chop "_apig_bdog,_l`") + `(chop "spider,/That wr_nj_ntickled inside her;_aspider_b_c") + `(chop ", to_s a ") + `(chop "_sed ") + `(chop "There_qan old lady who_g") + `(chop "_a_r_bpig,_d") + `(chop "_acat_b_p,_") + `(chop "_acow_b_r,_i") + `(chop "_adog_bcat,_j") + `(chop "I don't know ") + `(chop "iggled and ") + `(chop "donkey") + `(chop "bird") + `(chop " was ") + `(chop "goat") + `(chop " swallow") + `(chop "he_gthe") ) + +(de oldLady (Lst Flg) + (loop + (let C (pop 'Lst) + (cond + (Flg + (setq Flg + (oldLady (get *Dict (- (char C) 94))) ) ) + ((= "_" C) (on Flg)) + ((= "/" C) (prinl)) + (T (prin C)) ) ) + (NIL Lst) ) + Flg ) + +(oldLady (car *Dict)) diff --git a/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py b/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py new file mode 100644 index 0000000000..4b402427ae --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py @@ -0,0 +1,11 @@ +import zlib, base64 + +b64 = b''' +eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL +2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii// +WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ +uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh +W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N +Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM +zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE=''' +print(zlib.decompress(base64.b64decode(b64)).decode("utf-8", "strict")) diff --git a/Task/Old-lady-swallowed-a-fly/README b/Task/Old-lady-swallowed-a-fly/README new file mode 100644 index 0000000000..e050d1658b --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Old_lady_swallowed_a_fly diff --git a/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx b/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx new file mode 100644 index 0000000000..4ace1f402c --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx @@ -0,0 +1,24 @@ +/*REXX program to display the lyrics for the song: "I Know an Old Lady".*/ +@ = 'fly spider bird cat dog goat cow horse' ; #=words(@) +first = "I know an old lady who swallowed a" ; sw=79 +@ate = 'She swallowed the'; @2catch= "to catch the" ; @.= +@.1 = "I don't know why she swallowed a fly," +@.2 = "That wriggled and jiggled and tickled inside her."; @.2.0=1 +@.3 = "How absurd to swallow a bird!" +@.4 = "Imagine that, to swallow a cat!" +@.5 = "My, what a hog, to swallow a dog!" +@.6 = "Just opened her throat and swallowed a goat!" +@.7 = "I wonder how she swallowed a cow?!" +@.8 = "She's dead, of course!!" + + do j=1 for #; animal=word(@,j); say + say center(first animal',',sw); if j\==1 then say center(@.j, sw) + if j==# then leave + do k=j to 2 by -1; km=k-1 + say center(@ate word(@,k) @2catch word(@,km)',',sw) + if @.km.0\=='' then say center(@.km, sw) + end /*k*/ + say center(@.1, sw) + say center("I guess she'll die.", sw) + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-1.rkt b/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-1.rkt new file mode 100644 index 0000000000..3c7201511f --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-1.rkt @@ -0,0 +1,24 @@ +#lang at-exp racket + +(define (line . xs) (for-each display xs) (newline)) + +(let loop ([animals + '([fly #f] + [spider "That wriggled and wiggled and tiggled inside her"] + [bird "How absurd to swallow a bird"] + [cat "Fancy that to swallow a cat"] + [dog "What a hog, to swallow a dog"] + [cow "I don't know how she swallowed a cow"] + [horse "She's dead, of course"])] + [seen '()]) + (when (pair? animals) + (match animals + [(list (list animal desc) more ...) + @line{There was an old lady that swallowed a @animal,} + (when desc @line{@|desc|.}) + (when (pair? more) + (for ([this (cons animal seen)] [that seen]) + @line{She swallowed the @this to catch the @that,}) + @line{I don't know why she swallowed a fly - perhaps she'll die!} + @line{} + (loop more (cons animal seen)))]))) diff --git a/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-2.rkt b/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-2.rkt new file mode 100644 index 0000000000..2d1584c300 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Racket/old-lady-swallowed-a-fly-2.rkt @@ -0,0 +1,6 @@ +#lang s-exp framework/private/decode +7VK7TsQwEOz9FcM1AcncZyCoQaLey/piCyuObJ+s/D3rXHj4lIIKgaCItJkZ7cyOfM0uTZ5m +7J6siQaFEmhE8AxPPCNbykiFvA/FMAhHP2v1AA5jl/EyhoJiZyRrLlW4xWSipSlVtvMe7MyV +Ul/0SZNjE7XIhSjRDYOv+Mgon+a8zm5MIoes3qvHJkuuf8su5ICecm8X7LvuOLjIWt3Lfjqk +U+SaYuVXditxxdu8b338rOvEUas7GvuVa44Tcuu2/qz7CHuu6PeWwGHQ6rmiBCtz24KwWy0I +3KZdqvwDbfWhXPhY+S59RLX5dkTapF66/2/3fYMNMZklVJfAhlgjHKW2k8B7tbtRrw== diff --git a/Task/Old-lady-swallowed-a-fly/Ruby/old-lady-swallowed-a-fly.rb b/Task/Old-lady-swallowed-a-fly/Ruby/old-lady-swallowed-a-fly.rb new file mode 100644 index 0000000000..9b52a3aa7c --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Ruby/old-lady-swallowed-a-fly.rb @@ -0,0 +1,32 @@ +descriptions = { + :fly => "I don't know why S", + :spider => "That wriggled and jiggled and tickled inside her.", + :bird => "Quite absurd T", + :cat => "Fancy that, S", + :dog => "What a hog, S", + :goat => "She opened her throat T", + :cow => "I don't know how S", + :horse => "She's dead, of course.", +} +animals = descriptions.keys + +animals.each_with_index do |animal, idx| + puts "There was an old lady who swallowed a #{animal}." + + d = descriptions[animal] + case d[-1] + when "S" then d[-1] = "she swallowed a #{animal}." + when "T" then d[-1] = "to swallow a #{animal}." + end + puts d + break if animal == :horse + + idx.downto(1) do |i| + puts "She swallowed the #{animals[i]} to catch the #{animals[i-1]}." + case animals[i-1] + when :spider, :fly then puts descriptions[animals[i-1]] + end + end + + print "Perhaps she'll die.\n\n" +end diff --git a/Task/Old-lady-swallowed-a-fly/Scala/old-lady-swallowed-a-fly.scala b/Task/Old-lady-swallowed-a-fly/Scala/old-lady-swallowed-a-fly.scala new file mode 100644 index 0000000000..dadb3c5fa5 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Scala/old-lady-swallowed-a-fly.scala @@ -0,0 +1,27 @@ +case class Verse(animal: String, remark: String, die: Boolean = false, always: Boolean = false) + +val verses = List( + Verse("horse", "She’s dead, of course!", die = true), + Verse("donkey", "It was rather wonky. To swallow a donkey."), + Verse("cow", "I don’t know how. To swallow a cow."), + Verse("goat", "She just opened her throat. To swallow a goat."), + Verse("pig", "Her mouth was so big. To swallow a pig."), + Verse("dog", "What a hog. To swallow a dog."), + Verse("cat", "Fancy that. To swallow a cat."), + Verse("bird", "Quite absurd. To swallow a bird."), + Verse("spider", "That wriggled and jiggled and tickled inside her."), + Verse("fly", "I don’t know why she swallowed the fly.", always = true) +) + +for (i <- 1 to verses.size; verse = verses takeRight i; starting = verse.head) { + println(s"There was an old lady who swallowed a ${starting.animal},") + println(starting.remark) + if (!starting.die) { + for (List(it, next) <- verse.sliding(2,1)) { + println(s"She swallowed the ${it.animal} to catch the ${next.animal},") + if (next.always) println(next.remark) + } + println("Perhaps she’ll die!") + println + } +} diff --git a/Task/Old-lady-swallowed-a-fly/Seed7/old-lady-swallowed-a-fly.seed7 b/Task/Old-lady-swallowed-a-fly/Seed7/old-lady-swallowed-a-fly.seed7 new file mode 100644 index 0000000000..ae0e8f94e6 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Seed7/old-lady-swallowed-a-fly.seed7 @@ -0,0 +1,34 @@ +$ include "seed7_05.s7i"; + +const array array string: verses is [] ( + [] ("fly", "I don't know why she swallowed the fly."), + [] ("spider", "That wriggled and jiggled and tickled inside her."), + [] ("bird", "Quite absurd. To swallow a bird."), + [] ("cat", "Fancy that. To swallow a cat."), + [] ("dog", "What a hog. To swallow a dog."), + [] ("pig", "Her mouth was so big. To swallow a pig."), + [] ("goat", "She just opened her throat. To swallow a goat."), + [] ("cow", "I don't know how. To swallow a cow."), + [] ("donkey", "It was rather wonky. To swallow a donkey."), + [] ("horse", "She's dead, of course!")); + +const proc: main is func + local + var integer: verseNumber is 0; + var integer: animal is 0; + begin + for key verseNumber range verses do + writeln("There was an old lady who swallowed a " <& verses[verseNumber][1] <& ","); + writeln(verses[verseNumber][2]); + if verseNumber <> length(verses) then + for animal range verseNumber downto 2 do + writeln("She swallowed the " <& verses[animal][1] <& " to catch the " <& verses[pred(animal)][1] <& ","); + end for; + if verseNumber <> 1 then + writeln(verses[1][2]); + end if; + writeln("Perhaps she'll die!"); + writeln; + end if; + end for; + end func; diff --git a/Task/Old-lady-swallowed-a-fly/TXR/old-lady-swallowed-a-fly.txr b/Task/Old-lady-swallowed-a-fly/TXR/old-lady-swallowed-a-fly.txr new file mode 100644 index 0000000000..d5e2aa5b0b --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/TXR/old-lady-swallowed-a-fly.txr @@ -0,0 +1,83 @@ +@(deffilter abbr + ("IK" "I know an old lady who swallowed a") ("SW" "She swallowed the") + ("SS" "she swallowed") ("CA" "to catch the") ("XX" "Perhaps she'll die") + ("C" "cow") ("G" "goat") ("D" "dog") ("T" "cat") ("R" "bird") + ("S " "spider ") ("F" "fly")) +@(bind lastverse + ("IK C" + "I don't know how SS the C" + "SW C CA G" + "SW G CA D" + "SW D CA T" + "SW T CA R" + "SW R CA S" + "SW S CA F" + "But I don't know why SS that F" + "XX" + "" + "IK horse" + "She's alive and well of course!")) +@(bind animal_line + ("G: Opened her throat and down went the G!" + "D: What a hog to swallow a D!" + "T: Imagine that! She swallowed a T!" + "R: How absurd to swallow a R!" + "S: That wriggled and jiggled and tickled inside her" + "F: But I don't know why SS the F")) +@(define expand_backwards (song lengthened_song done)) +@ (local line2 line3 verse rest animal previous_animal previous_animal_verse) +@ (next :list song) +@ (cases) +IK @animal +@line2 +SW @animal CA @previous_animal +@ (maybe) +But @(skip)F +@ (end) +@ (collect) +@ verse +@ (until) + +@ (end) +@ (collect) +@ rest +@ (end) +@ (next :list animal_line) +@ (skip) +@previous_animal: @previous_animal_verse +@ (output :into lengthened_song) +IK @previous_animal +@previous_animal_verse +@ (repeat) +@ verse +@ (end) + +@ (repeat) +@ song +@ (end) +@ (end) +@ (bind done nil) +@ (or) +IK @(skip) +@line2 +XX +@ (bind lengthened_song song) +@ (bind done t) +@ (end) +@(end) +@(define expand_song (in out)) +@ (local lengthened done) +@ (expand_backwards in lengthened done) +@ (cases) +@ (bind done nil) +@ (expand_song lengthened out) +@ (or) +@ (bind out lengthened) +@ (end) +@(end) +@(expand_song lastverse song) +@(output :filter abbr) +@ (repeat) +@song +@ (end) +@(end) diff --git a/Task/Old-lady-swallowed-a-fly/Tcl/old-lady-swallowed-a-fly.tcl b/Task/Old-lady-swallowed-a-fly/Tcl/old-lady-swallowed-a-fly.tcl new file mode 100644 index 0000000000..4521fa6eb5 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Tcl/old-lady-swallowed-a-fly.tcl @@ -0,0 +1,12 @@ +package require Tcl 8.6 + +puts [zlib inflate [binary decode base64 " + 7VRNa8MwDL3nV2inXkZ+xDa29taxws5q7NZuPSvYDib/fnJKPxwXBoNCx3KTn56t + p6dEC9hbioAWyAgwKHqIisBHNIaiFICwMX1dLUCQnYUDO6oevJIXrMCngbeUTmHr + U3pmDAgt64ov/1jEt1pIV1crhQGi09utSbgVsLuIg272KdbWMx1UuvFRCDm8BYGg + wdCos7hbN/Gknair904HCbj2HZ9gdaKcCKXihOd6j37cUXfPGOrqFW3T81sc560N + 2VItw7nUP23BC23r6jN9ogiK49yCIVuqZTiX+i+sWmo2Y86lv6gLCiLyEwRrPTZt + 4JW6Gc5FT+ZemPtGxy53nQ9ArbSMq6RFOSr+zTM915DwXP00jd8sRoqjIoqR0XpM + nCtGcDITPI3qxgvc7mWqE4aN5DCknyYy2hfL/MC85lzKjMybxnsP452T83JQNPMg + JIpHoA001DH88A0= +"]] diff --git a/Task/Order-disjoint-list-items/00DESCRIPTION b/Task/Order-disjoint-list-items/00DESCRIPTION new file mode 100644 index 0000000000..c6f61b3b6a --- /dev/null +++ b/Task/Order-disjoint-list-items/00DESCRIPTION @@ -0,0 +1,27 @@ +Given M as a list of items and another list N of items chosen from M, create M' as a list with the ''first'' occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N. That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N. + +For example: +:if M is 'the cat sat on the mat' +:And N is 'mat cat' +:Then the result M' is 'the mat sat on the cat'. +The words not in N are left in their original positions. + +If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered. + +For example: +:M = 'A B C A B C A B C' +:N = 'C A C A' +Is ordered as: +:M' = 'C B A C B A A B C' + +Show the output, here, for at least the following inputs: +
Data M: 'the cat sat on the mat' Order N: 'mat cat'
+Data M: 'the cat sat on the mat' Order N: 'cat mat'
+Data M: 'A B C A B C A B C'      Order N: 'C A C A'
+Data M: 'A B C A B D A B E'      Order N: 'E A D A'
+Data M: 'A B'                    Order N: 'B'
+Data M: 'A B'                    Order N: 'B A'
+Data M: 'A B B A'                Order N: 'B A'
+ +;Cf: +* [[Sort disjoint sublist]] diff --git a/Task/Order-disjoint-list-items/AutoHotkey/order-disjoint-list-items.ahk b/Task/Order-disjoint-list-items/AutoHotkey/order-disjoint-list-items.ahk new file mode 100644 index 0000000000..fa8139493a --- /dev/null +++ b/Task/Order-disjoint-list-items/AutoHotkey/order-disjoint-list-items.ahk @@ -0,0 +1,21 @@ +Data := [ {M: "the cat sat on the mat", N: "mat cat"} + , {M: "the cat sat on the mat", N: "cat mat"} + , {M: "A B C A B C A B C", N: "C A C A"} + , {M: "A B C A B D A B E", N: "E A D A"} + , {M: "A B", N: "B"} + , {M: "A B", N: "B A"} + , {M: "A B B A", N: "B A"} ] + +for Key, Val in Data + Output .= Val.M " :: " Val.N " -> " OrderDisjointList(Val.M, Val.N) "`n" +MsgBox, % RTrim(Output, "`n") + +OrderDisjointList(M, N) { + ItemsN := [] + Loop, Parse, N, % A_Space + ItemsN[A_LoopField] := ItemsN[A_LoopField] ? ItemsN[A_LoopField] + 1 : 1 + N := StrSplit(N, A_Space) + Loop, Parse, M, % A_Space + Result .= (ItemsN[A_LoopField]-- > 0 ? N.Remove(1) : A_LoopField) " " + return RTrim(Result) +} diff --git a/Task/Order-disjoint-list-items/Bracmat/order-disjoint-list-items.bracmat b/Task/Order-disjoint-list-items/Bracmat/order-disjoint-list-items.bracmat new file mode 100644 index 0000000000..791b70ae8b --- /dev/null +++ b/Task/Order-disjoint-list-items/Bracmat/order-disjoint-list-items.bracmat @@ -0,0 +1,35 @@ +( ( odli + = M N NN item A Z R + . !arg:(?M.?N) + & :?NN + & whl + ' ( !N:%?item ?N + & ( !M:?A !item ?Z + & !A (.) !Z:?M + & !NN !item:?NN + | + ) + ) + & :?R + & whl + ' ( !M:?A (.) ?M + & !NN:%?item ?NN + & !R !A !item:?R + ) + & !R !M + ) +& (the cat sat on the mat.mat cat) + (the cat sat on the mat.cat mat) + (A B C A B C A B C.C A C A) + (A B C A B D A B E.E A D A) + (A B.B) + (A B.B A) + (A B B A.B A) + : ?tests +& whl + ' ( !tests:(?M.?N) ?tests + & put$("Data M:" !M) + & put$("\tOrder N:" !N) + & out$(\t odli$(!M.!N)) + ) +); diff --git a/Task/Order-disjoint-list-items/D/order-disjoint-list-items.d b/Task/Order-disjoint-list-items/D/order-disjoint-list-items.d new file mode 100644 index 0000000000..156f53304d --- /dev/null +++ b/Task/Order-disjoint-list-items/D/order-disjoint-list-items.d @@ -0,0 +1,51 @@ +import std.stdio, std.string, std.algorithm, std.array, std.range, + std.conv; + +T[] orderDisjointArrayItems(T)(in T[] data, in T[] items) +pure /*nothrow*/ @safe { + int[] itemIndices; + foreach (item; items.dup.sort().uniq) { + immutable int itemCount = items.count(item); + assert(data.count(item) >= itemCount, + text("More of ", item, " than in data")); + auto lastIndex = [-1]; + foreach (immutable _; 0 .. itemCount) { + immutable start = lastIndex.back + 1; + lastIndex ~= data[start .. $].countUntil(item) + start; + } + itemIndices ~= lastIndex.dropOne; + } + + itemIndices.sort(); + auto result = data.dup; + foreach (index, item; zip(itemIndices, items)) + result[index] = item; + return result; +} + +void main() { + immutable problems = + "the cat sat on the mat | mat cat + the cat sat on the mat | cat mat + A B C A B C A B C | C A C A + A B C A B D A B E | E A D A + A B | B + A B | B A + A B B A | B A + | + A | A + A B | + A B B A | A B + A B A B | A B + A B A B | B A B A + A B C C B A | A C A C + A B C C B A | C A C A" + .splitLines.map!(r => r.split("|")).array; + + foreach (immutable p; problems) { + immutable a = p[0].split; + immutable b = p[1].split; + writefln("%s | %s -> %-(%s %)", p[0].strip, p[1].strip, + orderDisjointArrayItems(a, b)); + } +} diff --git a/Task/Order-disjoint-list-items/Go/order-disjoint-list-items.go b/Task/Order-disjoint-list-items/Go/order-disjoint-list-items.go new file mode 100644 index 0000000000..79be421400 --- /dev/null +++ b/Task/Order-disjoint-list-items/Go/order-disjoint-list-items.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "sort" + "strings" +) + +type indexSort struct { + val sort.Interface + ind []int +} + +func (s indexSort) Len() int { return len(s.ind) } +func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } +func (s indexSort) Swap(i, j int) { + s.val.Swap(s.ind[i], s.ind[j]) + s.ind[i], s.ind[j] = s.ind[j], s.ind[i] +} + +func disjointSliceSort(m, n []string) []string { + s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))} + used := make(map[int]bool) + for _, nw := range n { + for i, mw := range m { + if used[i] || mw != nw { + continue + } + used[i] = true + s.ind = append(s.ind, i) + break + } + } + sort.Sort(s) + return s.val.(sort.StringSlice) +} + +func disjointStringSort(m, n string) string { + return strings.Join( + disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ") +} + +func main() { + for _, data := range []struct{ m, n string }{ + {"the cat sat on the mat", "mat cat"}, + {"the cat sat on the mat", "cat mat"}, + {"A B C A B C A B C", "C A C A"}, + {"A B C A B D A B E", "E A D A"}, + {"A B", "B"}, + {"A B", "B A"}, + {"A B B A", "B A"}, + } { + mp := disjointStringSort(data.m, data.n) + fmt.Printf("%s → %s » %s\n", data.m, data.n, mp) + } + +} diff --git a/Task/Order-disjoint-list-items/Icon/order-disjoint-list-items.icon b/Task/Order-disjoint-list-items/Icon/order-disjoint-list-items.icon new file mode 100644 index 0000000000..aa4568a2bb --- /dev/null +++ b/Task/Order-disjoint-list-items/Icon/order-disjoint-list-items.icon @@ -0,0 +1,23 @@ +procedure main(A) + every write(" -> ",odli("the cat sat on the mat","mat cat")) + every write(" -> ",odli("the cat sat on the mat","cat mat")) + every write(" -> ",odli("A B C A B C A B C","C A C A")) + every write(" -> ",odli("A B C A B D A B E","E A D A")) + every write(" -> ",odli("A B","B")) + every write(" -> ",odli("A B","B A")) + every write(" -> ",odli("A B B A","B A")) +end + +procedure odli(M,N) + writes(M," :: ",N) + Mp := "" + P := N ||:= " " + (M||" ") ? while item := tab(upto(' '))||move(1) do { + if find(item,P) then { + P ?:= 1(tab(find(item)),move(*item))||tab(0) + N ?:= (item := tab(upto(' '))||move(1), tab(0)) + } + Mp ||:= item + } + return Mp +end diff --git a/Task/Order-disjoint-list-items/J/order-disjoint-list-items-1.j b/Task/Order-disjoint-list-items/J/order-disjoint-list-items-1.j new file mode 100644 index 0000000000..82bb3ae357 --- /dev/null +++ b/Task/Order-disjoint-list-items/J/order-disjoint-list-items-1.j @@ -0,0 +1,9 @@ +disjorder=:3 :0&.;: +: + clusters=. ( %s%n", a[0], a[1], Arrays.toString(r)); + } + } + + // if input items cannot be null + static String[] orderDisjointItems(String[] m, String[] n) { + for (String e : n) { + int idx = ArrayUtils.indexOf(m, e); + if (idx != -1) + m[idx] = null; + } + for (int i = 0, j = 0; i < m.length; i++) { + if (m[i] == null) + m[i] = n[j++]; + } + return m; + } + + // otherwise + static String[] orderDisjointItems2(String[] m, String[] n) { + BitSet bitSet = new BitSet(m.length); + for (String e : n) { + int idx = -1; + do { + idx = ArrayUtils.indexOf(m, e, idx + 1); + } while (idx != -1 && bitSet.get(idx)); + if (idx != -1) + bitSet.set(idx); + } + for (int i = 0, j = 0; i < m.length; i++) { + if (bitSet.get(i)) + m[i] = n[j++]; + } + return m; + } +} diff --git a/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-1.pl6 b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-1.pl6 new file mode 100644 index 0000000000..ed8302f637 --- /dev/null +++ b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-1.pl6 @@ -0,0 +1,4 @@ +sub order-disjoint-list-items(\M, \N) { + my \bag = N.BagHash; + M.map: { bag{$_}-- ?? N.shift !! $_ } +} diff --git a/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-2.pl6 b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-2.pl6 new file mode 100644 index 0000000000..b5ad957df0 --- /dev/null +++ b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items-2.pl6 @@ -0,0 +1,12 @@ +for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]}) + the cat sat on the mat mat cat + the cat sat on the mat cat mat + A B C A B C A B C C A C A + A B C A B D A B E E A D A + A B B + A B B A + A B B A B A + X X Y X + A X Y A + --- +-> $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) } diff --git a/Task/Order-disjoint-list-items/Perl/order-disjoint-list-items.pl b/Task/Order-disjoint-list-items/Perl/order-disjoint-list-items.pl new file mode 100644 index 0000000000..bcf086f8fc --- /dev/null +++ b/Task/Order-disjoint-list-items/Perl/order-disjoint-list-items.pl @@ -0,0 +1,21 @@ +sub dsort { + my ($m, $n) = @_; + my %h; + $h{$_}++ for @$n; + map $h{$_}-- > 0 ? shift @$n : $_, @$m; +} + +for (split "\n", <<"IN") + the cat sat on the mat | mat cat + the cat sat on the mat | cat mat + A B C A B C A B C | C A C A + A B C A B D A B E | E A D A + A B | B + A B | B A + A B B A | B A +IN +{ + + my ($a, $b) = map([split], split '\|'); + print "@$a | @$b -> @{[dsort($a, $b)]}\n"; +} diff --git a/Task/Order-disjoint-list-items/Python/order-disjoint-list-items.py b/Task/Order-disjoint-list-items/Python/order-disjoint-list-items.py new file mode 100644 index 0000000000..777af94530 --- /dev/null +++ b/Task/Order-disjoint-list-items/Python/order-disjoint-list-items.py @@ -0,0 +1,37 @@ +from __future__ import print_function + +def order_disjoint_list_items(data, items): + #Modifies data list in-place + itemindices = [] + for item in set(items): + itemcount = items.count(item) + #assert data.count(item) >= itemcount, 'More of %r than in data' % item + lastindex = [-1] + for i in range(itemcount): + lastindex.append(data.index(item, lastindex[-1] + 1)) + itemindices += lastindex[1:] + itemindices.sort() + for index, item in zip(itemindices, items): + data[index] = item + +if __name__ == '__main__': + tostring = ' '.join + for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')), + (str.split('the cat sat on the mat'), str.split('cat mat')), + (list('ABCABCABC'), list('CACA')), + (list('ABCABDABE'), list('EADA')), + (list('AB'), list('B')), + (list('AB'), list('BA')), + (list('ABBA'), list('BA')), + (list(''), list('')), + (list('A'), list('A')), + (list('AB'), list('')), + (list('ABBA'), list('AB')), + (list('ABAB'), list('AB')), + (list('ABAB'), list('BABA')), + (list('ABCCBA'), list('ACAC')), + (list('ABCCBA'), list('CACA')), + ]: + print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ') + order_disjoint_list_items(data, items) + print("-> M' %r" % tostring(data)) diff --git a/Task/Order-disjoint-list-items/README b/Task/Order-disjoint-list-items/README new file mode 100644 index 0000000000..3b1d06c29f --- /dev/null +++ b/Task/Order-disjoint-list-items/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Order_disjoint_list_items diff --git a/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx b/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx new file mode 100644 index 0000000000..8b1e1d2494 --- /dev/null +++ b/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx @@ -0,0 +1,40 @@ +/*REXX program orders a disjoint list of M items with a list of N items.*/ +used = '0'x /*indicates word has been parsed.*/ +@. = /*placeholder indicates e─o─array*/ +@.1 = " the cat sat on the mat | mat cat " /*string.*/ +@.2 = " the cat sat on the mat | cat mat " /*string.*/ +@.3 = " A B C A B C A B C | C A C A " /*string.*/ +@.4 = " A B C A B D A B E | E A D A " /*string.*/ +@.5 = " A B | B " /*string.*/ +@.6 = " A B | B A " /*string.*/ +@.7 = " A B B A | B A " /*string.*/ +@.8 = " | " /*string.*/ +@.9 = " A | A " /*string.*/ +@.10 = " A B | " /*string.*/ +@.11 = " A B B A | A B " /*string.*/ +@.12 = " A B A B | A B " /*string.*/ +@.13 = " A B A B | B A B A " /*string.*/ +@.14 = " A B C C B A | A C A C " /*string.*/ +@.15 = " A B C C B A | C A C A " /*string.*/ + /* [↓] process each input string*/ + do j=1 while @.j\==''; r.= /*nullify the replacement string.*/ + parse var @.j m '|' n /*parse input string into M & N.*/ + mw=words(m); do i=mw for mw by -1; x=word(m,i); !.i=x; $.x=i; end + /* [↑] build ! and $ arrays. */ + do k=1 for words(n)%2 by 2 /* [↓] process the N array. */ + _=word(n,k); v=word(n,k+1) /*get an order word & replacement*/ + p1=wordpos(_,m); p2=wordpos(v,m) /*positions of word & replacement*/ + if p1==0 | p2==0 then iterate /*if either not found, skip 'em. */ + if $._>>$.v then do; r.p2=!.p1; r.p1=!.p2; end /*switch words.*/ + else do; r.p1=!.p1; r.p2=!.p2; end /*don't switch.*/ + !.p1=used; !.p2=used; m= /*mark as used.*/ + do i=1 for mw; m=m !.i; x=word(m,i); !.i=x; $.x=i; end + end /*k*/ /* [↑] rebuild the ! & $ arrays.*/ + mp= /*the MP (M') string (so far).*/ + do q=1 for mw; if !.q==used then mp=mp r.q /*use original. */ + else mp=mp !.q /*use substitute*/ + end /*q*/ /* [↑] re-build the (output) str*/ + /*═══════════════════════════════*/ + say @.j '───►' space(mp) /*display the new text reordered.*/ + end /*j*/ /* [↑] end of processing N words*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Order-disjoint-list-items/Racket/order-disjoint-list-items.rkt b/Task/Order-disjoint-list-items/Racket/order-disjoint-list-items.rkt new file mode 100644 index 0000000000..4eed37811c --- /dev/null +++ b/Task/Order-disjoint-list-items/Racket/order-disjoint-list-items.rkt @@ -0,0 +1,37 @@ +#lang racket +(define disjorder + (match-lambda** + (((list) n) '()) + ((m (list)) m) + (((list h m-tail ...) (list h n-tail ...)) + (list* h (disjorder m-tail n-tail))) + ;; the (not g/h) below stop greedy matching of the list which + ;; would pick out orderings from the right first. + (((list h (and (not g) m-tail-left) ... g m-tail-right ...) + (list g (and (not h) n-tail-left) ... h n-tail-right ...)) + (disjorder `(,g ,@m-tail-left ,h ,@m-tail-right) + `(,g ,@n-tail-left ,h ,@n-tail-right))) + (((list h m-tail ...) n) + (list* h (disjorder m-tail n))))) + +(define (report-disjorder m n) + (printf "Data M: ~a Order N: ~a -> ~a~%" + (~a #:min-width 25 m) (~a #:min-width 10 n) (disjorder m n))) + +;; Do the task tests +(report-disjorder '(the cat sat on the mat) '(mat cat)) +(report-disjorder '(the cat sat on the mat) '(cat mat)) +(report-disjorder '(A B C A B C A B C) '(C A C A)) +(report-disjorder '(A B C A B D A B E) '(E A D A)) +(report-disjorder '(A B) '(B)) +(report-disjorder '(A B) '(B A)) +(report-disjorder '(A B B A) '(B A)) +;; Do all of the other python tests +(report-disjorder '() '()) +(report-disjorder '(A) '(A)) +(report-disjorder '(A B) '()) +(report-disjorder '(A B B A) '(A B)) +(report-disjorder '(A B A B) '(A B)) +(report-disjorder '(A B A B) '(B A B A)) +(report-disjorder '(A B C C B A) '(A C A C)) +(report-disjorder '(A B C C B A) '(C A C A)) diff --git a/Task/Order-disjoint-list-items/Ruby/order-disjoint-list-items.rb b/Task/Order-disjoint-list-items/Ruby/order-disjoint-list-items.rb new file mode 100644 index 0000000000..de97bb7e67 --- /dev/null +++ b/Task/Order-disjoint-list-items/Ruby/order-disjoint-list-items.rb @@ -0,0 +1,17 @@ +test_data = [ +'the cat sat on the mat', 'mat cat', +'the cat sat on the mat', 'cat mat', +'A B C A B C A B C' , 'C A C A', +'A B C A B D A B E' , 'E A D A', +'A B' , 'B', +'A B' , 'B A', +'A B B A' , 'B A', +'the cat sat on the chair', 'chair cat'] + +test_data.each_slice(2) do |str, order| + result, order_items = str.dup, order.split + re = Regexp.union(order_items.uniq) + offsets = str.enum_for(:scan, re).map{ ($~.begin(0) ... $~.end(0)) } # $~ is last MatchData object + order_items.zip(offsets).reverse_each{|item, offset| result[offset] = item} + puts "Data M: %-24s Order N: %-10s-> M' %-12s" % [str, order, result] +end diff --git a/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-1.scala b/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-1.scala new file mode 100644 index 0000000000..5b96540c40 --- /dev/null +++ b/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-1.scala @@ -0,0 +1,5 @@ +def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] = + if (input.isEmpty || used.size >= using.size) input + else if (using diff used contains input.head) + using(used.size) +: order(input.tail, using, used :+ input.head) + else input.head +: order(input.tail, using, used) diff --git a/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-2.scala b/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-2.scala new file mode 100644 index 0000000000..0cdd06e0cf --- /dev/null +++ b/Task/Order-disjoint-list-items/Scala/order-disjoint-list-items-2.scala @@ -0,0 +1,14 @@ +val tests = List( + "the cat sat on the mat" -> "mat cat", + "the cat sat on the mat" -> "cat mat", + "A B C A B C A B C" -> "C A C A", + "A B C A B D A B E" -> "E A D A", + "A B" -> "B", + "A B" -> "B A", + "A B B A" -> "B A" +) + +tests.foreach{case (input, using) => + val done = order(input.split(" "), using.split(" ")) + println(f"""Data M: $input%-24s Order N: $using%-9s -> Result M': ${done mkString " "}""") +} diff --git a/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-1.tcl b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-1.tcl new file mode 100644 index 0000000000..eb3dac4ea0 --- /dev/null +++ b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-1.tcl @@ -0,0 +1,13 @@ +proc orderDisjoint {theList theOrderList} { + foreach item $theOrderList {incr n($item)} + set is {} + set i 0 + foreach item $theList { + if {[info exist n($item)] && [incr n($item) -1] >= 0} { + lappend is $i + } + incr i + } + foreach item $theOrderList i $is {lset theList $i $item} + return $theList +} diff --git a/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-2.tcl b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-2.tcl new file mode 100644 index 0000000000..5c2631b98d --- /dev/null +++ b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-2.tcl @@ -0,0 +1,18 @@ +proc orderDisjoint {theList theOrderList} { + foreach item $theOrderList {incr n($item)} + set is - + set i 0 + foreach item $theList { + if {[info exist n($item)] && [incr n($item) -1] >= 0} { + lappend is $i + } + incr i + } + set i 0 + foreach item $theOrderList { + if {[incr n($item)] <= 1} { + lset theList [lindex $is [incr i]] $item + } + } + return $theList +} diff --git a/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-3.tcl b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-3.tcl new file mode 100644 index 0000000000..a64cd36d05 --- /dev/null +++ b/Task/Order-disjoint-list-items/Tcl/order-disjoint-list-items-3.tcl @@ -0,0 +1,11 @@ +foreach {items order} { + "the cat sat on the mat" "mat cat" + "the cat sat on the mat" "cat mat" + "A B C A B C A B C" "C A C A" + "A B C A B D A B E" "E A D A" + "A B" "B" + "A B" "B A" + "A B B A" "B A" +} { + puts "'$items' with '$order' => '[orderDisjoint $items $order]'" +} diff --git a/Task/Paraffins/00DESCRIPTION b/Task/Paraffins/00DESCRIPTION new file mode 100644 index 0000000000..433ef805a9 --- /dev/null +++ b/Task/Paraffins/00DESCRIPTION @@ -0,0 +1,67 @@ +This organic chemistry task is essentially to implement a tree enumeration algorithm. + +The problem is to enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (or [[wp:alkane|alkane]]s). Paraffins are built up using only carbon, which has 4 bonds and hydrogen, which has 1. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogens linking the remaining unused bonds. + +In a paraffin one is allowed neither double bonds (two bonds between the same pair of atoms) nor cycles of linked carbons, so all paraffins with n carbon atoms share the empirical formula CnH2n+2 but for all n >= 4 there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly with n. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when you are looking at a flat diagram), so rotations or reorientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. + +For example with n = 3 there is only 1 way of linking the carbons despite the different orientations you can draw the molecule in; and with n = 4 there are 2 configurations, a straight chain: (CH3)(CH2)(CH2)(CH3) and a branched chain: (CH3)(CH(CH3))(CH3). Due to bond rotations it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. + +The input is just the number 'n' of carbon atoms of a molecule, like 17. The output is how many different different paraffins there are with 'n' carbon atoms (like 24_894 if n = 17). + +The sequence of those results is visible in the [[oeis:A000602|Sloane encyclopedia]]. The sequence is (the index starts from 0, and represents the number of carbon atoms): + + 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, + 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, + 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, + 10660307791, 27711253769, ... + +'''Extra credit''' + +Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, like: + +*Main> all_paraffins 1 + [CCP H H H H] +*Main> all_paraffins 2 + [BCP (C H H H) (C H H H)] +*Main> all_paraffins 3 + [CCP H H (C H H H) (C H H H)] +*Main> all_paraffins 4 + [BCP (C H H (C H H H)) (C H H (C H H H)),CCP H (C H H H) (C H H H) + (C H H H)] +*Main> all_paraffins 5 + [CCP H H (C H H (C H H H)) (C H H (C H H H)),CCP H (C H H H) + (C H H H) (C H H (C H H H)),CCP (C H H H) (C H H H) (C H H H) + (C H H H)] +*Main> all_paraffins 6 + [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),BCP + (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),BCP (C H + (C H H H) (C H H H)) (C H (C H H H) (C H H H)),CCP H (C H H H) + (C H H (C H H H)) (C H H (C H H H)),CCP (C H H H) (C H H H) + (C H H H) (C H H (C H H H))] + +Showing a basic 2D ASCII-art representation of the paraffines is better, like (molecule names aren't necessary): +
 Methane         Ethane              Propane              Iso-butane
+
+    H             H   H             H   H   H             H   H   H
+    |             |   |             |   |   |             |   |   |
+H - C - H     H - C - C - H     H - C - C - C - H     H - C - C - C - H
+    |             |   |             |   |   |             |   |   |
+    H             H   H             H   H   H             H   |   H
+                                                              |
+                                                          H - C - H
+                                                              |
+                                                              H
+ +'''Links''' + +A paper that explains the problem and its solution in a functional language: +http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf + +A Haskell implementation: +http://darcs.brianweb.net/nofib/imaginary/paraffins/Main.hs   ◄── dead link. + +A Scheme implementation: +http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm + +A Fortress implementation: +http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005 diff --git a/Task/Paraffins/C/paraffins-1.c b/Task/Paraffins/C/paraffins-1.c new file mode 100644 index 0000000000..4e891e7f50 --- /dev/null +++ b/Task/Paraffins/C/paraffins-1.c @@ -0,0 +1,115 @@ +#include + +#define MAX_N 33 /* max number of tree nodes */ +#define BRANCH 4 /* max number of edges a single node can have */ + +/* The basic idea: a paraffin molecule can be thought as a simple tree + with each node being a carbon atom. Counting molecules is thus the + problem of counting free (unrooted) trees of given number of nodes. + + An unrooted tree needs to be uniquely represented, so we need a way + to cannonicalize equivalent free trees. For that, we need to first + define the cannonical form of rooted trees. Since rooted trees can + be constructed by a root node and up to BRANCH rooted subtrees that + are arranged in some definite order, we can define it thusly: + * Given the root of a tree, the weight of each of its branches is + the number of nodes contained in that branch; + * A cannonical rooted tree would have its direct subtrees ordered + in descending order by weight; + * In case multiple subtrees are the same weight, they are ordered + by some unstated, but definite, order (this code doesn't really + care what the ordering is; it only counts the number of choices + in such a case, not enumerating individual trees.) + + A rooted tree of N nodes can then be constructed by adding smaller, + cannonical rooted trees to a root node, such that: + * Each subtree has fewer than BRANCH branches (since it must have + an empty slot for an edge to connect to the new root); + * Weight of those subtrees added later are no higher than earlier + ones; + * Their weight total N-1. + A rooted tree so constructed would be itself cannonical. + + For an unrooted tree, we can define the radius of any of its nodes: + it's the maximum weight of any of the subtrees if this node is used + as the root. A node is the center of a tree if it has the smallest + radius among all the nodes. A tree can have either one or two such + centers; if two, they must be adjacent (cf. Knuth, tAoCP 2.3.4.4). + + An important fact is that, a node in a tree is its sole center, IFF + its radius times 2 is no greater than the sum of the weights of all + branches (ibid). While we are making rooted trees, we can add such + trees encountered to the count of cannonical unrooted trees. + + A bi-centered unrooted tree with N nodes can be made by joining two + trees, each with N/2 nodes and fewer than BRANCH subtrees, at root. + The pair must be ordered in aforementioned implicit way so that the + product is cannonical. */ + +typedef unsigned long long xint; +#define FMT "llu" + +xint rooted[MAX_N] = {1, 1, 0}; +xint unrooted[MAX_N] = {1, 1, 0}; + +/* choose k out of m possible values; chosen values may repeat, but the + ordering of them does not matter. It's binomial(m + k - 1, k) */ +xint choose(xint m, xint k) +{ + xint i, r; + + if (k == 1) return m; + for (r = m, i = 1; i < k; i++) + r = r * (m + i) / (i + 1); + return r; +} + +/* constructing rooted trees of BR branches at root, with at most + N radius, and SUM nodes in the partial tree already built. It's + recursive, and CNT and L carry down the number of combinations + and the tree radius already encountered. */ +void tree(xint br, xint n, xint cnt, xint sum, xint l) +{ + xint b, c, m, s; + + for (b = br + 1; b <= BRANCH; b++) { + s = sum + (b - br) * n; + if (s >= MAX_N) return; + + /* First B of BR branches are all of weight n; the + rest are at most of weight N-1 */ + c = choose(rooted[n], b - br) * cnt; + + /* This partial tree is singly centered as is */ + if (l * 2 < s) unrooted[s] += c; + + /* Trees saturate at root can't be used as building + blocks for larger trees, so forget them */ + if (b == BRANCH) return; + rooted[s] += c; + + /* Build the rest of the branches */ + for (m = n; --m; ) tree(b, m, c, s, l); + } +} + +void bicenter(int s) +{ + if (s & 1) return; + + /* Pick two of the half-size building blocks, allowing + repetition. */ + unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; +} + +int main() +{ + xint n; + for (n = 1; n < MAX_N; n++) { + tree(0, n, 1, 1, n); + bicenter(n); + printf("%"FMT": %"FMT"\n", n, unrooted[n]); + } + + return 0; +} diff --git a/Task/Paraffins/C/paraffins-2.c b/Task/Paraffins/C/paraffins-2.c new file mode 100644 index 0000000000..96e36e9e0c --- /dev/null +++ b/Task/Paraffins/C/paraffins-2.c @@ -0,0 +1,106 @@ +#include +#include +#include + +#define MAX_BRANCH 4 +#define MAX_N 500 + +mpz_t bcache[MAX_N + 1]; +mpz_t ucache[MAX_N + 1]; +mpz_t *rcache[MAX_N + 1][MAX_BRANCH + 1]; + +mpz_t tmp1, tmp2; +void choose(mpz_t r, mpz_t m, int k) +{ + int i; + mpz_set(r, m); + + mpz_add_ui(tmp1, m, 1); + for (i = 1; i < k; ) { + mpz_mul(r, r, tmp1); + mpz_divexact_ui(r, r, ++i); + + if (i >= k) break; + mpz_add_ui(tmp1, tmp1, 1); + } +} + +mpz_t rtmp1, rtmp2; +void calc_rooted(mpz_t res, int n, int b, int r) +{ + mpz_set_ui(res, 0); + + if (n == 1 && b == 0 && r == 0) { + mpz_set_ui(res, 1); + return; + } else if (n <= b || n <= r || n == 1 || b == 0 || r == 0) + return; + + int b1, r1; + for (b1 = 1; b1 <= b && r * b1 < n; b1++) { + choose(rtmp1, bcache[r], b1); + mpz_set_ui(rtmp2, 0); + for (r1 = 0; r1 < r && r1 + r * b1 < n; r1++) + mpz_add(rtmp2, rtmp2, rcache[n - r * b1][b - b1][r1]); + + mpz_addmul(res, rtmp1, rtmp2); + } +} + +void calc_first_branch(int n) +{ + int b, r; + mpz_init_set_ui(bcache[n], 0); + + for (b = 0; b < MAX_BRANCH; b++) + for (r = 0; r < n; r++) + mpz_add(bcache[n], bcache[n], rcache[n][b][r]); +} + +void calc_unrooted(int n) +{ + int b, r; + + for (b = 0; b <= MAX_BRANCH; b++) { + mpz_t *p = malloc(sizeof(mpz_t) * n); + rcache[n][b] = p; + for (r = 0; r < n; r++) { + mpz_init(p[r]); + calc_rooted(p[r], n, b, r); + } + } + + calc_first_branch(n); + + mpz_init_set_ui(ucache[n], 0); + for (r = 0; r * 2 < n; r++) + for (b = 0; b <= MAX_BRANCH; b++) + mpz_add(ucache[n], ucache[n], rcache[n][b][r]); + + if (!(n & 1)) { + mpz_add_ui(rtmp1, bcache[n/2], 1); + mpz_mul(rtmp1, rtmp1, bcache[n/2]); + mpz_divexact_ui(rtmp1, rtmp1, 2); + mpz_add(ucache[n], ucache[n], rtmp1); + } +} + +void init(void) +{ + mpz_init(tmp1), mpz_init(tmp2); + mpz_init(rtmp1), mpz_init(rtmp2); +} + +int main(void) +{ + int i; + + init(); + + for (i = 0; i <= MAX_N; i++) { + calc_unrooted(i); + gmp_printf("%d: %Zd\n", i, ucache[i]); + } + + return 0; +} diff --git a/Task/Paraffins/D/paraffins.d b/Task/Paraffins/D/paraffins.d new file mode 100644 index 0000000000..de4ca5193b --- /dev/null +++ b/Task/Paraffins/D/paraffins.d @@ -0,0 +1,44 @@ +import std.stdio, std.bigint; + +enum uint nMax = 250; +enum uint nBranches = 4; + +__gshared BigInt[nMax + 1] rooted = [1.BigInt, 1.BigInt /*...*/], + unrooted = [1.BigInt, 1.BigInt /*...*/]; + +void tree(in uint br, in uint n, in uint l, in uint inSum, + in BigInt cnt) nothrow { + __gshared static BigInt[nBranches] c; + + uint sum = inSum; + foreach (immutable b; br + 1 .. nBranches + 1) { + sum += n; + if (sum > nMax || (l * 2 >= sum && b >= nBranches)) + return; + if (b == br + 1) { + c[br] = rooted[n] * cnt; + } else { + c[br] *= rooted[n] + b - br - 1; + c[br] /= b - br; + } + if (l * 2 < sum) + unrooted[sum] += c[br]; + if (b < nBranches) + rooted[sum] += c[br]; + foreach_reverse (immutable m; 1 .. n) + tree(b, m, l, sum, c[br]); + } +} + +void bicenter(in uint s) nothrow { + if ((s & 1) == 0) + unrooted[s] += rooted[s / 2] * (rooted[s / 2] + 1) / 2; +} + +void main() { + foreach (immutable n; 1 .. nMax + 1) { + tree(0, n, n, 1, 1.BigInt); + n.bicenter; + writeln(n, ": ", unrooted[n]); + } +} diff --git a/Task/Paraffins/Go/paraffins.go b/Task/Paraffins/Go/paraffins.go new file mode 100644 index 0000000000..b0fa2764c3 --- /dev/null +++ b/Task/Paraffins/Go/paraffins.go @@ -0,0 +1,61 @@ +package main + +import ( + "fmt" + "math/big" +) + +const branches = 4 +const nMax = 500 + +var rooted, unrooted [nMax + 1]big.Int +var c [branches]big.Int +var tmp = new(big.Int) +var one = big.NewInt(1) + +func tree(br, n, l, sum int, cnt *big.Int) { + for b := br + 1; b <= branches; b++ { + sum += n + if sum > nMax { + return + } + if l*2 >= sum && b >= branches { + return + } + if b == br+1 { + c[br].Mul(&rooted[n], cnt) + } else { + tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) + c[br].Mul(&c[br], tmp) + c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) + } + if l*2 < sum { + unrooted[sum].Add(&unrooted[sum], &c[br]) + } + if b < branches { + rooted[sum].Add(&rooted[sum], &c[br]) + } + for m := n - 1; m > 0; m-- { + tree(b, m, l, sum, &c[br]) + } + } +} + +func bicenter(s int) { + if s&1 == 0 { + tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) + unrooted[s].Add(&unrooted[s], tmp) + } +} + +func main() { + rooted[0].SetInt64(1) + rooted[1].SetInt64(1) + unrooted[0].SetInt64(1) + unrooted[1].SetInt64(1) + for n := 1; n <= nMax; n++ { + tree(0, n, n, 1, big.NewInt(1)) + bicenter(n) + fmt.Printf("%d: %d\n", n, &unrooted[n]) + } +} diff --git a/Task/Paraffins/Haskell/paraffins.hs b/Task/Paraffins/Haskell/paraffins.hs new file mode 100644 index 0000000000..648ca1bd99 --- /dev/null +++ b/Task/Paraffins/Haskell/paraffins.hs @@ -0,0 +1,32 @@ +import Data.Array + +choose :: Integer -> Int -> Integer +choose m k = let kk = toInteger k in (product [m..m+kk-1]) `div` (product [1..kk]) + +max_branches = 4 +max_nodes = 200 + +bcache = listArray (0, max_nodes) + [sum[rcache!n!b!r | r <- [0..n], b <- [0..max_branches-1]] | n <- [0..max_nodes]] +build_block = (bcache !) + +rcache = listArray (0,max_nodes) [arr_b i | i <- [0..max_nodes]] where + arr_b n = listArray(0,max_branches) [arr_r b n | b <- [0..max_branches]] + arr_r b n = listArray(0,n) [rooted n b r | r <- [0..n]] + +rooted 1 0 0 = 1 +rooted 1 _ _ = 0 +rooted _ 0 _ = 0 +rooted _ _ 0 = 0 +rooted n b r + | (n <= b) || (n <= r) = 0 + | otherwise = sum [(firsts b1) * (rests b1) | b1 <- [1..b], r * b1 < n] where + firsts = choose (build_block r) + rests bb = sum [rcache!(n-r*bb)!(b - bb)!r1 | r1 <- [0..r-1], r1 < (n-r*bb)] + +unrooted n = unicenter + bycenter where + unicenter = sum [ rcache!n!b!r | b <- [0..max_branches], r <-[0..n], r * 2 < n] + bycenter| odd n = 0 + | otherwise = x * (x + 1) `div` 2 where x = build_block (n `div` 2) + +main = mapM_ print $ map (\x->(x, unrooted x)) [1..max_nodes] diff --git a/Task/Paraffins/J/paraffins-1.j b/Task/Paraffins/J/paraffins-1.j new file mode 100644 index 0000000000..c2b55326bc --- /dev/null +++ b/Task/Paraffins/J/paraffins-1.j @@ -0,0 +1,32 @@ +part3=: ;@((<@([(],.(-+/"1))],.]+i.@(]-~1+<.@-:@-))"0 i.@>:@<.@%&3)) + +part4=: 3 :0 +ij=.; (,.]+i.@:(]-~1+[:<.3%~y-]))&.> i.1+<.y%4 +(,.y - +/"1) ; (<@(],"1 0 <.@-:@(y-[) (] + i.@>:@-) {:@] >. (>.-:y)-[)~+/)"1 ij +) + +c0=: */@:{ +c1=: 13 :'(*-:@(*>:))/y{~}:x' +c2=: 13 :'(*-:@(*>:))~/y{~}.x' +c3=: 13 :'3!2+y{~{.x' + +radGenN=: [:;[:(],[:+/c0`c1`c2`c3@.(#.@(}.=}:)@[)"1)&.>/(<1x),~part3&.>@ i.@- + +bcpGenN=: [: , 0 ,.~ -:@(*>:)@({~i.) + +c11=: 13 :'*/(y{~0 1{x), -:(*>:)y{~{:x' +c12=: 13 :'*/(y{~0 3{x), -:(*>:)y{~2{x' +c13=: 13 :'*/(y{~{.x) , 3!2+ y{~{: x' +c14=: 13 :'*/(y{~_2{.x), -:(*>:)y{~{.x' +c15=: 13 :'*/ -:(*>:) y{~0 3{x' +c16=: 13 :'*/(y{~{:x) , 3!2+ y{~{. x' +c17=: 13 :'4!3+y{~{.x' + +cassl=: c0`c11`c12`c13`c14`c15`c16`c17 + +ccpGenN=: 4 :0 +if. 0=y do. i.0 return. end. +y{.2({.,0,}.) 0,+/@:(x cassl@.(#.@(}.=}:)@[)"1~[)@:part4"0 [1-.~i.y-1 +) + +NofParaff=: {. radGenN ((ccpGenN +:) + bcpGenN ) 2&|+<.@-: diff --git a/Task/Paraffins/J/paraffins-2.j b/Task/Paraffins/J/paraffins-2.j new file mode 100644 index 0000000000..0dbd3e9574 --- /dev/null +++ b/Task/Paraffins/J/paraffins-2.j @@ -0,0 +1,7 @@ + 6 6 $ NofParaff 36 + 1 1 1 1 2 3 + 5 9 18 35 75 159 + 355 802 1858 4347 10359 24894 + 60523 148284 366319 910726 2278658 5731580 + 14490245 36797588 93839412 240215803 617105614 1590507121 +4111846763 10660307791 27711253769 72214088660 188626236139 493782952902 diff --git a/Task/Paraffins/Mathematica/paraffins.math b/Task/Paraffins/Mathematica/paraffins.math new file mode 100644 index 0000000000..9b885a3530 --- /dev/null +++ b/Task/Paraffins/Mathematica/paraffins.math @@ -0,0 +1,14 @@ +G000602[n_] := + Block[{x}, + x*CycleIndexPolynomial[SymmetricGroup[4], + Table[ComposeSeries[#, x^i + O[x]^(n + 1)], {i, 4}]] - + CycleIndexPolynomial[SymmetricGroup[2], + Table[ComposeSeries[# - 1, x^i + O[x]^(n + 1)], {i, 2}]] + + ComposeSeries[#, x^2 + O[x]^(n + 1)] &@ + Fold[Series[ + 1 + x/6 (#1^3 + 3 #1 ComposeSeries[#1, x^2 + O[x]^#2] + + 2 ComposeSeries[#1, x^3 + O[x]^#2]), {x, 0, #2}] &, + 1 + O[x], Range[n + 1]]]; +A000602[n_] := SeriesCoefficient[G000602[n], n]; +A000602List[n_] := CoefficientList[G000602[n], x]; +Grid@Transpose@{Range[0, 200], A000602List@200} diff --git a/Task/Paraffins/Pascal/paraffins.pascal b/Task/Paraffins/Pascal/paraffins.pascal new file mode 100644 index 0000000000..1fbdfb9b3c --- /dev/null +++ b/Task/Paraffins/Pascal/paraffins.pascal @@ -0,0 +1,88 @@ +Program Paraffins; + +uses + gmp; + +const + max_n = 500; + branch = 4; + +var + rooted, unrooted: array [0 .. max_n-1] of mpz_t; + c: array [0 .. branch-1] of mpz_t; + cnt, tmp: mpz_t; + n: integer; + fmt: pchar; + sum: integer; + +procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t); + var + b, m: integer; + begin + for b := br + 1 to branch do + begin + sum := sum + n; + if sum >= max_n then + exit; + + (* prevent unneeded long math *) + if (l * 2 >= sum) and (b >= branch) then + exit; + + if b = (br + 1) then + mpz_mul(c[br], rooted[n], cnt) + else + begin + mpz_add_ui(tmp, rooted[n], b - br - 1); + mpz_mul(c[br], c[br], tmp); + mpz_divexact_ui(c[br], c[br], b - br); + end; + + if l * 2 < sum then + mpz_add(unrooted[sum], unrooted[sum], c[br]); + + if b < branch then + begin + mpz_add(rooted[sum], rooted[sum], c[br]); + for m := n-1 downto 1 do + tree(b, m, l, sum, c[br]); + end; + end; + end; + +procedure bicenter(s: integer); +begin + if odd(s) then + exit; + mpz_add_ui(tmp, rooted[s div 2], 1); + mpz_mul(tmp, rooted[s div 2], tmp); + mpz_tdiv_q_2exp(tmp, tmp, 1); + + mpz_add(unrooted[s], unrooted[s], tmp); +end; + +begin + for n := 0 to 1 do + begin + mpz_init_set_ui(rooted[n], 1); + mpz_init_set_ui(unrooted[n], 1); + end; + for n := 2 to max_n-1 do + begin + mpz_init_set_ui(rooted[n], 0); + mpz_init_set_ui(unrooted[n], 0); + end; + for n := 0 to BRANCH-1 do + mpz_init(c[n]); + + mpz_init(tmp); + + mpz_init_set_ui(cnt, 1); + sum := 1; + for n := 1 to MAX_N do + begin + tree(0, n, n, sum, cnt); + bicenter(n); + mp_printf('%d: %Zd'+chr(13)+chr(10), n, @unrooted[n]); + end; +end. diff --git a/Task/Paraffins/Perl-6/paraffins.pl6 b/Task/Paraffins/Perl-6/paraffins.pl6 new file mode 100644 index 0000000000..6dba8d9030 --- /dev/null +++ b/Task/Paraffins/Perl-6/paraffins.pl6 @@ -0,0 +1,45 @@ +sub count-unrooted-trees(Int $max-branches, Int $max-weight) { + my @rooted = 1,1,0 xx $max-weight - 1; + my @unrooted = 1,1,0 xx $max-weight - 1; + + sub count-trees-with-centroid(Int $radius) { + sub add-branches( + Int $branches, # number of branches to add + Int $w, # weight of heaviest branch to add + Int $weight is copy, # accumulated weight of tree + Int $choices is copy, # number of choices so far + ) { + $choices *= @rooted[$w]; + for 1 .. $branches -> $b { + ($weight += $w) <= $max-weight or last; + @unrooted[$weight] += $choices if $weight > 2*$radius; + if $b < $branches { + @rooted[$weight] += $choices; + add-branches($branches - $b, $_, $weight, $choices) for 1 ..^ $w; + $choices = $choices * (@rooted[$w] + $b) div ($b + 1); + } + } + } + add-branches($max-branches, $radius, 1, 1); + } + + sub count-trees-with-bicentroid(Int $weight) { + if $weight %% 2 { + my \halfs = @rooted[$weight div 2]; + @unrooted[$weight] += (halfs * (halfs + 1)) div 2; + } + } + + gather { + take 1; + for 1 .. $max-weight { + count-trees-with-centroid($_); + count-trees-with-bicentroid($_); + take @unrooted[$_]; + } + } +} + +my constant N = 100; +my @paraffins := count-unrooted-trees(4, N); +say .fmt('%3d'), ': ', @paraffins[$_] for 1 .. 30, N; diff --git a/Task/Paraffins/Perl/paraffins.pl b/Task/Paraffins/Perl/paraffins.pl new file mode 100644 index 0000000000..102e39684e --- /dev/null +++ b/Task/Paraffins/Perl/paraffins.pl @@ -0,0 +1,40 @@ +use Math::GMPz; + +my $nmax = 250; +my $nbranches = 4; + +my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; +my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; +my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1; + +sub tree { + my($br, $n, $l, $sum, $cnt) = @_; + for my $b ($br+1 .. $nbranches) { + $sum += $n; + return if $sum > $nmax || ($l*2 >= $sum && $b >= $nbranches); + if ($b == $br+1) { + $c[$br] = $rooted[$n] * $cnt; + } else { + $c[$br] *= $rooted[$n] + $b - $br - 1; + $c[$br] /= $b - $br; + } + $unrooted[$sum] += $c[$br] if $l*2 < $sum; + return if $b >= $nbranches; + $rooted[$sum] += $c[$br]; + for my $m (reverse 1 .. $n-1) { + next if $sum+$m > $nmax; + tree($b, $m, $l, $sum, $c[$br]); + } + } +} + +sub bicenter { + my $s = shift; + $unrooted[$s] += $rooted[$s/2] * ($rooted[$s/2]+1) / 2 unless $s & 1; +} + +for my $n (1 .. $nmax) { + tree(0, $n, $n, 1, Math::GMPz->new(1)); + bicenter($n); + print "$n: $unrooted[$n]\n"; +} diff --git a/Task/Paraffins/Pike/paraffins.pike b/Task/Paraffins/Pike/paraffins.pike new file mode 100644 index 0000000000..dae19d79d6 --- /dev/null +++ b/Task/Paraffins/Pike/paraffins.pike @@ -0,0 +1,63 @@ +int MAX_N = 300; +int BRANCH = 4; + +array ra = allocate(MAX_N); +array unrooted = allocate(MAX_N); + +void tree(int br, int n, int l, int sum, int cnt) +{ + int c; + for (int b = br + 1; b < BRANCH + 1; b++) + { + sum += n; + if (sum >= MAX_N) + return; + + // prevent unneeded long math + if (l * 2 >= sum && b >= BRANCH) + return; + + if (b == br + 1) + { + c = ra[n] * cnt; + } + else + { + c = c * (ra[n] + (b - br - 1)) / (b - br); + } + + if (l * 2 < sum) + unrooted[sum] += c; + + if (b < BRANCH) + { + ra[sum] += c; + for (int m=1; m < n; m++) + { + tree(b, m, l, sum, c); + } + } + } +} + +void bicenter(int s) +{ + if (!(s & 1)) + { + int aux = ra[s / 2]; + unrooted[s] += aux * (aux + 1) / 2; + } +} + + +void main() +{ + ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1; + + for (int n = 1; n < MAX_N; n++) + { + tree(0, n, n, 1, 1); + bicenter(n); + write("%d: %d\n", n, unrooted[n]); + } +} diff --git a/Task/Paraffins/Python/paraffins.py b/Task/Paraffins/Python/paraffins.py new file mode 100644 index 0000000000..5a8a15f5d0 --- /dev/null +++ b/Task/Paraffins/Python/paraffins.py @@ -0,0 +1,53 @@ +try: + import psyco + psyco.full() +except ImportError: + pass + +MAX_N = 300 +BRANCH = 4 + +ra = [0] * MAX_N +unrooted = [0] * MAX_N + +def tree(br, n, l, sum = 1, cnt = 1): + global ra, unrooted, MAX_N, BRANCH + for b in xrange(br + 1, BRANCH + 1): + sum += n + if sum >= MAX_N: + return + + # prevent unneeded long math + if l * 2 >= sum and b >= BRANCH: + return + + if b == br + 1: + c = ra[n] * cnt + else: + c = c * (ra[n] + (b - br - 1)) / (b - br) + + if l * 2 < sum: + unrooted[sum] += c + + if b < BRANCH: + ra[sum] += c; + for m in range(1, n): + tree(b, m, l, sum, c) + +def bicenter(s): + global ra, unrooted + if not (s & 1): + aux = ra[s / 2] + unrooted[s] += aux * (aux + 1) / 2 + + +def main(): + global ra, unrooted, MAX_N + ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1 + + for n in xrange(1, MAX_N): + tree(0, n, n) + bicenter(n) + print "%d: %d" % (n, unrooted[n]) + +main() diff --git a/Task/Paraffins/README b/Task/Paraffins/README new file mode 100644 index 0000000000..afb6f0d9d4 --- /dev/null +++ b/Task/Paraffins/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Paraffins diff --git a/Task/Paraffins/REXX/paraffins.rexx b/Task/Paraffins/REXX/paraffins.rexx new file mode 100644 index 0000000000..65063a0917 --- /dev/null +++ b/Task/Paraffins/REXX/paraffins.rexx @@ -0,0 +1,27 @@ +/*REXX program to enumerate number # paraffins for N atoms of carbon.*/ +parse arg nodes .; if nodes=='' then nodes=100 /*Not given? Use default*/ + rooted. = 0; rooted.0=1; rooted.1=1 /*define base rooted #s.*/ +unrooted. = 0; unrooted.0=1; unrooted.1=1 /* " " unrooted " */ +numeric digits max(9,nodes%2) /*may use gi-hugeic nums*/ +w=length(nodes) /*for formatted display.*/ +say right(0,w) unrooted.0 /*··· zero carbon atoms.*/ + /* [↓] process nodes. */ + do C=1 for nodes; h=C%2 /*C: # of carbon atoms.*/ + call tree 0, C, C, 1, 1 /* [↓] if C is even. */ + if C//2==0 then unrooted.C=unrooted.C + rooted.h*(rooted.h+1)%2 + say right(C,w) unrooted.C /*display formatted #'s.*/ + end /*C*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TREE subroutine─────────────────────*/ +tree: procedure expose rooted. unrooted. nodes #. /*recursive.*/ +parse arg br,n,L,sum,cnt; nm=n-1; LL=L+L; brp=br+1 + do b=brp to 4; sum=sum+n; if sum>nodes then leave + if b==4 then if LL>=sum then leave + if b==brp then #.br=rooted.n*cnt + else #.br=#.br*(rooted.n+b-brp)%(b-br) + if LL= s MAX_N) (return)) + (define c (* (choose (vector-ref rooted n) (- b br)) cnt)) + (when (< (* l 2) s) (vector-inc! unrooted s c)) + (when (= b BRANCH) (return)) + (vector-inc! rooted s c) + (for ([m (in-range (sub1 n) 0 -1)]) (tree b m c s l))))) + +(define (bicenter s) + (when (even? s) + (vector-inc! unrooted s (* (vector-ref rooted (/ s 2)) + (add1 (vector-ref rooted (/ s 2))) + 1/2)))) + +(for ([n (in-range 1 MAX_N)]) + (tree 0 n 1 1 n) + (bicenter n) + (printf "~a: ~a\n" n (vector-ref unrooted n))) diff --git a/Task/Paraffins/Ruby/paraffins.rb b/Task/Paraffins/Ruby/paraffins.rb new file mode 100644 index 0000000000..de5ab8f422 --- /dev/null +++ b/Task/Paraffins/Ruby/paraffins.rb @@ -0,0 +1,36 @@ +MAX_N = 500 +BRANCH = 4 + +def tree(br, n, l=n, sum=1, cnt=1) + for b in br+1 .. BRANCH + sum += n + return if sum >= MAX_N + # prevent unneeded long math + return if l * 2 >= sum and b >= BRANCH + if b == br + 1 + c = $ra[n] * cnt + else + c = c * ($ra[n] + (b - br - 1)) / (b - br) + end + $unrooted[sum] += c if l * 2 < sum + next if b >= BRANCH + $ra[sum] += c + (1...n).each {|m| tree(b, m, l, sum, c)} + end +end + +def bicenter(s) + return if s.odd? + aux = $ra[s / 2] + $unrooted[s] += aux * (aux + 1) / 2 +end + +$ra = [0] * MAX_N +$unrooted = [0] * MAX_N + +$ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1 +for n in 1...MAX_N + tree(0, n) + bicenter(n) + puts "%d: %d" % [n, $unrooted[n]] +end diff --git a/Task/Paraffins/Seed7/paraffins.seed7 b/Task/Paraffins/Seed7/paraffins.seed7 new file mode 100644 index 0000000000..8f54625ada --- /dev/null +++ b/Task/Paraffins/Seed7/paraffins.seed7 @@ -0,0 +1,62 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const integer: max_n is 500; +const integer: branch is 4; + +var array bigInteger: rooted is max_n times 0_; +var array bigInteger: unrooted is max_n times 0_; + +const proc: tree (in integer: br, in integer: n, in integer: l, in var integer: sum, in bigInteger: cnt) is func + local + var integer: b is 0; + var integer: m is 0; + var bigInteger: c is 0_; + var bigInteger: diff is 0_; + begin + for b range br + 1 to branch do + sum +:= n; + if sum > max_n or l * 2 >= sum and b >= branch then + # Prevent unneeded long math. + b := branch; + else + if b = (br + 1) then + c := rooted[n] * cnt; + else + diff := bigInteger conv (b - br); + c := c * (rooted[n] + pred(diff)) div diff; + end if; + if l * 2 < sum then + unrooted[sum] +:= c; + end if; + if b < branch then + rooted[sum] +:= c; + for m range n-1 downto 1 do + tree(b, m, l, sum, c); + end for; + end if; + end if; + end for; + end func; + +const proc: bicenter (in integer: s) is func + begin + if not odd(s) then + unrooted[s] +:= (rooted[s div 2] * succ(rooted[s div 2])) >> 1; + end if; + end func; + +const proc: main is func + local + var bigInteger: cnt is 1_; + var integer: n is 0; + var integer: sum is 1; + begin + rooted[1] := 1_; + unrooted[1] := 1_; + for n range 1 to max_n do + tree(0, n, n, sum, cnt); + bicenter(n); + writeln(n <& ": " <& unrooted[n]); + end for; + end func; diff --git a/Task/Paraffins/Tcl/paraffins.tcl b/Task/Paraffins/Tcl/paraffins.tcl new file mode 100644 index 0000000000..562fcd9767 --- /dev/null +++ b/Task/Paraffins/Tcl/paraffins.tcl @@ -0,0 +1,46 @@ +package require Tcl 8.5 + +set maxN 200 +set rooted [lrepeat $maxN 0] +lset rooted 0 1; lset rooted 1 1 +set unrooted $rooted + +proc choose {m k} { + if {$k == 1} { + return $m + } + for {set r $m; set i 1} {$i < $k} {incr i} { + set r [expr {$r * ($m+$i) / ($i+1)}] + } + return $r +} + +proc tree {br n cnt sum l} { + global maxN rooted unrooted + for {set b [expr {$br+1}]} {$b <= 4} {incr b} { + set s [expr {$sum + ($b-$br) * $n}] + if {$s >= $maxN} return + set c [expr {[choose [lindex $rooted $n] [expr {$b-$br}]] * $cnt}] + if {$l*2 < $s} { + lset unrooted $s [expr {[lindex $unrooted $s] + $c}] + } + if {$b == 4} return + lset rooted $s [expr {[lindex $rooted $s] + $c}] + for {set m $n} {[incr m -1]} {} { + tree $b $m $c $s $l + } + } +} + +proc bicenter {s} { + if {$s & 1} return + global unrooted rooted + set r [lindex $rooted [expr {$s/2}]] + lset unrooted $s [expr {[lindex $unrooted $s] + $r*($r+1)/2}] +} + +for {set n 1} {$n < $maxN} {incr n} { + tree 0 $n 1 1 $n + bicenter $n + puts "${n}: [lindex $unrooted $n]" +} diff --git a/Task/Parse-an-IP-Address/00DESCRIPTION b/Task/Parse-an-IP-Address/00DESCRIPTION new file mode 100644 index 0000000000..2159dd0f8b --- /dev/null +++ b/Task/Parse-an-IP-Address/00DESCRIPTION @@ -0,0 +1,27 @@ +The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. + +Taking the following as inputs: +{| border="1" cellspacing="0" cellpadding=2 +|- +|127.0.0.1 +|The "localhost" IPv4 address +|- +|127.0.0.1:80 +|The "localhost" IPv4 address, with a specified port (80) +|- +|::1 +|The "localhost" IPv6 address +|- +|[::1]:80 +|The "localhost" IPv6 address, with a specified port (80) +|- +|2605:2700:0:3::4713:93e3 +|Rosetta Code's primary server's public IPv6 address +|- +|[2605:2700:0:3::4713:93e3]:80 +|Rosetta Code's primary server's public IPv6 address, with a specified port (80) +|} + +Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. + +For example 127.0.0.1 has the address number 7F000001 (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the address number FFFF7F000001 (281472812449793 decimal). Meanwhile ::1 has address number 1 and serves the same purpose in the ipv6 address space that 127.0.0.1 serves in the ipv4 address space. diff --git a/Task/Parse-an-IP-Address/C/parse-an-ip-address-1.c b/Task/Parse-an-IP-Address/C/parse-an-ip-address-1.c new file mode 100644 index 0000000000..50e84aee31 --- /dev/null +++ b/Task/Parse-an-IP-Address/C/parse-an-ip-address-1.c @@ -0,0 +1,298 @@ +#include +#include + + +static unsigned int _parseDecimal ( const char** pchCursor ) +{ + unsigned int nVal = 0; + char chNow; + while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) + { + //shift digit in + nVal *= 10; + nVal += chNow - '0'; + + ++*pchCursor; + } + return nVal; +} + + + +static unsigned int _parseHex ( const char** pchCursor ) +{ + unsigned int nVal = 0; + char chNow; + while ( chNow = **pchCursor & 0x5f, //(collapses case, but mutilates digits) + (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || + (chNow >= 'A' && chNow <= 'F') + ) + { + unsigned char nybbleValue; + chNow -= 0x10; //scootch digital values down; hex now offset by x31 + nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); + //shift nybble in + nVal <<= 4; + nVal += nybbleValue; + + ++*pchCursor; + } + return nVal; +} + + + +//Parse a textual IPv4 or IPv6 address, optionally with port, into a binary +//array (for the address, in network order), and an optionally provided port. +//Also, indicate which of those forms (4 or 6) was parsed. Return true on +//success. ppszText must be a nul-terminated ASCII string. It will be +//updated to point to the character which terminated parsing (so you can carry +//on with other things. abyAddr must be 16 bytes. You can provide NULL for +//abyAddr, nPort, bIsIPv6, if you are not interested in any of those +//informations. If we request port, but there is no port part, then nPort will +//be set to 0. There may be no whitespace leading or internal (though this may +//be used to terminate a successful parse. +//Note: the binary address and integer port are in network order. +int ParseIPv4OrIPv6 ( const char** ppszText, + unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) +{ + unsigned char* abyAddrLocal; + unsigned char abyDummyAddr[16]; + + //find first colon, dot, and open bracket + const char* pchColon = strchr ( *ppszText, ':' ); + const char* pchDot = strchr ( *ppszText, '.' ); + const char* pchOpenBracket = strchr ( *ppszText, '[' ); + const char* pchCloseBracket = NULL; + + + //we'll consider this to (probably) be IPv6 if we find an open + //bracket, or an absence of dots, or if there is a colon, and it + //precedes any dots that may or may not be there + int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || + ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); + //OK, now do a little further sanity check our initial guess... + if ( bIsIPv6local ) + { + //if open bracket, then must have close bracket that follows somewhere + pchCloseBracket = strchr ( *ppszText, ']' ); + if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || + pchCloseBracket < pchOpenBracket ) ) + return 0; + } + else //probably ipv4 + { + //dots must exist, and precede any colons + if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) + return 0; + } + + //we figured out this much so far.... + if ( NULL != pbIsIPv6 ) + *pbIsIPv6 = bIsIPv6local; + + //especially for IPv6 (where we will be decompressing and validating) + //we really need to have a working buffer even if the caller didn't + //care about the results. + abyAddrLocal = abyAddr; //prefer to use the caller's + if ( NULL == abyAddrLocal ) //but use a dummy if we must + abyAddrLocal = abyDummyAddr; + + //OK, there should be no correctly formed strings which are miscategorized, + //and now any format errors will be found out as we continue parsing + //according to plan. + if ( ! bIsIPv6local ) //try to parse as IPv4 + { + //4 dotted quad decimal; optional port if there is a colon + //since there are just 4, and because the last one can be terminated + //differently, I'm just going to unroll any potential loop. + unsigned char* pbyAddrCursor = abyAddrLocal; + unsigned int nVal; + const char* pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); //get first val + if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) //must be in range and followed by dot and nonempty + return 0; + *(pbyAddrCursor++) = (unsigned char) nVal; //stick it in addr + ++(*ppszText); //past the dot + + pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); //get second val + if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) + return 0; + *(pbyAddrCursor++) = (unsigned char) nVal; + ++(*ppszText); //past the dot + + pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); //get third val + if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) + return 0; + *(pbyAddrCursor++) = (unsigned char) nVal; + ++(*ppszText); //past the dot + + pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); //get fourth val + if ( nVal > 255 || pszTextBefore == *ppszText ) //(we can terminate this one in several ways) + return 0; + *(pbyAddrCursor++) = (unsigned char) nVal; + + if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it + { + unsigned short usPortNetwork; //save value in network order + ++(*ppszText); //past the colon + pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); + if ( nVal > 65535 || pszTextBefore == *ppszText ) + return 0; + ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; + ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); + *pnPort = usPortNetwork; + return 1; + } + else //finished just with ip address + { + if ( NULL != pnPort ) + *pnPort = 0; //indicate we have no port part + return 1; + } + } + else //try to parse as IPv6 + { + unsigned char* pbyAddrCursor; + unsigned char* pbyZerosLoc; + int bIPv4Detected; + int nIdx; + //up to 8 16-bit hex quantities, separated by colons, with at most one + //empty quantity, acting as a stretchy run of zeroes. optional port + //if there are brackets followed by colon and decimal port number. + //A further form allows an ipv4 dotted quad instead of the last two + //16-bit quantities, but only if in the ipv4 space ::ffff:x:x . + if ( NULL != pchOpenBracket ) //start past the open bracket, if it exists + *ppszText = pchOpenBracket + 1; + pbyAddrCursor = abyAddrLocal; + pbyZerosLoc = NULL; //if we find a 'zero compression' location + bIPv4Detected = 0; + for ( nIdx = 0; nIdx < 8; ++nIdx ) //we've got up to 8 of these, so we will use a loop + { + const char* pszTextBefore = *ppszText; + unsigned nVal =_parseHex ( ppszText ); //get value; these are hex + if ( pszTextBefore == *ppszText ) //if empty, we are zero compressing; note the loc + { + if ( NULL != pbyZerosLoc ) //there can be only one! + { + //unless it's a terminal empty field, then this is OK, it just means we're done with the host part + if ( pbyZerosLoc == pbyAddrCursor ) + { + --nIdx; + break; + } + return 0; //otherwise, it's a format error + } + if ( ':' != **ppszText ) //empty field can only be via : + return 0; + if ( 0 == nIdx ) //leading zero compression requires an extra peek, and adjustment + { + ++(*ppszText); + if ( ':' != **ppszText ) + return 0; + } + + pbyZerosLoc = pbyAddrCursor; + ++(*ppszText); + } + else + { + if ( '.' == **ppszText ) //special case of ipv4 convenience notation + { + //who knows how to parse ipv4? we do! + const char* pszTextlocal = pszTextBefore; //back it up + unsigned char abyAddrlocal[16]; + int bIsIPv6local; + int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); + *ppszText = pszTextlocal; //success or fail, remember the terminating char + if ( ! bParseResultlocal || bIsIPv6local ) //must parse and must be ipv4 + return 0; + //transfer addrlocal into the present location + *(pbyAddrCursor++) = abyAddrlocal[0]; + *(pbyAddrCursor++) = abyAddrlocal[1]; + *(pbyAddrCursor++) = abyAddrlocal[2]; + *(pbyAddrCursor++) = abyAddrlocal[3]; + ++nIdx; //pretend like we took another short, since the ipv4 effectively is two shorts + bIPv4Detected = 1; //remember how we got here for further validation later + break; //totally done with address + } + + if ( nVal > 65535 ) //must be 16 bit quantity + return 0; + *(pbyAddrCursor++) = nVal >> 8; //transfer in network order + *(pbyAddrCursor++) = nVal & 0xff; + if ( ':' == **ppszText ) //typical case inside; carry on + { + ++(*ppszText); + } + else //some other terminating character; done with this parsing parts + { + break; + } + } + } + + //handle any zero compression we found + if ( NULL != pbyZerosLoc ) + { + int nHead = (int)( pbyZerosLoc - abyAddrLocal ); //how much before zero compression + int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); //how much after zero compression + int nZeros = 16 - nTail - nHead; //how much zeros + memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); //scootch stuff down + memset ( pbyZerosLoc, 0, nZeros ); //clear the compressed zeros + } + + //validation of ipv4 subspace ::ffff:x.x + if ( bIPv4Detected ) + { + static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; + if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) + return 0; + } + + //close bracket + if ( NULL != pchOpenBracket ) + { + if ( ']' != **ppszText ) + return 0; + ++(*ppszText); + } + + if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it + { + const char* pszTextBefore; + unsigned int nVal; + unsigned short usPortNetwork; //save value in network order + ++(*ppszText); //past the colon + pszTextBefore = *ppszText; + pszTextBefore = *ppszText; + nVal =_parseDecimal ( ppszText ); + if ( nVal > 65535 || pszTextBefore == *ppszText ) + return 0; + ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; + ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); + *pnPort = usPortNetwork; + return 1; + } + else //finished just with ip address + { + if ( NULL != pnPort ) + *pnPort = 0; //indicate we have no port part + return 1; + } + } + +} + + +//simple version if we want don't care about knowing how much we ate +int ParseIPv4OrIPv6_2 ( const char* pszText, + unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) +{ + const char* pszTextLocal = pszText; + return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6); +} diff --git a/Task/Parse-an-IP-Address/C/parse-an-ip-address-2.c b/Task/Parse-an-IP-Address/C/parse-an-ip-address-2.c new file mode 100644 index 0000000000..85b31d5910 --- /dev/null +++ b/Task/Parse-an-IP-Address/C/parse-an-ip-address-2.c @@ -0,0 +1,80 @@ +#include + +... (above code for ParseIPv4OrIPv6 goes here) ... + +unsigned short htons ( unsigned short us ) +{ + return ( ((unsigned char*)&us)[0] << 8 ) + ((unsigned char*)&us)[1]; +} + +void dumpbin ( unsigned char* pbyBin, int nLen ) +{ + int i; + for ( i = 0; i < nLen; ++i ) + { + printf ( "%02x", pbyBin[i] ); + } +} + + +void testcase ( const char* pszTest ) +{ + unsigned char abyAddr[16]; + int bIsIPv6; + int nPort; + int bSuccess; + + printf ( "Test case '%s'\n", pszTest ); + const char* pszTextCursor = pszTest; + bSuccess = ParseIPv4OrIPv6 ( &pszTextCursor, abyAddr, &nPort, &bIsIPv6 ); + if ( ! bSuccess ) + { + printf ( "parse failed, at about index %d; rest: '%s'\n", pszTextCursor - pszTest, pszTextCursor ); + return; + } + + printf ( "addr: " ); + dumpbin ( abyAddr, bIsIPv6 ? 16 : 4 ); + printf ( "\n" ); + if ( 0 == nPort ) + printf ( "port absent" ); + else + printf ( "port: %d", htons ( nPort ) ); + printf ( "\n\n" ); + +} + + + +int main ( int argc, char* argv[] ) +{ + + //The "localhost" IPv4 address + testcase ( "127.0.0.1" ); + + //The "localhost" IPv4 address, with a specified port (80) + testcase ( "127.0.0.1:80" ); + //The "localhost" IPv6 address + testcase ( "::1" ); + //The "localhost" IPv6 address, with a specified port (80) + testcase ( "[::1]:80" ); + //Rosetta Code's primary server's public IPv6 address + testcase ( "2605:2700:0:3::4713:93e3" ); + //Rosetta Code's primary server's public IPv6 address, with a specified port (80) + testcase ( "[2605:2700:0:3::4713:93e3]:80" ); + + //ipv4 space + testcase ( "::ffff:192.168.173.22" ); + //ipv4 space with port + testcase ( "[::ffff:192.168.173.22]:80" ); + //trailing compression + testcase ( "1::" ); + //trailing compression with port + testcase ( "[1::]:80" ); + //'any' address compression + testcase ( "::" ); + //'any' address compression with port + testcase ( "[::]:80" ); + + return 0; +} diff --git a/Task/Parse-an-IP-Address/Go/parse-an-ip-address.go b/Task/Parse-an-IP-Address/Go/parse-an-ip-address.go new file mode 100644 index 0000000000..a281354f7c --- /dev/null +++ b/Task/Parse-an-IP-Address/Go/parse-an-ip-address.go @@ -0,0 +1,69 @@ +package main + +import ( + "errors" + "fmt" + "net" + "strconv" + "strings" +) + +func ParseIPPort(s string) (ip net.IP, port, space string, err error) { + ip = net.ParseIP(s) + if ip == nil { + var host string + host, port, err = net.SplitHostPort(s) + if err != nil { + return + } + if port != "" { + // This check only makes sense if service names are not allowed + if _, err = strconv.ParseUint(port, 10, 16); err != nil { + return + } + } + ip = net.ParseIP(host) + } + if ip == nil { + err = errors.New("invalid address format") + } else { + space = "IPv6" + if ip4 := ip.To4(); ip4 != nil { + space = "IPv4" + ip = ip4 + } + } + return +} + +func main() { + var testCases = []string{ + "127.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + } + max := len("Input") + for _, addr := range testCases { + if len(addr) > max { + max = len(addr) + } + } + fmt.Printf("%-*s %*s %-6s %s\n", max, "Input", + 2*net.IPv6len, "Address", "Space", "Port") + for _, addr := range testCases { + fmt.Printf("%-*s ", max, addr) + ip, port, space, err := ParseIPPort(addr) + if err != nil { + fmt.Println(err) + continue + } + fmt.Print(strings.Repeat(" ", net.IPv6len-len(ip))) + for _, b := range ip { + fmt.Printf("%02x", b) + } + fmt.Printf(" %-6s %s\n", space, port) + } +} diff --git a/Task/Parse-an-IP-Address/Icon/parse-an-ip-address.icon b/Task/Parse-an-IP-Address/Icon/parse-an-ip-address.icon new file mode 100644 index 0000000000..9c34e32cd8 --- /dev/null +++ b/Task/Parse-an-IP-Address/Icon/parse-an-ip-address.icon @@ -0,0 +1,81 @@ +link printf, hexcvt + +procedure main() + L := ["192.168.0.1", # private + "127.0.0.1", # loop back + "127.0.0.1:80", # loop back +port + "2001:db8:85a3:0:0:8a2e:370:7334", # doc, IPv6 for 555-1234 + "2001:db8:85a3::8a2e:370:7334", # doc + "::1", # loop back + "[::1]:80", # loop back +port + "::", # unspecified + "::ffff:192.168.0.1", # transition + "2605:2700:0:3::4713:93e3", # RC + "[2605:2700:0:3::4713:93e3]:80", # RC + "::ffff:71.19.147.227", # RC transition + "[::ffff:71.19.147.227]:80", # RC transition +port + "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443", # doc +port + "256.0.0.0", # invalid + "g::1"] # invalid + + every x := !L do { + if x ? (ip := ipmatch(), port := portmatch(), pos(0)) then { + if i := IPv4decode(ip) then + printf("%s is the IPv4 address = x'%s'",x,i) + else if i := IPv6decode(ip) then + printf("%s is the IPv6 address = x'%s'",x,i) + else { + printf("%s is not a valid IP address\n",x) + next + } + if \port then printf(" port=%s\n",port) else printf("\n") + } + else printf("%s is not an IP address\n",x) + } +end + + +procedure ipmatch() #: match an ip v4/v6 address +static c4,c6 +initial { + c4 := &digits ++ '.' + c6 := &digits ++ 'abcdef:' + } + suspend (="[" || ( (="::ffff:" || tab(many(c4))) | tab(many(c6)) ) || ="]") | + ( ="::ffff:" || tab(many(c4))) | tab(many(c6|c4)) +end + +procedure portmatch() #: match a port number + return (=":",0 < (65536 > tab(many(&digits)))) | &null +end + +procedure IPv4decode(s) #: match IPv4 to hex string + s ? ( ip := (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", + ip +:= (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", + ip +:= (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", + ip +:= (0 <= (256 > tab(many(&digits)))), + return right(hexstring(ip,,&lcase),8) ) +end + +procedure IPv6decode(s) #: IPv6 to hex string + s ?:= 2(="[", tab(-1), ="]") # remove any [] + if find(".",s) then # transitional + s ? ( tab(many(':0')), ="ffff:", + return right("ffff" || IPv4decode(tab(0)),32,"0") ) + else { + h := t := "" + s ? { + while x := tab(find(":")) do { # head + if *x <= 4 then h ||:= right(x,4,"0") + if ="::" then break + else move(1) + } + while x := tab(find(":")|0) do { # tail + if *x <= 4 then t ||:= right(x,4,"0") + move(1) | break + } + if x := h || repl("0",32-(*h+*t)) || t then # and insides + return x + } + } +end diff --git a/Task/Parse-an-IP-Address/J/parse-an-ip-address-1.j b/Task/Parse-an-IP-Address/J/parse-an-ip-address-1.j new file mode 100644 index 0000000000..a9cf66c3b1 --- /dev/null +++ b/Task/Parse-an-IP-Address/J/parse-an-ip-address-1.j @@ -0,0 +1,37 @@ +parseaddr=:3 :0 + if. '.' e. y do. + if. +./'::' E. y do. + parsehybrid y + else. + parseipv4 y + end. + else. + parseipv6 y + end. +) + +parseipv4=:3 :0 + 'addr port'=. 2{.<;._2 y,'::' + 4,((4#256)#._&".;._1'.',addr),_".port +) + +parseipv6=:3 :0 + 'addr port'=. 2{.<;._2 (y-.'['),']]' + split=. I. '::' E. addr + a1=. 8{. dfh;._2 (split {. addr),8#':' + a2=._8{. dfh;._1 (8#':'),split }. addr + 6,(65536x#.a1+a2),_".port-.':' +) + +parsehybrid=:3 :0 + 'kludge port'=. 2{.<;._2 (tolower y-.'['),']]' + addr=. _1 {:: <;._2 kludge,':' + assert. (kludge-:'::ffff:',addr) +. kludge-: '::',addr + 6,(16bffff00000000+1{parseipv4 addr),_".port-.':' +) + +fmt=:3 :0 + port=. '' + ((#y){.'v';'addr';'port')=. y + 'ipv',(":v),' ',(hfd addr),(#port)#' ',":port +) diff --git a/Task/Parse-an-IP-Address/J/parse-an-ip-address-2.j b/Task/Parse-an-IP-Address/J/parse-an-ip-address-2.j new file mode 100644 index 0000000000..42640df981 --- /dev/null +++ b/Task/Parse-an-IP-Address/J/parse-an-ip-address-2.j @@ -0,0 +1,12 @@ + fmt parseaddr '127.0.0.1' +ipv4 7f000001 + fmt parseaddr '127.0.0.1:80' +ipv4 7f000001 80 + fmt parseaddr '::1' +ipv6 1 + fmt parseaddr '[::1]:80' +ipv6 1 80 + fmt parseaddr '2605:2700:0:3::4713:93e3' +ipv6 260527000000000300000000471393e3 + fmt parseaddr '[2605:2700:0:3::4713:93e3]:80' +ipv6 260527000000000300000000471393e3 80 diff --git a/Task/Parse-an-IP-Address/Java/parse-an-ip-address-1.java b/Task/Parse-an-IP-Address/Java/parse-an-ip-address-1.java new file mode 100644 index 0000000000..08880eb15c --- /dev/null +++ b/Task/Parse-an-IP-Address/Java/parse-an-ip-address-1.java @@ -0,0 +1,190 @@ +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.regex.Pattern; + +import javax.xml.bind.DatatypeConverter; + +/** + * Parses ipv4 and ipv6 addresses. Emits each described IP address as a + * hexadecimal integer representing the address, the address space, and the port + * number specified, if any. + */ +public class IPParser { + /* + * Using regex to ensure that the address is a valid one. This allows for + * separating by format and ensures that the operations done on a format + * will be valid. + */ + // 0.0.0.0-255.255.255.255 + private final String ipv4segment = + "(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"; + + // 0-65535 + private final String portsegment = + ":(?:6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|" + + "6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])"; + private final String ipv4address = "(" + ipv4segment + "\\.){3,3}" + + ipv4segment; + private final String ipv4addressWithPort = ipv4address + portsegment + "?"; + private final String ipv6segment = "[a-fA-F0-9]{1,4}"; + private final String ipv6address = "(" + + // 1:2:3:4:5:6:7:8 + "(" + ipv6segment + ":){7,7}" + ipv6segment + "|" + + // 1::, 1:2:3:4:5:6:7:: + "(" + ipv6segment + ":){1,7}:|" + + // 1::8, 1:2:3:4:5:6::8, 1:2:3:4:5:6::8 + "(" + ipv6segment + ":){1,6}:" + ipv6segment + "|" + + // 1::7:8, 1:2:3:4:5::7:8, 1:2:3:4:5::8 + "(" + ipv6segment + ":){1,5}(:" + ipv6segment + "){1,2}|" + + // 1::6:7:8, 1:2:3:4::6:7:8, 1:2:3:4::8 + "(" + ipv6segment + ":){1,4}(:" + ipv6segment + "){1,3}|" + + // 1::5:6:7:8, 1:2:3::5:6:7:8, 1:2:3::8 + "(" + ipv6segment + ":){1,3}(:" + ipv6segment + "){1,4}|" + + // # 1::4:5:6:7:8, 1:2::4:5:6:7:8, 1:2::8 + "(" + ipv6segment + ":){1,2}(:" + ipv6segment + "){1,5}|" + + // # 1::3:4:5:6:7:8, 1::3:4:5:6:7:8, 1::8 + ipv6segment + ":((:" + ipv6segment + "){1,6})|" + + // ::2:3:4:5:6:7:8, ::2:3:4:5:6:7:8, ::8, :: + ":((:" + ipv6segment + "){1,7}|:)|" + + // fe80::7:8%eth0, fe80::7:8%1 (link-local IPv6 addresses with + // zone index) + "fe80:(:" + ipv6segment + "){0,4}%[0-9a-zA-Z]{1,}|" + + // ::255.255.255.255, ::ffff:255.255.255.255, + // ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and + // IPv4-translated addresses) + "::(ffff(:0{1,4}){0,1}:){0,1}" + ipv4address + "|" + + // 2001:db8:3:4::192.0.2.33, 64:ff9b::192.0.2.33 (IPv4-Embedded + // IPv6 Address) + "(" + ipv6segment + ":){1,4}:" + ipv4address + ")"; + + private final String ipv6addressWithPort = "\\[" + ipv6address + "\\]" + + portsegment + "?"; + + /** + * Parses ipv4 and ipv6 addresses. Emits each described IP address as a + * hexadecimal integer representing the address, the address space, and the + * port number specified, if any. + * + * @param address the address to analyze + */ + public void parse(String address) { + + // Used for storing values to be printed + String space = "";// ipv4, ipv6, or unknown + String hex = "";// hex value of the address + String port = "";// the port or unknown + + // Try to match the pattern with one of the 2 types, with or without a + // port + if (Pattern.matches("^" + ipv4address + "$", address)) { + InetAddress a; + space = "IPv4"; + try { + a = InetAddress.getByName(address); + hex = DatatypeConverter.printHexBinary(a.getAddress()); + } + catch (UnknownHostException e) { + e.printStackTrace(); + hex = "Invalid"; + } + port = "Absent"; + } + else if (Pattern.matches("^" + ipv4addressWithPort + "$", address)) { + String[] parts = address.split("\\."); + port = parts[3].split(":")[1]; + parts[3] = parts[3].split(":")[0]; + InetAddress a; + space = "IPv4"; + try { + address = parts[0] + parts[1] + parts[2] + parts[3]; + a = InetAddress.getByName(address); + hex = DatatypeConverter.printHexBinary(a.getAddress()); + } + catch (UnknownHostException e) { + e.printStackTrace(); + hex = "Invalid"; + } + } + else if (Pattern.matches("^" + ipv6address + "$", address)) { + InetAddress a; + space = "IPv6"; + try { + a = Inet6Address.getByName(address); + hex = DatatypeConverter.printHexBinary(a.getAddress()); + } + catch (UnknownHostException e) { + e.printStackTrace(); + hex = "Invalid"; + } + port = "Absent"; + } + else if (Pattern.matches("^" + ipv6addressWithPort + "$", address)) { + String[] parts = address.split(":"); + InetAddress a; + space = "IPv6"; + address = + address.replace("[", "").replace("]", "") + .replaceAll(portsegment + "$", ""); + try { + a = Inet6Address.getByName(address); + hex = DatatypeConverter.printHexBinary(a.getAddress()); + } + catch (UnknownHostException e) { + e.printStackTrace(); + hex = "Invalid"; + } + port = parts[parts.length - 1]; + } + else { + // Not a valid address + hex = "Invalid"; + space = "Invalid"; + port = "Invalid"; + } + + // Output the findings to the console + System.out.println("Test case: '" + address + "'"); + System.out.println("Space: " + space); + System.out.println("Address: " + hex); + System.out.println("Port: " + port); + System.out.println(); + + } + + /** + * Tests the parser using various addresses. + * + * @param args arguments for the program + */ + public static void main(String[] args) { + IPParser parser = new IPParser(); + + // The "localhost" IPv4 address + parser.parse("127.0.0.1"); + // The "localhost" IPv4 address, with a specified port (80) + parser.parse("127.0.0.1:80"); + // The "localhost" IPv6 address + parser.parse("::1"); + // The "localhost" IPv6 address, with a specified port (80) + parser.parse("[::1]:80"); + // Rosetta Code's primary server's public IPv6 address + parser.parse("2605:2700:0:3::4713:93e3"); + // Rosetta Code's primary server's public IPv6 address, with a specified + // port (80) + parser.parse("[2605:2700:0:3::4713:93e3]:80"); + + // ipv6 space + parser.parse("::ffff:192.168.173.22"); + // ipv6 space with port + parser.parse("[::ffff:192.168.173.22]:80"); + // trailing compression + parser.parse("1::"); + // trailing compression with port + parser.parse("[1::]:80"); + // 'any' address compression + parser.parse("::"); + // 'any' address compression with port + parser.parse("[::]:80"); + } +} diff --git a/Task/Parse-an-IP-Address/Java/parse-an-ip-address-2.java b/Task/Parse-an-IP-Address/Java/parse-an-ip-address-2.java new file mode 100644 index 0000000000..1055f0a49b --- /dev/null +++ b/Task/Parse-an-IP-Address/Java/parse-an-ip-address-2.java @@ -0,0 +1,59 @@ +Test case: '127.0.0.1' +Space: IPv4 +Address: 7F000001 +Port: Absent + +Test case: '127.0.0.1:80' +Space: IPv4 +Address: 0001F019 +Port: 80 + +Test case: '::1' +Space: IPv6 +Address: 00000000000000000000000000000001 +Port: Absent + +Test case: '[::1]:80' +Space: IPv6 +Address: 00000000000000000000000000000001 +Port: 80 + +Test case: '2605:2700:0:3::4713:93e3' +Space: IPv6 +Address: 260527000000000300000000471393E3 +Port: Absent + +Test case: '[2605:2700:0:3::4713:93e3]:80' +Space: IPv6 +Address: 260527000000000300000000471393E3 +Port: 80 + +Test case: '::ffff:192.168.173.22' +Space: IPv6 +Address: C0A8AD16 +Port: Absent + +Test case: '[::ffff:192.168.173.22]:80' +Space: IPv6 +Address: C0A8AD16 +Port: 80 + +Test case: '1::' +Space: IPv6 +Address: 00010000000000000000000000000000 +Port: Absent + +Test case: '[1::]:80' +Space: IPv6 +Address: 00010000000000000000000000000000 +Port: 80 + +Test case: '::' +Space: IPv6 +Address: 00000000000000000000000000000000 +Port: Absent + +Test case: '[::]:80' +Space: IPv6 +Address: 00000000000000000000000000000000 +Port: 80 diff --git a/Task/Parse-an-IP-Address/Perl-6/parse-an-ip-address.pl6 b/Task/Parse-an-IP-Address/Perl-6/parse-an-ip-address.pl6 new file mode 100644 index 0000000000..8d49db1f41 --- /dev/null +++ b/Task/Parse-an-IP-Address/Perl-6/parse-an-ip-address.pl6 @@ -0,0 +1,84 @@ +grammar IP_Addr { + token TOP { ^ [ | ] $ } + + token IPv4 { + [ +% '.' ] == 4 }> ? + { @*by8 = @$ } + } + + token IPv6 { + | + | '[' ']' + } + + token ipv6 { + | +% ':' == 8 }> + { @*by16 = @$ } + + | [ () +% ':']? '::' () +% ':' + { @*by16 = @$0, '0' xx 8 - (@$0 + @$1), @$1 } + + | '::ffff:' + { @*by16 = '0' xx 5, 'ffff', by8to16 @*by8 } + } + + token d8 { (\d+) } + token d16 { (\d+) } + token h16 { (<:hexdigit>+) } + + token port { + ':' { $*port = +$ } + } +} + +sub by8to16 (@m) { gather for @m -> $a,$b { take ($a * 256 + $b).fmt("%04x") } } + +my @cases = < + 127.0.0.1 + 127.0.0.1:80 + ::1 + [::1]:80 + 2605:2700:0:3::4713:93e3 + [2605:2700:0:3::4713:93e3]:80 + 2001:db8:85a3:0:0:8a2e:370:7334 + 2001:db8:85a3::8a2e:370:7334 + [2001:db8:85a3:8d3:1319:8a2e:370:7348]:443 + 192.168.0.1 + ::ffff:192.168.0.1 + ::ffff:71.19.147.227 + [::ffff:71.19.147.227]:80 + :: + 256.0.0.0 + g::1 + 0000 + 0000:0000 + 0000:0000:0000:0000:0000:0000:0000:0000 + 0000:0000:0000::0000:0000 + 0000::0000::0000:0000 + ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff + ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff + fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff + fff:ffff:0:ffff:ffff:ffff:ffff:ffff +>; + +for @cases -> $addr { + my @*by8; + my @*by16; + my $*port; + + IP_Addr.parse($addr); + + say $addr; + if @*by16 { + say " IPv6: ", @*by16».map({:16(~$_)})».fmt("%04x").join; + say " Port: ", $*port if $*port; + } + elsif @*by8 { + say " IPv4: ", @*by8».fmt("%02x").join; + say " Port: ", $*port if $*port; + } + else { + say " BOGUS!"; + } + say ''; +} diff --git a/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-1.pl b/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-1.pl new file mode 100644 index 0000000000..398c8ba735 --- /dev/null +++ b/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-1.pl @@ -0,0 +1,82 @@ +sub parse_v4 { + my ($ip, $port) = @_; + my @quad = split(/\./, $ip); + + return unless @quad == 4; + for (@quad) { return if ($_ > 255) } + + if (!length $port) { $port = -1 } + elsif ($port =~ /^(\d+)$/) { $port = $1 } + else { return } + + my $h = join '' => map(sprintf("%02x", $_), @quad); + return $h, $port +} + +sub parse_v6 { + my $ip = shift; + my $omits; + + return unless $ip =~ /^[\da-f:.]+$/i; # invalid char + + $ip =~ s/^:/0:/; + $omits = 1 if $ip =~ s/::/:z:/g; + return if $ip =~ /z.*z/; # multiple omits illegal + + my $v4 = ''; + my $len = 8; + + if ($ip =~ s/:((?:\d+\.){3}\d+)$//) { + # hybrid 4/6 ip + ($v4) = parse_v4($1) or return; + $len -= 2; + + } + # what's left should be v6 only + return unless $ip =~ /^[:a-fz\d]+$/i; + + my @h = split(/:/, $ip); + return if @h + $omits > $len; # too many segments + + @h = map( $_ eq 'z' ? (0) x ($len - @h + 1) : ($_), @h); + return join('' => map(sprintf("%04x", hex($_)), @h)).$v4; +} + +sub parse_ip { + my $str = shift; + $str =~ s/^\s*//; + $str =~ s/\s*$//; + + if ($str =~ s/^((?:\d+\.)+\d+)(?::(\d+))?$//) { + return 'v4', parse_v4($1, $2); + } + + my ($ip, $port); + if ($str =~ /^\[(.*?)\]:(\d+)$/) { + $port = $2; + $ip = parse_v6($1); + } else { + $port = -1; + $ip = parse_v6($str); + } + + return unless $ip; + return 'v6', $ip, $port; +} + +for (qw/127.0.0.1 127.0.0.1:80 + ::1 + [::1]:80 + 2605:2700:0:3::4713:93e3 + [2605:2700:0:3::4713:93e3]:80 + ::ffff:192.168.0.1 + [::ffff:192.168.0.1]:22 + ::ffff:127.0.0.0.1 + a::b::1/) +{ + print "$_\n\t"; + my ($ver, $ip, $port) = parse_ip($_) + or print "parse error\n" and next; + + print "$ver $ip\tport $port\n\n"; +} diff --git a/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-2.pl b/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-2.pl new file mode 100644 index 0000000000..7dffd819e5 --- /dev/null +++ b/Task/Parse-an-IP-Address/Perl/parse-an-ip-address-2.pl @@ -0,0 +1,28 @@ +127.0.0.1 + v4 7f000001 port -1 + +127.0.0.1:80 + v4 7f000001 port 80 + +::1 + v6 00000000000000000000000000000001 port -1 + +[::1]:80 + v6 00000000000000000000000000000001 port 80 + +2605:2700:0:3::4713:93e3 + v6 260527000000000300000000471393e3 port -1 + +[2605:2700:0:3::4713:93e3]:80 + v6 260527000000000300000000471393e3 port 80 + +::ffff:192.168.0.1 + v6 00000000000000000000ffffc0a80001 port -1 + +[::ffff:192.168.0.1]:22 + v6 00000000000000000000ffffc0a80001 port 22 + +::ffff:127.0.0.0.1 + parse error +a::b::1 + parse error diff --git a/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-1.l b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-1.l new file mode 100644 index 0000000000..d6c90807ea --- /dev/null +++ b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-1.l @@ -0,0 +1,32 @@ +# Return a cons pair of address and port: (address . port) +(de ipAddress (Adr) + (use (@A @B @C @D @Port) + (cond + ((match '("[" @A "]" ":" @Port) Adr) + (adrIPv6 (split @A ":") @Port) ) + ((match '("[" @A "]") Adr) + (adrIPv6 (split @A ":")) ) + ((match '(@A ":" @B ":" @C) Adr) + (adrIPv6 (cons @A @B (split @C ":"))) ) + ((match '(@A "." @B "." @C "." @D ":" @Port) Adr) + (adrIPv4 (list @A @B @C @D) @Port) ) + ((match '(@A "." @B "." @C "." @D) Adr) + (adrIPv4 (list @A @B @C @D)) ) + (T (quit "Bad IP address" (pack Adr))) ) ) ) + +(de adrIPv4 (Lst Port) + (cons + (sum >> (-24 -16 -8 0) (mapcar format Lst)) + (format Port) ) ) + +(de adrIPv6 (Lst Port) + (cons + (sum >> + (-112 -96 -80 -64 -48 -32 -16 0) + (mapcan + '((X) + (if X + (cons (hex X)) + (need (- 9 (length Lst)) 0) ) ) # Handle '::' + (cons (or (car Lst) "0") (cdr Lst)) ) ) + (format Port) ) ) diff --git a/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-2.l b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-2.l new file mode 100644 index 0000000000..dfa529a917 --- /dev/null +++ b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-2.l @@ -0,0 +1,14 @@ +(for A + (quote + "127.0.0.1" + "127.0.0.1:80" + "::1" + "[::1]:80" + "2605:2700:0:3::4713:93e3" + "[2605:2700:0:3::4713:93e3]:80" ) + (let I (ipAddress (chop A)) + (tab (-29 34 40 7) + A + (hex (car I)) + (format (car I)) + (cdr I) ) ) ) diff --git a/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-3.l b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-3.l new file mode 100644 index 0000000000..66d064f0aa --- /dev/null +++ b/Task/Parse-an-IP-Address/PicoLisp/parse-an-ip-address-3.l @@ -0,0 +1,277 @@ +*process or(!) source xref attributes macro options; + /********************************************************************* + * Program to parse an IP address into --> IPv4 or IPv6 format + * 28.05.2013 Walter Pachl translated from REXX version 3 + * x2d was the hard part :-) + *********************************************************************/ + ip: proc options(main); + Dcl ipa char(50) Var; + Dcl ipi char(50) Var; + Dcl ipax char(50) Var Init(''); + Dcl ipad char(50) Var Init(''); + Dcl space char(4); + Dcl port char(5) Var; + dcl head Char(132) Var; + head=' input IP address hex IP address '!! + ' decimal IP address space port'; + Put Edit(head)(Skip,a); + Put Edit(copies('_',30), + copies('_',32), + copies('_',39), + copies('_', 5), + copies('_', 5)) + (Skip,6(a,x(1))); + + call expand('127.0.0.1'); + call expand('127.0.0.1:80'); + call expand('2605:2700:0:3::4713:93e3'); + call expand('[2605:2700:0:3::4713:93e3]:80'); + call expand('::1'); + call expand('[::1]:80'); + + expand: procedure(s); + Dcl s Char(50) Var; + ipi=s; + ipa=s; + If index(ipa,'.')>0 Then + Call expand_ipv4; + Else + Call expand_ipv6; + ipad=x2d(ipax); + Put Edit(left(ipi,30),right(ipax,32),right(ipad,39), + right(space,5),right(port,5)) + (Skip,6(a,x(1))); + End; + + expand_ipv4: Proc; + Dcl a(4) Char(3) Var; + Dcl (pp,j) Bin Fixed(31); + space='IPv4'; + pp=index(ipa,':'); + If pp>0 Then Do; + port=substr(ipa,pp+1); + ipa=left(ipa,pp-1); + End; + Else + Port=''; + Call parse((ipa),'.',a); + ipax=''; + do j=1 To 4; + ipax=ipax!!a(j); + end; + End; + + expand_ipv6: Proc; + Dcl a(8) Char(4) Var; + Dcl (s,o1,o2) Char(50) Var Init(''); + Dcl (i,ii,pp,j,n) Bin Fixed(31) Init(0); + space='IPv6'; + pp=index(ipa,']:'); + If pp>0 Then Do; + port=substr(ipa,pp+2); + ipa=substr(ipa,2,pp-2); + End; + Else + Port=''; + s=ipa; + j=0; + Do i=1 To 8 While(s>''); + pp=index(s,':'); + dcl temp Char(6) Var; + If pp>1 Then + temp=left(s,pp-1); + Else + temp=s; + temp=right(temp,4,'0'); + Select(pp); + When(0) Do; + a(i)=temp; + s=''; + End; + When(1) Do; + a(i)='----'; + ii=i; + s=substr(s,pp+1); + If left(s,1)=':' Then + s=substr(s,2); + End; + Otherwise Do; + a(i)=temp; + s=substr(s,pp+1); + End; + End; + End; + n=i-1; + o1=''; + o2=''; + Do i=1 To n; + If i=ii Then Do; + o1=o1!!'----'; + Do j=1 To 9-n; + o2=o2!!'0000'; + End; + End; + Else Do; + o1=o1!!right(a(i),4,'0'); + o2=o2!!right(a(i),4,'0'); + End; + End; + ipax=o2; + End; + + parse: Proc(s,c,a); + Dcl s Char(50) Var; + Dcl c Char( 1); + Dcl a(*) Char(*) Var; + Dcl (i,p) Bin Fixed(31); + a=''; + Do i=1 By 1 While(length(s)>0); + p=index(s,c); + If p>0 Then Do; + a(i)=left(s,p-1); + s=substr(s,p+1); + End; + Else Do; + a(i)=s; + s=''; + End; + End; + End; + + /* + underscore: Proc(s) Returns(char(132) Var); + Dcl s Char(*); + Dcl r Char(length(s)) Var Init(''); + Dcl i Bin Fixed(31); + Dcl us Bit(1) Init('0'b); + Do i=1 To length(s)-1; + If substr(s,i,1)>' ' Then Do; + r=r!!'_'; + us='1'b; + End; + Else Do; + If substr(s,i+1,1)>' ' & us Then + r=r!!'_'; + Else Do; + r=r!!' '; + us='0'b; + End; + End; + End; + If substr(s,length(s),1)>' ' Then + r=r!!'_'; + Return(r); + End; + + center: Proc(s,l) Returns(char(50) Var); + Dcl s char(50) Var; + Dcl (l,b) Bin Fixed(31); + b=(l-length(s))/2; + Return(left(copies(' ',b)!!s,l)); + End; + */ + copies: Proc(c,n) Returns(char(50) Var); + Dcl c char(50) Var; + Dcl n Bin Fixed(31); + Return(repeat(c,n-1)); + End; + + + c2d: Procedure(s) Returns(Char(50) Var); + Dcl s Char(*) Var; + Dcl d Pic'99'; + Dcl (v,part,result,old) Char(100) Var; + Dcl i Bin Fixed(31); + result='0'; + v='1'; + + Do i=length(s) To 1 By -1; + d=c2d(substr(s,i,1)); + part=longmult((v),(d)); + result=longadd((result),(part)); + v=longmult((v),'16'); + End; + Do While(left(result,1)='0'); + result=substr(result,2); + End; + Return(result); + /* + dbg: Proc(txt); + Dcl txt Char(*); + Put Skip list(txt); + End; + */ + x2d: Procedure(c) Returns(Char(2)); + Dcl c Char(1); + Dcl res Char(2); + Select(c); + When('a','A') res='10'; + When('b','B') res='11'; + When('c','C') res='12'; + When('d','D') res='13'; + When('e','E') res='14'; + When('f','F') res='15'; + Otherwise res='0'!!c; + End; + Return(res); + End; + + longmult: Procedure(as,bs) Returns(Char(1000) Var); + /* REXX ************************************************************** + * Multiply(as,bs) -> as*bs + *********************************************************************/ + Dcl (as,bs) Char(*); + Dcl (a(1000),b(1000),r(1000)) Pic'9'; + Dcl (p,s) Pic'99'; + Dcl (al,bl) Bin Fixed(31); + Dcl (i,ai,bi,ri,rim) Bin Fixed(31); + Dcl res Char(1000) Var Init((1000)'0'); + al=length(as); Do ai=al To 1 By -1; a(ai)=substr(as,al-ai+1,1); End; + bl=length(bs); Do bi=bl To 1 By -1; b(bi)=substr(bs,bl-bi+1,1); End; + r=0; + rim=0; + Do bi=1 To bl; + Do ai=1 To al; + ri=ai+bi-1; + p=a(ai)*b(bi); + Do i=ri by 1 Until(p=0); + s=r(i)+p; + r(i)=mod(s,10); + p=s/10; + End; + rim=max(rim,i); + End; + End; + res=''; + Do i=1 To rim; + res=r(i)!!res; + End; + Return(res); + End; + + longadd: proc(as,bs) Returns(Char(100) Var); + Dcl (as,bs) Char(*) Var; + Dcl cs Char(100) Var Init(''); + Dcl (al,bl,cl,i) Bin Fixed(31); + Dcl a(100) Pic'9' Init((100)0); + Dcl b(100) Pic'9' Init((100)0); + Dcl c(100) Pic'9' Init((100)0); + Dcl temp Pic'99'; + al=length(as); + bl=length(bs); + Do i=1 To al; a(i)=substr(as,al-i+1,1); End; + Do i=1 To bl; b(i)=substr(bs,bl-i+1,1); End; + cl=max(al,bl)+1; + Do i=1 To cl; + temp=a(i)+b(i)+c(i); + c(i)=mod(temp,10); + c(i+1)=c(i+1)+temp/10; + End; + Do i=1 To cl; + cs=c(i)!!cs; + End; + Return(cs); + End; + End; + + end; diff --git a/Task/Parse-an-IP-Address/Python/parse-an-ip-address.py b/Task/Parse-an-IP-Address/Python/parse-an-ip-address.py new file mode 100644 index 0000000000..4204f556f4 --- /dev/null +++ b/Task/Parse-an-IP-Address/Python/parse-an-ip-address.py @@ -0,0 +1,124 @@ +import string +from pyparsing import * # import antigravity + +tests="""# +127.0.0.1 # The "localhost" IPv4 address +127.0.0.1:80 # The "localhost" IPv4 address, with a specified port (80) +::1 # The "localhost" IPv6 address +[::1]:80 # The "localhost" IPv6 address, with a specified port (80) +2605:2700:0:3::4713:93e3 # Rosetta Code's primary server's public IPv6 address +[2605:2700:0:3::4713:93e3]:80 # Rosetta Code's primary server's public IPv6 address, +port (80) +2001:db8:85a3:0:0:8a2e:370:7334 # doc, IPv6 for 555-1234 +2001:db8:85a3::8a2e:370:7334 # doc +[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443 # doc +port +192.168.0.1 # private +::ffff:192.168.0.1 # private transitional +::ffff:71.19.147.227 # Rosetta Code's transitional +[::ffff:71.19.147.227]:80 # Rosetta Code's transitional +port +:: # unspecified +256.0.0.0 # invalid, octet > 255 (currently not detected) +g::1 # invalid +0000 Bad address +0000:0000 Bad address +0000:0000:0000:0000:0000:0000:0000:0000 Good address +0000:0000:0000::0000:0000 Good Address +0000::0000::0000:0000 Bad address +ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff Good address +ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff Bad address +fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff Good address +fff:ffff:0:ffff:ffff:ffff:ffff:ffff Good address +""" + +def print_args(args): + print "print_args:", args + +def join(args): + args[0]="".join(args) + del args[1:] + +def replace(val): + def lambda_replace(args): + args[0]=val + del args[1:] + return lambda_replace + +def atoi(args): args[0]=string.atoi(args[0]) +def itohex2(args): args[0]="%02x"%args[0] + +def hextoi(args): args[0]=string.atoi(args[0], 16) +def itohex4(args): args[0]="%04x"%args[0] + +def assert_in_range(lwb, upb): + def range_check(args): + return # turn range checking off + if args[0] < lwb: + raise ValueError,"value %d < %d"%(args[0], lwb) + if args[0] > upb: + raise ValueError,"value %d > %d"%(args[0], upb) + return range_check + +dot = Literal(".").suppress()("dot"); colon = Literal(":").suppress()("colon") +octet = Word(nums).setParseAction(atoi,assert_in_range(0,255),itohex2)("octet"); + +port = Word(nums).setParseAction(atoi,assert_in_range(0,256*256-1))("port") +ipv4 = (octet + (dot+octet)*3)("addr") +ipv4.setParseAction(join) #,hextoi) + +ipv4_port = ipv4+colon.suppress()+port + +a2f = "abcdef" +hex = oneOf(" ".join(nums+a2f)); + +hexet = (hex*(0,4))("hexet") +hexet.setParseAction(join, hextoi, itohex4) + +max=8; stop=max+1 + +xXXXX_etc = [None, hexet]; xXXXX_etc.extend([hexet + (colon+hexet)*n for n in range(1,max)]) +x0000_etc = [ Literal("::").setParseAction(replace("0000"*num_x0000s)) for num_x0000s in range(stop) ] + +ipv6=xXXXX_etc[-1]+x0000_etc[0] | xXXXX_etc[-1] + +# Build a table of rules for IPv6, in particular the double colon +for num_prefix in range(max-1, -1, -1): + for num_x0000s in range(0,stop-num_prefix): + x0000 = x0000_etc[num_x0000s] + num_suffix=max-num_prefix-num_x0000s + if num_prefix: + if num_suffix: pat = xXXXX_etc[num_prefix]+x0000+xXXXX_etc[num_suffix] + else: pat = xXXXX_etc[num_prefix]+x0000 + elif num_suffix: pat = x0000+xXXXX_etc[num_suffix] + else: pat=x0000 + ipv6 = ipv6 | pat + +ipv6.setParseAction(join) # ,hextoi) +ipv6_port = Literal("[").suppress() + ipv6 + Literal("]").suppress()+colon+port + +ipv6_transitional = (Literal("::ffff:").setParseAction(replace("0"*20+"ffff"))+ipv4).setParseAction(join) +ipv6_transitional_port = Literal("[").suppress() + ipv6_transitional + Literal("]").suppress()+colon+port + +ip_fmt = ( + (ipv4_port|ipv4)("ipv4") | + (ipv6_transitional_port|ipv6_transitional|ipv6_port|ipv6)("ipv6") + ) + LineEnd() + +class IPAddr(object): + def __init__(self, string): + self.service = dict(zip(("address","port"), ip_fmt.parseString(string)[:])) + def __getitem__(self, key): return self.service[key] + def __contains__(self, key): return key in self.service + def __repr__(self): return `self.service` # "".join(self.service) + address=property(lambda self: self.service["address"]) + port=property(lambda self: self.service["port"]) + is_service=property(lambda self: "port" in self.service) + version=property(lambda self: {False:4, True:6}[len(self.address)>8]) + +for test in tests.splitlines(): + if not test.startswith("#"): + ip_str, desc = test.split(None,1) + print ip_str,"=>", + try: + ip=IPAddr(ip_str) + print ip, "IP Version:",ip.version,"- Address is OK!", + except (ParseException,ValueError), details: print "Bad! IP address syntax error detected:",details, + print "- Actually:",desc diff --git a/Task/Parse-an-IP-Address/README b/Task/Parse-an-IP-Address/README new file mode 100644 index 0000000000..e72521df20 --- /dev/null +++ b/Task/Parse-an-IP-Address/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Parse_an_IP_Address diff --git a/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx new file mode 100644 index 0000000000..2220692326 --- /dev/null +++ b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx @@ -0,0 +1,39 @@ +/*REXX program to parse an IP address into ──► IPv4 or IPv6 format, port*/ + say center('input IP address' ,30), + center('hex IP address' ,32), + center('decimal IP address' ,39) 'space port' + _='─' + say copies(_,30) copies(_,32) copies(_,39) copies(_,5) copies(_,5) +call IP_parse 127.0.0.1 /*this IP doesn't need quotes. */ +call IP_parse '127.0.0.1:80' +call IP_parse '::1' +call IP_parse '[::1]:80' +call IP_parse '2605:2700:0:3::4713:93e3' +call IP_parse '[2605:2700:0:3::4713:93e3]:80' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────IP_parse subroutine─────────────────*/ +IP_parse: procedure; parse arg a .; hx=; @.=; numeric digits 50 +dot=pos('.',a)\==0 /*see if there is a dot present. */ + +if dot then do; parse var a @.1 '.' @.2 "." @.3 '.' @.4 ":" port + do j=1 for 4; hx=hx || d2x(@.j,2) + end /*j*/ + end /*if dot*/ + else do; parse var a pureA ']:' port + _=space(translate(pureA,,'[]'),0) /*remove brackets*/ + parse var _ x '::' y + do L=1 until x=='' /*get left side.*/ + parse var x @.L ':' x + end /*L*/ + y=reverse(y) + do r=8 by -1 /*get right side.*/ + parse var y z ':' y; if z=='' then leave + @.r=reverse(z) + end /*r*/ + + do k=1 for 8; hx=hx || right(word(@.k 0, 1), 4, 0) + end /*k*/ + end /*else dot*/ + +say left(a,30) right(hx,32) right(x2d(hx),39) ' IPv'||(6-2*dot) right(port,5) +return diff --git a/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-2.rexx b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-2.rexx new file mode 100644 index 0000000000..770ca42f91 --- /dev/null +++ b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-2.rexx @@ -0,0 +1,83 @@ +/* REXX *************************************************************** +* 27.05.2013 Walter Pachl +**********************************************************************/ +Numeric Digits 100 +say center('input IP address' ,30), + center('hex IP address' ,32), + center('decimal IP address' ,39) 'space port' + +say copies(_,30) copies(_,32) copies(_,39) copies(_,5) copies(_,5) /*hdr*/ +call expand '127.0.0.1' +call expand '127.0.0.1:80' +call expand '::1' +call expand '[::1]:80' +call expand '2605:2700:0:3::4713:93e3' +call expand '[2605:2700:0:3::4713:93e3]:80' +Say ' ' +Say 'The following 2 are the same' +Call expand '2001:0db8:0:0:0:0:1428:57ab' +Call expand '2001:db8::1428:57ab' +Say ' ' +Say 'The following 3 are all the same' +Call expand '2001:0db8:0:0:8d3:0:0:0' +Call expand '2001:db8:0:0:8d3::' +Call expand '2001:db8::8d3:0:0:0' +Exit + +expand: Procedure +Parse Arg s +If pos('.',s)>0 Then + Parse Value expand_ip4(s) With exp space port +Else + Parse Value expand_ip6(s) With exp space port +Say left(s,30) right(exp,32) right(x2d(exp),39) right(space,5) right(port,5) +Return + +expand_ip4: Procedure +Parse Arg s +If pos(':',s)>0 Then + Parse Var s s ':' port +Else + port='' +Do i=1 To 4 + Parse Var s a.i '.' s + End +res='' +Do i=1 To 4 + res=res||d2x(a.i,2) + End +Return res 'IPv4' port + +expand_ip6: Procedure +/********************************************************************** +* Note: Doublecolon ('::') requires the inclusion of as many 0000 +* tokens as necessary to result in 8 tokens +**********************************************************************/ +Parse Arg s +If pos(']:',s)>0 Then + Parse Var s '[' s ']:' port +Else + port='' +sc=s +ii=0 +Do i=1 To 8 While s<>'' + Parse Var s x.i ':' s + If left(s,1)=':' Then Do + ii=i + s=substr(s,2) + End + End +n=i-1 +ol='' +o2='' +Do i=1 To n + ol=ol||right(x.i,4,'0') + o2=o2||right(x.i,4,'0') + If i=ii Then Do + ol=ol||'----' + Do j=1 To 8-n + o2=o2||'0000' + End + End + End +Return o2 'IPv6' port diff --git a/Task/Parse-an-IP-Address/Racket/parse-an-ip-address.rkt b/Task/Parse-an-IP-Address/Racket/parse-an-ip-address.rkt new file mode 100644 index 0000000000..ba29a6b2b1 --- /dev/null +++ b/Task/Parse-an-IP-Address/Racket/parse-an-ip-address.rkt @@ -0,0 +1,29 @@ +#lang racket + +(require net/private/ip) + +(define (bytes->hex bs) + (string-append* (map (λ(n) (~r n #:base 16 #:min-width 2 #:pad-string "0")) + (bytes->list bs)))) + +(define (parse-ip str) + (define-values [ipstr portstr] + (match str + [(regexp #rx"^([0-9.]+):([0-9]+)$" (list _ i p)) (values i p)] + [(regexp #rx"^\\[([0-9a-fA-F:]+)\\]:([0-9]+)$" (list _ i p)) (values i p)] + [_ (values str "")])) + (define ip (make-ip-address ipstr)) + (define 4? (ipv4? ip)) + (define hex (bytes->hex ((if 4? ipv4-bytes ipv6-bytes) ip))) + (displayln (~a (~a str #:min-width 30) + " " + (~a hex #:min-width 32 #:align 'right) + " ipv" (if 4? "4" "6") " " portstr))) + +(for-each parse-ip + '("127.0.0.1" + "127.0.0.1:80" + "::1" + "[::1]:80" + "2605:2700:0:3::4713:93e3" + "[2605:2700:0:3::4713:93e3]:80")) diff --git a/Task/Parse-an-IP-Address/Ruby/parse-an-ip-address.rb b/Task/Parse-an-IP-Address/Ruby/parse-an-ip-address.rb new file mode 100644 index 0000000000..b9858c841f --- /dev/null +++ b/Task/Parse-an-IP-Address/Ruby/parse-an-ip-address.rb @@ -0,0 +1,64 @@ +require 'socket' +require 'ipaddr' + +IP_ADDRESSES = ["127.0.0.1", "127.0.0.1:80", + "::1", "[::1]:80", + "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", + "fe80::1%lo0", "1600 Pennsylvania Avenue NW"] +output = [] +output << %w(String Address Port Family Hex Scope?) +output << %w(------ ------- ---- ------ --- ------) + +# Parse _string_ for an IP address and optional port number. Returns +# them in an Addrinfo object. +def parse_addr(string) + # Split host and port number from string. + case string + when /\A\[(?
.* )\]:(? \d+ )\z/x # string like "[::1]:80" + address, port = $~[:address], $~[:port] + when /\A(?
[^:]+ ):(? \d+ )\z/x # string like "127.0.0.1:80" + address, port = $~[:address], $~[:port] + else # string with no port number + address, port = string, nil + end + + # Pass address, port to Addrinfo.getaddrinfo. It will raise SocketError if address or port is not valid. + # IPAddr currently cannot handle ::1 notation, use Addrinfo instead + ary = Addrinfo.getaddrinfo(address, port) + + # An IP address is exactly one address. + ary.size == 1 or raise SocketError, "expected 1 address, found #{ary.size}" + ary.first +end + +def output_table(rows) + widths = [] + rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }} + format = widths.map {|size| "%#{size}s"}.join("\t") + rows.each {|row| puts format % row} +end + +family_hash = {Socket::AF_INET => "ipv4", Socket::AF_INET6 => "ipv6"} + +IP_ADDRESSES.each do |string| + begin + addr = parse_addr(string) + rescue SocketError + output << [string, "illegal address", '','','',''] + else + (cur_string ||= []) << string << addr.ip_address << addr.ip_port.to_s << family_hash[addr.afamily] # for output + + # Show address in hexadecimal. We must unpack it from sockaddr string. + if addr.ipv4? + # network byte order "N" + cur_string << "0x%08x" % IPAddr.new(addr.ip_address).hton.unpack('N') << "" + elsif addr.ipv6? + # 32 bytes for address, network byte order "N4" + cur_string << "0x%032x" % IPAddr.new(addr.ip_address).to_i + cur_string << (addr.ipv6_linklocal? ? ary[4] : "") # for Scope + end + output << cur_string + end +end + +output_table output diff --git a/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-1.tcl b/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-1.tcl new file mode 100644 index 0000000000..de6fb43bf8 --- /dev/null +++ b/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-1.tcl @@ -0,0 +1,39 @@ +package require Tcl 8.5 +package require ip + +proc parseIP {address} { + set result {} + set family [ip::version $address] + set port -1 + if {$family == -1} { + if {[regexp {^\[(.*)\]:(\d+)$} $address -> address port]} { + dict set result port $port + set family [ip::version $address] + if {$family != 6} { + return -code error "bad address" + } + } elseif {[regexp {^(.*):(\d+)$} $address -> address port]} { + dict set result port $port + set family [ip::version $address] + if {$family != 4} { + return -code error "bad address" + } + } else { + return -code error "bad address" + } + } + # Only possible error in ports is to be too large an integer + if {$port > 65535} { + return -code error "bad port" + } + dict set result family $family + if {$family == 4} { + # IPv4 normalized form is dotted quad, but toInteger helps + dict set result addr [format %x [ip::toInteger $address]] + } else { + # IPv6 normalized form is colin-separated hex + dict set result addr [string map {: ""} [ip::normalize $address]] + } + # Return the descriptor dictionary + return $result +} diff --git a/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-2.tcl b/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-2.tcl new file mode 100644 index 0000000000..15d1687ff2 --- /dev/null +++ b/Task/Parse-an-IP-Address/Tcl/parse-an-ip-address-2.tcl @@ -0,0 +1,27 @@ +foreach address { + 127.0.0.1 + 127.0.0.1:80 + ::1 + [::1]:80 + 2605:2700:0:3::4713:93e3 + [2605:2700:0:3::4713:93e3]:80 + ::ffff:192.168.0.1 + [::ffff:192.168.0.1]:22 + ::ffff:127.0.0.0.1 + a::b::1 + 127.0.0.1:100000 +} { + if {[catch { + set parsed [parseIP $address] + } msg]} { + puts "error ${msg}: \"$address\"" + continue + } + dict with parsed { + puts -nonewline "family: IPv$family addr: $addr" + if {[dict exists $parsed port]} { + puts -nonewline " port: $port" + } + puts "" + } +} diff --git a/Task/Penneys-game/00DESCRIPTION b/Task/Penneys-game/00DESCRIPTION new file mode 100644 index 0000000000..867435e43d --- /dev/null +++ b/Task/Penneys-game/00DESCRIPTION @@ -0,0 +1,18 @@ +[[wp:Penney's_game|Penneys game]] is a game where two players bet on being the first to see a particular sequence of Heads and Tails in consecutive tosses of a fair coin. + +It is common to agree on a sequence length of three then one player will openly choose a sequence, for example Heads, Tails, Heads, or HTH for short; then the other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. + +For example: One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. + +;The Task: +Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. +* Who chooses and shows their sequence of three should be chosen randomly. +* If going first, the computer should choose its sequence of three randomly. +* If going second, the computer should automatically play [[wp:Penney's_game#Analysis_of_the_three-bit_game|the optimum sequence]]. +* Successive coin tosses should be shown. + +Show output of a game where the computer choses first and a game where the user goes first here on this page. + +;Refs: +* [https://www.youtube.com/watch?v=OcYnlSenF04 The Penney Ante Part 1] (Video). +* [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video). diff --git a/Task/Penneys-game/C++/penneys-game.cpp b/Task/Penneys-game/C++/penneys-game.cpp new file mode 100644 index 0000000000..f7d0b2e864 --- /dev/null +++ b/Task/Penneys-game/C++/penneys-game.cpp @@ -0,0 +1,86 @@ +#include +#include +#include + +using namespace std; + +class penney +{ +public: + penney() + { pW = cW = 0; } + void gameLoop() + { + string a; + while( true ) + { + playerChoice = computerChoice = ""; + if( rand() % 2 ) + { computer(); player(); } + else + { player(); computer(); } + + play(); + + cout << "[Y] to play again "; cin >> a; + if( a[0] != 'Y' && a[0] != 'y' ) + { + cout << "Computer won " << cW << " times." << endl << "Player won " << pW << " times."; + break; + } + cout << endl << endl; + } + } +private: + void computer() + { + if( playerChoice.length() == 0 ) + { + for( int x = 0; x < 3; x++ ) + computerChoice.append( ( rand() % 2 ) ? "H" : "T", 1 ); + } + else + { + computerChoice.append( playerChoice[1] == 'T' ? "H" : "T", 1 ); + computerChoice += playerChoice.substr( 0, 2 ); + } + cout << "Computer's sequence of three is: " << computerChoice << endl; + } + void player() + { + cout << "Enter your sequence of three (H/T) "; cin >> playerChoice; + } + void play() + { + sequence = ""; + while( true ) + { + sequence.append( ( rand() % 2 ) ? "H" : "T", 1 ); + if( sequence.find( playerChoice ) != sequence.npos ) + { + showWinner( 1 ); + break; + } + else if( sequence.find( computerChoice ) != sequence.npos ) + { + showWinner( 0 ); + break; + } + } + } + void showWinner( int i ) + { + string s; + if( i ) { s = "Player wins!"; pW++; } + else { s = "Computer wins!"; cW++; } + cout << "Tossed sequence: " << sequence << endl << s << endl << endl; + } + string playerChoice, computerChoice, sequence; + int pW, cW; +}; +int main( int argc, char* argv[] ) +{ + srand( static_cast( time( NULL ) ) ); + penney game; game.gameLoop(); + return 0; +} diff --git a/Task/Penneys-game/C/penneys-game.c b/Task/Penneys-game/C/penneys-game.c new file mode 100644 index 0000000000..42df332d99 --- /dev/null +++ b/Task/Penneys-game/C/penneys-game.c @@ -0,0 +1,121 @@ +#include +#include +#include + +#define SEQLEN 3 + +int getseq(char *s) +{ + int r = 0; + int i = 1 << (SEQLEN - 1); + + while (*s && i) { + switch (*s++) { + case 'H': + case 'h': + r |= i; + break; + case 'T': + case 't': + /* 0 indicates tails, this is 0, so do nothing */ + break; + default: + return -1; + } + i >>= 1; + } + + return r; +} + +void printseq(int seq) +{ + int i; + for (i = SEQLEN - 1; i >= 0; --i) + printf("%c", seq & (1 << i) ? 'h' : 't'); +} + +int getuser(void) +{ + int user; + char s[SEQLEN + 1]; + + printf("Enter your sequence of %d (h/t): ", SEQLEN); + while (1) { + /* This needs to be manually changed if SEQLEN is changed */ + if (scanf("%3s", s) != 1) exit(1); + if ((user = getseq(s)) != -1) return user; + printf("Please enter only h/t characters: "); + } +} + +int getai(int user) +{ + int ai; + + printf("Computers sequence of %d is: ", SEQLEN); + /* The ai's perfect choice will only be perfect for SEQLEN == 3 */ + if (user == -1) + ai = rand() & (1 << SEQLEN) - 1; + else + ai = (user >> 1) | ((~user << 1) & (1 << SEQLEN - 1)); + + printseq(ai); + printf("\n"); + return ai; +} + +int rungame(int user, int ai) +{ + /* Generate first SEQLEN flips. We only need to store the last SEQLEN + * tosses at any one time. */ + int last3 = rand() & (1 << SEQLEN) - 1; + + printf("Tossed sequence: "); + printseq(last3); + while (1) { + if (user == last3) { + printf("\nUser wins!\n"); + return 1; + } + + if (ai == last3) { + printf("\nAi wins!\n"); + return 0; + } + + last3 = ((last3 << 1) & (1 << SEQLEN) - 2) | (rand() & 1); + printf("%c", last3 & 1 ? 'h' : 't'); + } +} + +int main(void) +{ + srand(time(NULL)); + int playerwins = 0; + int totalgames = 0; + + /* Just use ctrl-c for exit */ + while (1) { + int user = -1; + int ai = -1; + + printf("\n"); + if (rand() & 1) { + ai = getai(user); + user = getuser(); + } + else { + user = getuser(); + ai = getai(user); + } + + playerwins += rungame(user, ai); + totalgames++; + + printf("You have won %d out of %d games\n", playerwins, totalgames); + printf("=================================\n"); + } + + return 0; +} diff --git a/Task/Penneys-game/D/penneys-game.d b/Task/Penneys-game/D/penneys-game.d new file mode 100644 index 0000000000..a921d81003 --- /dev/null +++ b/Task/Penneys-game/D/penneys-game.d @@ -0,0 +1,35 @@ +void main() { + import std.stdio, std.random, std.algorithm, std.string, + std.conv, std.range, core.thread; + + immutable first = uniform(0, 2) == 0; + + string you, me; + if (first) { + me = 3.iota.map!(_ => "HT"[uniform(0, $)]).text; + writefln("I choose first and will win on first seeing %s in the list of tosses", me); + while (you.length != 3 || you.any!(c => !c.among('H', 'T')) || you == me) { + "What sequence of three Heads/Tails will you win with: ".write; + you = readln.strip; + } + } else { + while (you.length != 3 || you.any!(c => !c.among('H', 'T'))) { + "After you: What sequence of three Heads/Tails will you win with: ".write; + you = readln.strip; + } + me = (you[1] == 'T' ? 'H' : 'T') ~ you[0 .. 2]; + writefln("I win on first seeing %s in the list of tosses", me); + } + + "Rolling:\n ".write; + string rolled; + while (true) { + rolled ~= "HT"[uniform(0, $)]; + rolled.back.write; + if (rolled.endsWith(you)) + return "\n You win!".writeln; + if (rolled.endsWith(me)) + return "\n I win!".writeln; + Thread.sleep(1.seconds); + } +} diff --git a/Task/Penneys-game/Haskell/penneys-game.hs b/Task/Penneys-game/Haskell/penneys-game.hs new file mode 100644 index 0000000000..bef326d996 --- /dev/null +++ b/Task/Penneys-game/Haskell/penneys-game.hs @@ -0,0 +1,91 @@ +import qualified Data.List as L +import System.IO +import System.Random + +data CoinToss = H | T deriving (Read, Show, Eq) + +parseToss :: String -> [CoinToss] +parseToss [] = [] +parseToss (s:sx) + | s == 'h' || s == 'H' = H : parseToss sx + | s == 't' || s == 'T' = T : parseToss sx + | otherwise = parseToss sx + +notToss :: CoinToss -> CoinToss +notToss H = T +notToss T = H + +instance Random CoinToss where + random g = let (b, gb) = random g in (if b then H else T, gb) + randomR = undefined + +prompt :: (Read a) => String -> String -> (String -> Maybe a) -> IO a +prompt msg err parse = do + putStrLn msg + line <- getLine + let ans = parse line + case ans of + Nothing -> do + putStrLn err + prompt msg err parse + Just ansB -> return ansB + +showCat :: (Show a) => [a] -> String +showCat = concatMap show + +data Winner = Player | CPU + +-- This may never terminate. +runToss :: (RandomGen g) => [CoinToss] -> [CoinToss] -> g -> ([CoinToss], Winner) +runToss player cpu gen = + let stream = randoms gen + run ss@(s:sx) + | L.isPrefixOf player ss = player + | L.isPrefixOf cpu ss = cpu + | otherwise = s : run sx + winner = run stream + in if L.isSuffixOf player winner + then (winner, Player) + else (winner, CPU) + +game :: (RandomGen g, Num a, Show a) => Bool -> a -> a -> g -> IO () +game cpuTurn playerScore cpuScore gen = do + putStrLn $ "\nThe current score is CPU: " ++ show cpuScore + ++ ", You: " ++ show playerScore + + let (genA, genB) = split gen + promptPlayer check = + prompt "Pick 3 coin sides: " "Invalid input." $ \s -> + let tosses = parseToss s in + if check tosses then Just tosses else Nothing + promptCpu x = putStrLn $ "I have chosen: " ++ showCat x + + (tosses, winner) <- + if cpuTurn + then do + let cpuChoice = take 3 $ randoms gen + promptCpu cpuChoice + playerChoice <- promptPlayer $ \n -> n /= cpuChoice && 3 == length n + return $ runToss playerChoice cpuChoice genA + else do + playerChoice <- promptPlayer $ \n -> 3 == length n + let cpuChoice = case playerChoice of [a,b,_] -> [notToss b, a, b] + promptCpu cpuChoice + return $ runToss playerChoice cpuChoice genA + + putStrLn $ "The sequence tossed was: " ++ showCat tosses + + case winner of + Player -> do + putStrLn "You win!" + game (not cpuTurn) (playerScore + 1) cpuScore genB + CPU -> do + putStrLn "I win!" + game (not cpuTurn) playerScore (cpuScore + 1) genB + +main :: IO () +main = do + hSetBuffering stdin LineBuffering + stdgen <- getStdGen + let (cpuFirst, genA) = random stdgen + game cpuFirst 0 0 genA diff --git a/Task/Penneys-game/J/penneys-game-1.j b/Task/Penneys-game/J/penneys-game-1.j new file mode 100644 index 0000000000..e377045393 --- /dev/null +++ b/Task/Penneys-game/J/penneys-game-1.j @@ -0,0 +1,28 @@ +require 'format/printf numeric' + +randomize '' NB. randomize seed for new session + +Vals=: 'HT' NB. valid values +input=: 1!:1@<&1: NB. get input from user +prompt=: input@echo NB. prompt user for input +checkInput=: 'Choose 3 H/Ts' assert (Vals e.~ ]) , 3 = # +getUserSeq=: (] [ checkInput)@toupper@prompt +choose1st=: Vals {~ 3 ?@$ 2: NB. computer chooses 1st +choose2nd=: (0 1 1=1 0 1{])&.(Vals&i.) NB. computer chooses 2nd + +playPenney=: verb define + if. ?2 do. NB. randomize first chooser + Comp=. choose1st '' + 'Computer chose %s' printf ; +enum Yay ; +enum Boo ; +enum Bozo «'Dude' 'Cha' 'Bzzt' 'Hey' 'Silly dilly' 'Say what!?' 'You numbskull'»; + +sub flipping { + for 1..4 { + print "-\b"; sleep .1; + print "\\\b"; sleep .1; + print "|\b"; sleep .1; + print "/\b"; sleep .1; + } +} + +sub your-choice($p is copy) { + loop (my @seq; @seq != 3; $p = "{Bozo.pick}! Please pick exactly 3: ") { + @seq = prompt($p).uc.comb(/ H | T /).map: { + when 'H' { Heads } + when 'T' { Tails } + } + } + @seq; +} + +repeat until prompt("Wanna play again? ").lc ~~ /^n/ { + my $mefirst = Coin.roll; + print tc "$mefirst I start, {Coin(+!$mefirst).lc} you start, flipping...\n\t"; + flipping; + say my $flip = Coin.roll; + + my @yours; + my @mine; + + if $flip == $mefirst { + print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = Coin.roll(3); + @yours = your-choice("Now you gotta choose: "); + while @yours eqv @mine { + say "{Bozo.pick}! We'd both win at the same time if you pick that!"; + @yours = your-choice("Pick something different from me: "); + } + say "So, you'll win if we see: ", @yours; + } + else { + @yours = your-choice("{Boo.pick}! First you choose: "); + say "OK, you'll win if we see: ", @yours; + print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), @yours[0,1]; + } + + sub check($a,$b,$c) { + given [$a,$b,$c] { + when @mine { say "\n{Yay.pick}, I win, and you lose!"; Nil } + when @yours { say "\n{Boo.pick}, you win, but I'll beat you next time!"; Nil } + default { Coin.roll } + } + } + + sleep 1; + say < OK! Ready? Right... So... Yo!>.pick; + sleep .5; + say ("Pay attention now!", + "Watch closely!", + "Let's do it...", + "You feeling lucky?", + "No way you gonna win this...", + "Can I borrow that coin again?").pick; + sleep 1; + print "Here we go!\n\t"; + for Coin.roll(3), &check ...^ :!defined { + flipping; + print "$_ "; + } +} diff --git a/Task/Penneys-game/Python/penneys-game.py b/Task/Penneys-game/Python/penneys-game.py new file mode 100644 index 0000000000..b34540aa12 --- /dev/null +++ b/Task/Penneys-game/Python/penneys-game.py @@ -0,0 +1,30 @@ +from __future__ import print_function +import random +from time import sleep + +first = random.choice([True, False]) + +you = '' +if first: + me = ''.join(random.sample('HT'*3, 3)) + print('I choose first and will win on first seeing {} in the list of tosses'.format(me)) + while len(you) != 3 or any(ch not in 'HT' for ch in you) or you == me: + you = input('What sequence of three Heads/Tails will you win with: ') +else: + while len(you) != 3 or any(ch not in 'HT' for ch in you): + you = input('After you: What sequence of three Heads/Tails will you win with: ') + me = ('H' if you[1] == 'T' else 'T') + you[:2] + print('I win on first seeing {} in the list of tosses'.format(me)) + +print('Rolling:\n ', end='') +rolled = '' +while True: + rolled += random.choice('HT') + print(rolled[-1], end='') + if rolled.endswith(you): + print('\n You win!') + break + if rolled.endswith(me): + print('\n I win!') + break + sleep(1) # For dramatic effect diff --git a/Task/Penneys-game/README b/Task/Penneys-game/README new file mode 100644 index 0000000000..ef9c4cf217 --- /dev/null +++ b/Task/Penneys-game/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Penney's_game diff --git a/Task/Penneys-game/REXX/penneys-game.rexx b/Task/Penneys-game/REXX/penneys-game.rexx new file mode 100644 index 0000000000..c88e228eb4 --- /dev/null +++ b/Task/Penneys-game/REXX/penneys-game.rexx @@ -0,0 +1,67 @@ +/*REXX program plays Penney's Game, a 2-player coin toss sequence game.*/ +__=copies('─',9) /*literal for eyecatching fence. */ +signal on halt /*a clean way out if CLBF quits. */ +parse arg # ? . /*get optional args from the C.L.*/ +if #=='' | #=="," then #=3 /*default coin sequence length. */ +if ?\=='' & ?\==',' then call random ,,? /*use seed for RANDOM #s ?*/ +wins=0; do games=1 /*play a number of Penney's games*/ + call game /*play a single inning of a game.*/ + end /*games*/ /*keep at it 'til QUIT or halt.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one-line subroutines────────────────*/ +halt: say; say __ "Penney's Game was halted."; say; exit 13 +r: arg ,$; do arg(1); $=$||random(0,1); end; return $ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ +/*──────────────────────────────────GAME subroutine─────────────────────*/ +game: @.=; tosses=@. /*the coin toss sequence so far. */ +toss1=r(1) /*result: 0=computer, 1=CBLF.*/ +if \toss1 then call randComp /*maybe let the computer go first*/ +if toss1 then say __ "You win the first toss, so you pick your sequence first." + else say __ "The computer won first toss, the pick was: " @.comp + call prompter /*get the human's guess from C.L.*/ + call randComp /*get computer's guess if needed.*/ + /*CBLF: carbon-based life form. */ +say __ " your pick:" @.CBLF /*echo human's pick to terminal. */ +say __ "computer's pick:" @.comp /* " comp.'s " " " */ +say /* [↓] flip the coin 'til a win.*/ + do flips=1 until pos(@.CBLF,tosses)\==0 | pos(@.comp,tosses)\==0 + tosses=tosses || translate(r(1),'HT',10) + end /*flips*/ /* [↑] this is a flipping coin,*/ + /* [↓] series of tosses*/ +say __ "The tossed coin series was: " tosses /*show the coin tosses.*/ +say +@@@="won this toss with " flips ' coin tosses.' /*handy literal.*/ +if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end + else say __ "The computer" @@@ +_=wins; if _==0 then _='no' /*use gooder English.*/ +say __ "You've won" _ "game"s(wins) 'out of ' games"." +say; say copies('╩╦',79%2)'╩'; say /*show eyeball fence.*/ +return +/*──────────────────────────────────PROMPTER subroutine─────────────────*/ +prompter: oops=__ 'Oops! '; a= /*define some handy REXX literals*/ +@a_z='ABCDEFG-IJKLMNOPQRS+UVWXYZ' /*the extraneous alphabetic chars*/ +p=__ 'Pick a sequence of' # "coin tosses of H or T (Heads or Tails) or Quit:" + do until ok; say; say p; pull a /*uppercase the answer.*/ + if abbrev('QUIT',a,1) then exit 1 /*human wants to quit. */ + a=space(translate(a,,@a_z',./\;:_'),0) /*elide extraneous chrs*/ + b=translate(a,10,'HT'); L=length(a) /*tran───►bin; get len.*/ + ok=0 /*response is OK so far*/ + select /*verify user response.*/ + when \datatype(b,'B') then say oops "Illegal response." + when \datatype(a,'M') then say oops "Illegal characters in response." + when L==0 then say oops "No choice was given." + when L<# then say oops "Not enough coin choices." + when L># then say oops "Too many coin choices." + when a==@.comp then say oops "You can't choose the computer's choice: " @.comp + otherwise ok=1 + end /*select*/ + end /*until ok*/ +@.CBLF=a; @.CBLF!=b /*we have the human's guess now. */ +return +/*──────────────────────────────────RANDCOMP subroutine─────────────────*/ +randComp: if @.comp\=='' then return /*the computer already has a pick*/ +_=@.CBLF! /* [↓] use best-choice algorithm.*/ +if _\=='' then g=left((\substr(_,min(2,#),1))left(_,1)substr(_,3),#) + do until g\==@.CBLF!; g=r(#); end /*otherwise, generate a choice. */ +@.comp=translate(g,'HT',10) +return diff --git a/Task/Penneys-game/Racket/penneys-game.rkt b/Task/Penneys-game/Racket/penneys-game.rkt new file mode 100644 index 0000000000..f4dfb7dd96 --- /dev/null +++ b/Task/Penneys-game/Racket/penneys-game.rkt @@ -0,0 +1,37 @@ +#lang racket +;; Penney's Game. Tim Brown 2014-10-15 +(define (flip . _) (match (random 2) (0 "H") (1 "T"))) + +(define (get-human-sequence) ; no sanity checking here! + (display "choose your winning sequence of 3 H or T > ") + (drop-right (drop (string-split (string-upcase (read-line)) "") 1) 1)) + +(define flips->string (curryr string-join ".")) + +(define (game-on p1 p2) + (printf "~a chooses: ~a. ~a chooses: ~a~%" + (car p1) (flips->string (cdr p1)) (car p2) (flips->string (cdr p2))) + (match-define (list (list name.1 p1.1 p1.2 p1.3) (list name.2 p2.1 p2.2 p2.3)) (list p1 p2)) + (let turn ((seq null)) + (match seq + [(list-rest (== p1.3) (== p1.2) (== p1.1) _) name.1] + [(list-rest (== p2.3) (== p2.2) (== p2.1) _) name.2] + [else + (let* ((flp (flip)) (seq+ (cons flp else))) + (printf "new-flip: ~a -> ~a~%" flp (flips->string (reverse seq+))) (turn seq+))]))) + +(define (play-game) + (define-values + (player-1 player-2) + (match (flip) + ["H" (printf "Human chooses first: ") + (define p1 (cons 'Hom-Sap (get-human-sequence))) + (values p1 (cons 'Computer + (match p1 + [(list _ f1 (and f2 (app (match-lambda ("H" "T") ("T" "H")) ¬f2)) _) + (list ¬f2 f1 f2)])))] + ["T" (printf "Computer chooses first. ") + (define p1 (cons 'Computer (build-list 3 flip))) + (printf "~a chooses: ~a~%" (car p1) (flips->string (cdr p1))) + (values p1 (cons 'Hom-Sap (get-human-sequence)))])) + (printf "~a wins!~%" (game-on player-1 player-2))) diff --git a/Task/Penneys-game/Ruby/penneys-game.rb b/Task/Penneys-game/Ruby/penneys-game.rb new file mode 100644 index 0000000000..fa38533884 --- /dev/null +++ b/Task/Penneys-game/Ruby/penneys-game.rb @@ -0,0 +1,35 @@ +# Penney's Game + +Toss = [:Heads, :Tails] + +def yourChoice + puts "Enter your choice (H/T)" + choice = [] + 3.times do + until (c = $stdin.getc.upcase) == "H" or c == "T" + end + choice << (c=="H" ? Toss[0] : Toss[1]) + end + puts "You chose #{choice.join(' ')}" + choice +end + +puts "%s I start, %s you start ..... #{coin = Toss.sample}" % Toss +if coin == Toss[0] + myC = Array.new(3){Toss.sample} + puts "I chose #{myC.join(' ')}" + yC = yourChoice +else + yC = yourChoice + myC = Toss - [yC[1]] + yC.first(2) + puts "I chose #{myC.join(' ')}" +end + +seq = Array.new(3){Toss.sample} +print seq.join(' ') +loop do + puts "\n I win!" or break if seq == myC + puts "\n You win!" or break if seq == yC + seq.push(Toss.sample).shift + print " #{seq[-1]}" +end diff --git a/Task/Penneys-game/Tcl/penneys-game.tcl b/Task/Penneys-game/Tcl/penneys-game.tcl new file mode 100644 index 0000000000..8dc64ac42f --- /dev/null +++ b/Task/Penneys-game/Tcl/penneys-game.tcl @@ -0,0 +1,98 @@ +package require Tcl 8.6 + +oo::class create Player { + variable who seq seen idx + + constructor {name sequence} { + set who $name + set seq $sequence + set seen {} + set idx end-[expr {[string length $seq] - 1}] + } + + method pick {} { + return $seq + } + + method name {} { + return $who + } + + method match {digit} { + append seen $digit + return [expr {[string range $seen $idx end] eq $seq}] + } +} + +oo::class create HumanPlayer { + superclass Player + constructor {length {otherPlayersSelection ""}} { + fconfigure stdout -buffering none + while true { + puts -nonewline "What do you pick? (length $length): " + if {[gets stdin pick] < 0} exit + set pick [regsub -all {[^HT]} [string map {0 H 1 T h H t T} $pick] ""] + if {[string length $pick] eq $length} break + puts "That's not a legal pick!" + } + set name "Human" + if {[incr ::humans] > 1} {append name " #$::humans"} + next $name $pick + } +} + +oo::class create RobotPlayer { + superclass Player + constructor {length {otherPlayersSelection ""}} { + if {$otherPlayersSelection eq ""} { + set pick "" + for {set i 0} {$i < $length} {incr i} { + append pick [lindex {H T} [expr {int(rand()*2)}]] + } + } else { + if {$length != 3} { + error "lengths other than 3 not implemented" + } + lassign [split $otherPlayersSelection ""] a b c + set pick [string cat [string map {H T T H} $b] $a $b] + } + set name "Robot" + if {[incr ::robots] > 1} {append name " #$::robots"} + puts "$name picks $pick" + next $name $pick + } +} + +proc game {length args} { + puts "Let's play Penney's Game!" + + # instantiate the players + set picks {} + set players {} + while {[llength $args]} { + set idx [expr {int(rand()*[llength $args])}] + set p [[lindex $args $idx] new $length {*}$picks] + set args [lreplace $args $idx $idx] + lappend players $p + lappend picks [$p pick] + } + + # sanity check + if {[llength $picks] != [llength [lsort -unique $picks]]} { + puts "Two players picked the same thing; that's illegal" + } + + # do the game loop + while 1 { + set coin [lindex {H T} [expr {int(rand()*2)}]] + puts "Coin flip [incr counter] is $coin" + foreach p $players { + if {[$p match $coin]} { + puts "[$p name] has won!" + return + } + } + } +} + +game 3 HumanPlayer RobotPlayer diff --git a/Task/Penneys-game/UNIX-Shell/penneys-game.sh b/Task/Penneys-game/UNIX-Shell/penneys-game.sh new file mode 100644 index 0000000000..42926c9b8a --- /dev/null +++ b/Task/Penneys-game/UNIX-Shell/penneys-game.sh @@ -0,0 +1,70 @@ +#!/bin/bash +main() { + echo "Penney's Game" + echo -n "Flipping to see who goes first ... " + + if [[ $(flip) == H ]]; then + echo "I do." + p2=$(choose_sequence) + echo "I choose: $p2" + else + echo "You do." + fi + + while true; do + echo "Enter your three-flip sequence:" + read p1 + case "$p1" in + "$p2") echo "Sequence must be different from mine";; + [hHTt][hHtT][hHtT]) break;; + *) echo "Sequence must be three H's or T's";; + esac + done + p1=$(tr a-z A-Z <<<"$p1") + + if [ -z "$p2" ]; then + p2=$(choose_sequence "$p1") + echo "I choose: $p2" + fi + + echo + echo "Here we go. $p1, you win; $p2, I win." + flips= + + while true; do + flip=$(flip) + echo -n $flip + flips+=$flip + while (( ${#flips} > 3 )); do + flips="${flips#?}" + done + case "$flips" in + *$p1) echo $'\nYou win!'; exit 0;; + *$p2) echo $'\nI win!'; exit 1;; + esac + done +} + +choose_sequence() { + local result + if (( $# )); then + case "$1" in + ?Hh?) result=T;; + *) result=H;; + esac + result+="${1%?}" + else + result=$(flip)$(flip)$(flip) + fi + echo "$result" +} + +flip() { + if (( RANDOM % 2 )); then + echo H + else + echo T + fi +} + +main "$@" diff --git a/Task/Percolation-Bond-percolation/00DESCRIPTION b/Task/Percolation-Bond-percolation/00DESCRIPTION new file mode 100644 index 0000000000..62a37092d2 --- /dev/null +++ b/Task/Percolation-Bond-percolation/00DESCRIPTION @@ -0,0 +1,23 @@ +{{Percolation Simulation}} +Given an M \times N rectangular array of cells numbered \mathrm{cell}[0..M-1, 0..N-1]assume M is horizontal and N is downwards. Each \mathrm{cell}[m, n] is bounded by (horizontal) walls \mathrm{hwall}[m, n] and \mathrm{hwall}[m+1, n]; (vertical) walls \mathrm{vwall}[m, n] and \mathrm{vwall}[m, n+1] + +Assume that the probability of any wall being present is a constant p where +: 0.0 \le p \le 1.0 +Except for the outer horizontal walls at m = 0 and m = M which are always present. + +;The task: +Simulate pouring a fluid onto the top surface (n = 0) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall. + +The fluid does not move beyond the horizontal constraints of the grid. + +The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point. + +Given p repeat the percolation t times to estimate the proportion of times that the fluid can percolate to the bottom for any given p. + +Show how the probability of percolating through the random grid changes with p going from 0.0 to 1.0 in 0.1 increments and with the number of repetitions to estimate the fraction at any given p as t = 100. + +Use an M=10, N=10 grid of cells for all cases. + +Optionally depict fluid successfully percolating through a grid graphically. + +Show all output on this page. diff --git a/Task/Percolation-Bond-percolation/00META.yaml b/Task/Percolation-Bond-percolation/00META.yaml new file mode 100644 index 0000000000..a345140340 --- /dev/null +++ b/Task/Percolation-Bond-percolation/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Percolation Simulations diff --git a/Task/Percolation-Bond-percolation/C/percolation-bond-percolation.c b/Task/Percolation-Bond-percolation/C/percolation-bond-percolation.c new file mode 100644 index 0000000000..fc9e1dace1 --- /dev/null +++ b/Task/Percolation-Bond-percolation/C/percolation-bond-percolation.c @@ -0,0 +1,100 @@ +#include +#include +#include + +// cell states +#define FILL 1 +#define RWALL 2 // right wall +#define BWALL 4 // bottom wall + +typedef unsigned int c_t; + +c_t *cells, *start, *end; +int m, n; + +void make_grid(double p, int x, int y) +{ + int i, j, thresh = RAND_MAX * p; + m = x, n = y; + + // Allocate two addition rows to avoid checking bounds. + // Bottom row is also required by drippage + start = realloc(start, m * (n + 2) * sizeof(c_t)); + cells = start + m; + + for (i = 0; i < m; i++) + start[i] = BWALL | RWALL; + + for (i = 0, end = cells; i < y; i++) { + for (j = x; --j; ) + *end++ = (rand() < thresh ? BWALL : 0) + |(rand() < thresh ? RWALL : 0); + *end++ = RWALL | (rand() < thresh ? BWALL: 0); + } + memset(end, 0, sizeof(c_t) * m); +} + +void show_grid(void) +{ + int i, j; + + for (j = 0; j < m; j++) printf("+--"); + puts("+"); + + for (i = 0; i <= n; i++) { + putchar(i == n ? ' ' : '|'); + for (j = 0; j < m; j++) { + printf((cells[i*m + j] & FILL) ? "[]" : " "); + putchar((cells[i*m + j] & RWALL) ? '|' : ' '); + } + putchar('\n'); + + if (i == n) return; + + for (j = 0; j < m; j++) + printf((cells[i*m + j] & BWALL) ? "+--" : "+ "); + puts("+"); + } +} + +int fill(c_t *p) +{ + if ((*p & FILL)) return 0; + *p |= FILL; + if (p >= end) return 1; // success: reached bottom row + + return ( !(p[ 0] & BWALL) && fill(p + m) ) || + ( !(p[ 0] & RWALL) && fill(p + 1) ) || + ( !(p[-1] & RWALL) && fill(p - 1) ) || + ( !(p[-m] & BWALL) && fill(p - m) ); +} + +int percolate(void) +{ + int i; + for (i = 0; i < m && !fill(cells + i); i++); + + return i < m; +} + +int main(void) +{ + make_grid(.5, 10, 10); + percolate(); + show_grid(); + + int cnt, i, p; + + puts("\nrunning 10x10 grids 10000 times for each p:"); + for (p = 1; p < 10; p++) { + for (cnt = i = 0; i < 10000; i++) { + make_grid(p / 10., 10, 10); + cnt += percolate(); + //show_grid(); // don't + } + printf("p = %3g: %.4f\n", p / 10., (double)cnt / i); + } + + free(start); + return 0; +} diff --git a/Task/Percolation-Bond-percolation/D/percolation-bond-percolation.d b/Task/Percolation-Bond-percolation/D/percolation-bond-percolation.d new file mode 100644 index 0000000000..22cb10d04c --- /dev/null +++ b/Task/Percolation-Bond-percolation/D/percolation-bond-percolation.d @@ -0,0 +1,106 @@ +import std.stdio, std.random, std.array, std.range, std.algorithm; + +struct Grid { + // Not enforced by runtime and type system: + // a Cell must contain only the flags bits. + alias Cell = uint; + + enum : Cell { // Cell states (bit flags). + empty = 0, + filled = 1, + rightWall = 2, + bottomWall = 4 + } + + const size_t nc, nr; + Cell[] cells; + + this(in size_t nRows, in size_t nCols) pure nothrow { + nr = nRows; + nc = nCols; + + // Allocate two addition rows to avoid checking bounds. + // Bottom row is also required by drippage. + cells = new Cell[nc * (nr + 2)]; + } + + void initialize(in double prob, ref Xorshift rng) { + cells[0 .. nc] = bottomWall | rightWall; // First row. + + uint pos = nc; + foreach (immutable r; 1 .. nr + 1) { + foreach (immutable c; 1 .. nc) + cells[pos++] = (uniform01 < prob ?bottomWall : empty) | + (uniform01 < prob ? rightWall : empty); + cells[pos++] = rightWall | + (uniform01 < prob ? bottomWall : empty); + } + + cells[$ - nc .. $] = empty; // Last row. + } + + bool percolate() pure nothrow @nogc { + bool fill(in size_t i) pure nothrow @nogc { + if (cells[i] & filled) + return false; + + cells[i] |= filled; + + if (i >= cells.length - nc) + return true; // Success: reached bottom row. + + return (!(cells[i] & bottomWall) && fill(i + nc)) || + (!(cells[i] & rightWall) && fill(i + 1)) || + (!(cells[i - 1] & rightWall) && fill(i - 1)) || + (!(cells[i - nc] & bottomWall) && fill(i - nc)); + } + + return iota(nc, nc + nc).any!fill; + } + + void show() const { + writeln("+-".replicate(nc), '+'); + + foreach (immutable r; 1 .. nr + 2) { + write(r == nr + 1 ? ' ' : '|'); + foreach (immutable c; 0 .. nc) { + immutable cell = cells[r * nc + c]; + write((cell & filled) ? (r <= nr ? '#' : 'X') : ' '); + write((cell & rightWall) ? '|' : ' '); + } + writeln; + + if (r == nr + 1) + return; + + foreach (immutable c; 0 .. nc) + write((cells[r * nc + c] & bottomWall) ? "+-" : "+ "); + '+'.writeln; + } + } +} + +void main() { + enum uint nr = 10, nc = 10; // N. rows and columns of the grid. + enum uint nTries = 10_000; // N. simulations for each probability. + enum uint nStepsProb = 10; // N. steps of probability. + + auto rng = Xorshift(2); + auto g = Grid(nr, nc); + g.initialize(0.5, rng); + g.percolate; + g.show; + + writefln("\nRunning %dx%d grids %d times for each p:", + nr, nc, nTries); + foreach (immutable p; 0 .. nStepsProb) { + immutable probability = p / double(nStepsProb); + uint nPercolated = 0; + foreach (immutable i; 0 .. nTries) { + g.initialize(probability, rng); + nPercolated += g.percolate; + } + writefln("p = %0.2f: %.4f", + probability, nPercolated / double(nTries)); + } +} diff --git a/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go b/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go new file mode 100644 index 0000000000..d6711d7fd6 --- /dev/null +++ b/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go @@ -0,0 +1,132 @@ +package main + +import ( + "bytes" + "fmt" + "math/rand" + "time" +) + +func main() { + const ( + m, n = 10, 10 + t = 1000 + minp, maxp, Δp = 0.1, 0.99, 0.1 + ) + + // Purposely don't seed for a repeatable example grid: + g := NewGrid(.5, m, n) + g.Percolate() + fmt.Println(g) + + rand.Seed(time.Now().UnixNano()) // could pick a better seed + for p := float64(minp); p < maxp; p += Δp { + count := 0 + for i := 0; i < t; i++ { + g := NewGrid(p, m, n) + if g.Percolate() { + count++ + } + } + fmt.Printf("p=%.2f, %.3f\n", p, float64(count)/t) + } +} + +type cell struct { + full bool + right, down bool // true if open to the right (x+1) or down (y+1) +} + +type grid struct { + cell [][]cell // row first, i.e. [y][x] +} + +func NewGrid(p float64, xsize, ysize int) *grid { + g := &grid{cell: make([][]cell, ysize)} + for y := range g.cell { + g.cell[y] = make([]cell, xsize) + for x := 0; x < xsize-1; x++ { + if rand.Float64() > p { + g.cell[y][x].right = true + } + if rand.Float64() > p { + g.cell[y][x].down = true + } + } + if rand.Float64() > p { + g.cell[y][xsize-1].down = true + } + } + return g +} + +var ( + full = map[bool]string{false: " ", true: "**"} + hopen = map[bool]string{false: "--", true: " "} + vopen = map[bool]string{false: "|", true: " "} +) + +func (g *grid) String() string { + var buf bytes.Buffer + // Don't really need to call Grow but it helps avoid multiple + // reallocations if the size is large. + buf.Grow((len(g.cell) + 1) * len(g.cell[0]) * 7) + + for _ = range g.cell[0] { + buf.WriteString("+") + buf.WriteString(hopen[false]) + } + buf.WriteString("+\n") + for y := range g.cell { + buf.WriteString(vopen[false]) + for x := range g.cell[y] { + buf.WriteString(full[g.cell[y][x].full]) + buf.WriteString(vopen[g.cell[y][x].right]) + } + buf.WriteByte('\n') + for x := range g.cell[y] { + buf.WriteString("+") + buf.WriteString(hopen[g.cell[y][x].down]) + } + buf.WriteString("+\n") + } + ly := len(g.cell) - 1 + for x := range g.cell[ly] { + buf.WriteByte(' ') + buf.WriteString(full[g.cell[ly][x].down && g.cell[ly][x].full]) + } + return buf.String() +} + +func (g *grid) Percolate() bool { + for x := range g.cell[0] { + if g.fill(x, 0) { + return true + } + } + return false +} + +func (g *grid) fill(x, y int) bool { + if y >= len(g.cell) { + return true // Out the bottom + } + if g.cell[y][x].full { + return false // Allready filled + } + g.cell[y][x].full = true + + if g.cell[y][x].down && g.fill(x, y+1) { + return true + } + if g.cell[y][x].right && g.fill(x+1, y) { + return true + } + if x > 0 && g.cell[y][x-1].right && g.fill(x-1, y) { + return true + } + if y > 0 && g.cell[y-1][x].down && g.fill(x, y-1) { + return true + } + return false +} diff --git a/Task/Percolation-Bond-percolation/Python/percolation-bond-percolation.py b/Task/Percolation-Bond-percolation/Python/percolation-bond-percolation.py new file mode 100644 index 0000000000..b30fb1c41c --- /dev/null +++ b/Task/Percolation-Bond-percolation/Python/percolation-bond-percolation.py @@ -0,0 +1,83 @@ +from collections import namedtuple +from random import random +from pprint import pprint as pp + +Grid = namedtuple('Grid', 'cell, hwall, vwall') + +M, N, t = 10, 10, 100 + +class PercolatedException(Exception): pass + +HVF = [(' .', ' _'), (':', '|'), (' ', '#')] # Horiz, vert, fill chars + +def newgrid(p): + hwall = [[int(random() < p) for m in range(M)] + for n in range(N+1)] + vwall = [[(1 if m in (0, M) else int(random() < p)) for m in range(M+1)] + for n in range(N)] + cell = [[0 for m in range(M)] + for n in range(N)] + return Grid(cell, hwall, vwall) + +def pgrid(grid, percolated=None): + cell, hwall, vwall = grid + h, v, f = HVF + for n in range(N): + print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) + print('%i) ' % (n % 10) + ''.join(v[vwall[n][m]] + f[cell[n][m] if m < M else 0] + for m in range(M+1))[:-1]) + n = N + print(' ' + ''.join(h[hwall[n][m]] for m in range(M))) + if percolated: + where = percolated.args[0][0] + print('!) ' + ' ' * where + ' ' + f[1]) + +def pour_on_top(grid): + cell, hwall, vwall = grid + n = 0 + try: + for m in range(M): + if not hwall[n][m]: + flood_fill(m, n, cell, hwall, vwall) + except PercolatedException as ex: + return ex + return None + + +def flood_fill(m, n, cell, hwall, vwall): + # fill cell + cell[n][m] = 1 + # bottom + if n < N - 1 and not hwall[n + 1][m] and not cell[n+1][m]: + flood_fill(m, n+1, cell, hwall, vwall) + # THE bottom + elif n == N - 1 and not hwall[n + 1][m]: + raise PercolatedException((m, n+1)) + # left + if m and not vwall[n][m] and not cell[n][m - 1]: + flood_fill(m-1, n, cell, hwall, vwall) + # right + if m < M - 1 and not vwall[n][m + 1] and not cell[n][m + 1]: + flood_fill(m+1, n, cell, hwall, vwall) + # top + if n and not hwall[n][m] and not cell[n-1][m]: + flood_fill(m, n-1, cell, hwall, vwall) + +if __name__ == '__main__': + sample_printed = False + pcount = {} + for p10 in range(11): + p = (10 - p10) / 10.0 # count down so sample print is interesting + pcount[p] = 0 + for tries in range(t): + grid = newgrid(p) + percolated = pour_on_top(grid) + if percolated: + pcount[p] += 1 + if not sample_printed: + print('\nSample percolating %i x %i grid' % (M, N)) + pgrid(grid, percolated) + sample_printed = True + print('\n p: Fraction of %i tries that percolate through' % t ) + + pp({p:c/float(t) for p, c in pcount.items()}) diff --git a/Task/Percolation-Bond-percolation/README b/Task/Percolation-Bond-percolation/README new file mode 100644 index 0000000000..c82511edc7 --- /dev/null +++ b/Task/Percolation-Bond-percolation/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Percolation/Bond_percolation diff --git a/Task/Percolation-Bond-percolation/Racket/percolation-bond-percolation.rkt b/Task/Percolation-Bond-percolation/Racket/percolation-bond-percolation.rkt new file mode 100644 index 0000000000..0be5331a8b --- /dev/null +++ b/Task/Percolation-Bond-percolation/Racket/percolation-bond-percolation.rkt @@ -0,0 +1,117 @@ +#lang racket + +(define has-left-wall? (lambda (x) (bitwise-bit-set? x 0))) +(define has-right-wall? (lambda (x) (bitwise-bit-set? x 1))) +(define has-top-wall? (lambda (x) (bitwise-bit-set? x 2))) +(define has-bottom-wall? (lambda (x) (bitwise-bit-set? x 3))) +(define has-fluid? (lambda (x) (bitwise-bit-set? x 4))) + +(define (walls->cell l? r? t? b?) + (+ (if l? 1 0) (if r? 2 0) (if t? 4 0) (if b? 8 0))) + +(define (bonded-percol-grid M N p) + (define rv (make-vector (* M N))) + (for* ((idx (in-range (* M N)))) + (define left-wall? + (or (zero? (modulo idx M)) + (has-right-wall? (vector-ref rv (sub1 idx))))) + (define right-wall? + (or (= (modulo idx M) (sub1 M)) + (< (random) p))) + (define top-wall? + (if (< idx M) (< (random) p) + (has-bottom-wall? (vector-ref rv (- idx M))))) + (define bottom-wall? (< (random) p)) + (define cell-value + (walls->cell left-wall? right-wall? top-wall? bottom-wall?)) + (vector-set! rv idx cell-value)) + rv) + +(define (display-percol-grid M . vs) + (define N (/ (vector-length (car vs)) M)) + (define-syntax-rule (tab-eol m) + (when (= m (sub1 M)) (printf "\t"))) + (for ((n N)) + (for* ((v vs) (m M)) + (when (zero? m) (printf "+")) + (printf + (match (vector-ref v (+ (* n M) m)) + ((? has-top-wall?) "-+") + ((? has-fluid?) "#+") + (else ".+"))) + (tab-eol m)) + (newline) + (for* ((v vs) (m M)) + (when (zero? m) (printf "|")) + (printf + (match (vector-ref v (+ (* n M) m)) + ((and (? has-fluid?) (? has-right-wall?)) "#|") + ((? has-right-wall?) ".|") + ((? has-fluid?) "##") + (else ".."))) + (tab-eol m)) + (newline)) + (for* ((v vs) (m M)) + (when (zero? m) (printf "+")) + (printf + (match (vector-ref v (+ (* (sub1 M) M) m)) + ((? has-bottom-wall?) "-+") + ((? has-fluid?) "#+") + (else ".+"))) + (tab-eol m)) + (newline)) + +(define (find-bonded-grid-t/b-path M v) + (define N (/ (vector-length v) M)) + + (define (flood-cell idx) + (cond + [(= (quotient idx M) N) #t] ; wootiments! + [(has-fluid? (vector-ref v idx)) #f] ; been here + [else (define cell (vector-ref v idx)) + (vector-set! v idx (bitwise-ior cell 16)) + (or (and (not (has-bottom-wall? cell)) (flood-cell (+ idx M))) + (and (not (has-left-wall? cell)) (flood-cell (- idx 1))) + (and (not (has-right-wall? cell)) (flood-cell (+ idx 1))) + (and (not (has-top-wall? cell)) + (>= idx M) ; not top row + (flood-cell (- idx M))))])) + + (for/first ((m (in-range M)) + #:unless (has-top-wall? (vector-ref v m)) + #:when (flood-cell m)) #t)) + +(define t (make-parameter 1000)) +(define (experiment p) + (/ (for*/sum ((sample (in-range (t))) + (v (in-value (bonded-percol-grid 10 10 p))) + #:when (find-bonded-grid-t/b-path 10 v)) 1) + (t))) + +(define (main) + (for ((tenths (in-range 0 (add1 10)))) + (define p (/ tenths 10)) + (define e (experiment p)) + (printf "proportion of grids that percolate p=~a : ~a (~a)~%" + p e (real->decimal-string e 5)))) + +(module+ test + (define (make/display/flood/display-bonded-grid M N p attempts (atmpt 1)) + (define v (bonded-percol-grid M N p)) + (define v+ (vector-copy v)) + (cond [(or (find-bonded-grid-t/b-path M v+) (= attempts 0)) + (define v* (vector-copy v+)) + (define (flood-bonded-grid) + (when (find-bonded-grid-t/b-path M v*) + (flood-bonded-grid))) + (flood-bonded-grid) + (display-percol-grid M v v+ v*) + (printf "After ~a attempt(s)~%~%" atmpt)] + [else + (make/display/flood/display-bonded-grid + M N p (sub1 attempts) (add1 atmpt))])) + + (make/display/flood/display-bonded-grid 10 10 0 20) + (make/display/flood/display-bonded-grid 10 10 .25 20) + (make/display/flood/display-bonded-grid 10 10 .50 20) + (make/display/flood/display-bonded-grid 10 10 .75 20000)) diff --git a/Task/Percolation-Bond-percolation/Tcl/percolation-bond-percolation.tcl b/Task/Percolation-Bond-percolation/Tcl/percolation-bond-percolation.tcl new file mode 100644 index 0000000000..37b137b45c --- /dev/null +++ b/Task/Percolation-Bond-percolation/Tcl/percolation-bond-percolation.tcl @@ -0,0 +1,112 @@ +package require Tcl 8.6 + +# Structure the bond percolation system as a class +oo::class create BondPercolation { + variable hwall vwall cells M N + constructor {width height probability} { + set M $height + set N $width + for {set i 0} {$i <= $height} {incr i} { + for {set j 0;set walls {}} {$j < $width} {incr j} { + lappend walls [expr {rand() < $probability}] + } + lappend hwall $walls + } + for {set i 0} {$i <= $height} {incr i} { + for {set j 0;set walls {}} {$j <= $width} {incr j} { + lappend walls [expr {$j==0 || $j==$width || rand() < $probability}] + } + lappend vwall $walls + } + set cells [lrepeat $height [lrepeat $width 0]] + } + + method print {{percolated ""}} { + set nw [string length $M] + set grid $cells + if {$percolated ne ""} { + lappend grid [lrepeat $N 0] + lset grid end $percolated 1 + } + foreach hws $hwall vws [lrange $vwall 0 end-1] r $grid { + incr row + puts -nonewline [string repeat " " [expr {$nw+2}]] + foreach w $hws { + puts -nonewline [if {$w} {subst "+-"} {subst "+ "}] + } + puts "+" + puts -nonewline [format "%-*s" [expr {$nw+2}] [expr { + $row>$M ? $percolated eq "" ? " " : ">" : "$row)" + }]] + foreach v $vws c $r { + puts -nonewline [if {$v==1} {subst "|"} {subst " "}] + puts -nonewline [if {$c==1} {subst "#"} {subst " "}] + } + puts "" + } + } + + method percolate {} { + try { + for {set i 0} {$i < $N} {incr i} { + if {![lindex $hwall 0 $i]} { + my FloodFill $i 0 + } + } + return "" + } trap PERCOLATED n { + return $n + } + } + method FloodFill {x y} { + # fill cell + lset cells $y $x 1 + # bottom + if {![lindex $hwall [expr {$y+1}] $x]} { + if {$y == $N-1} { + # THE bottom + throw PERCOLATED $x + } + if {$y < $N-1 && ![lindex $cells [expr {$y+1}] $x]} { + my FloodFill $x [expr {$y+1}] + } + } + # left + if {![lindex $vwall $y $x] && ![lindex $cells $y [expr {$x-1}]]} { + my FloodFill [expr {$x-1}] $y + } + # right + if {![lindex $vwall $y [expr {$x+1}]] && ![lindex $cells $y [expr {$x+1}]]} { + my FloodFill [expr {$x+1}] $y + } + # top + if {$y>0 && ![lindex $hwall $y $x] && ![lindex $cells [expr {$y-1}] $x]} { + my FloodFill $x [expr {$y-1}] + } + } +} + +# Demonstrate one run +puts "Sample percolation, 10x10 p=0.5" +BondPercolation create bp 10 10 0.5 +bp print [bp percolate] +bp destroy +puts "" + +# Collect some aggregate statistics +apply {{} { + puts "Percentage of tries that percolate, varying p" + set tries 100 + for {set pint 0} {$pint <= 10} {incr pint} { + set p [expr {$pint * 0.1}] + set tot 0 + for {set i 0} {$i < $tries} {incr i} { + set bp [BondPercolation new 10 10 $p] + if {[$bp percolate] ne ""} { + incr tot + } + $bp destroy + } + puts [format "p=%.2f: %2.1f%%" $p [expr {$tot*100./$tries}]] + } +}} diff --git a/Task/Percolation-Mean-cluster-density/00DESCRIPTION b/Task/Percolation-Mean-cluster-density/00DESCRIPTION new file mode 100644 index 0000000000..b33710b784 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/00DESCRIPTION @@ -0,0 +1,22 @@ +{{Percolation Simulation}} +Let c be a 2D boolean square matrix of n \times n values of either 1 or 0 where the +probability of any value being 1 is p, (and of 0 is therefore 1-p). +We define a ''cluster'' of 1's as being a group of 1's connected vertically or +horizontally (i.e., using the [[wp:Von Neumann neighborhood|Von Neumann neighborhood rule]]) and bounded by either 0 or by the limits of the matrix. +Let the number of such clusters in such a randomly constructed matrix be C_n. + +Percolation theory states that K(p) (the mean cluster density) will satisfy K(p) = C_n / n^2 as n tends to infinity. For p = 0.5, K(p) is found numerically to approximate 0.065770... + +;Task + +Show the effect of varying n on the accuracy of simulated K(p) for p = 0.5 and +for values of n up to at least 1000. +Any calculation of C_n for finite n is subject to randomness, so an approximation should be +computed as the average of t runs, where t5. + +For extra credit, graphically show clusters in a 15\times 15, p=0.5 grid. + +Show your output here. + +;See also +* [http://mathworld.wolfram.com/s-Cluster.html s-Cluster] on Wolfram mathworld. diff --git a/Task/Percolation-Mean-cluster-density/00META.yaml b/Task/Percolation-Mean-cluster-density/00META.yaml new file mode 100644 index 0000000000..a345140340 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Percolation Simulations diff --git a/Task/Percolation-Mean-cluster-density/C/percolation-mean-cluster-density.c b/Task/Percolation-Mean-cluster-density/C/percolation-mean-cluster-density.c new file mode 100644 index 0000000000..08ab1299de --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/C/percolation-mean-cluster-density.c @@ -0,0 +1,77 @@ +#include +#include + +int *map, w, ww; + +void make_map(double p) +{ + int i, thresh = RAND_MAX * p; + i = ww = w * w; + + map = realloc(map, i * sizeof(int)); + while (i--) map[i] = -(rand() < thresh); +} + +char alpha[] = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; +#define ALEN ((int)(sizeof(alpha) - 3)) + +void show_cluster(void) +{ + int i, j, *s = map; + + for (i = 0; i < w; i++) { + for (j = 0; j < w; j++, s++) + printf(" %c", *s < ALEN ? alpha[1 + *s] : '?'); + putchar('\n'); + } +} + +void recur(int x, int v) { + if (x >= 0 && x < ww && map[x] == -1) { + map[x] = v; + recur(x - w, v); + recur(x - 1, v); + recur(x + 1, v); + recur(x + w, v); + } +} + +int count_clusters(void) +{ + int i, cls; + + for (cls = i = 0; i < ww; i++) { + if (-1 != map[i]) continue; + recur(i, ++cls); + } + + return cls; +} + +double tests(int n, double p) +{ + int i; + double k; + + for (k = i = 0; i < n; i++) { + make_map(p); + k += (double)count_clusters() / ww; + } + return k / n; +} + +int main(void) +{ + w = 15; + make_map(.5); + printf("width=15, p=0.5, %d clusters:\n", count_clusters()); + show_cluster(); + + printf("\np=0.5, iter=5:\n"); + for (w = 1<<2; w <= 1<<14; w<<=2) + printf("%5d %9.6f\n", w, tests(5, .5)); + + free(map); + return 0; +} diff --git a/Task/Percolation-Mean-cluster-density/D/percolation-mean-cluster-density.d b/Task/Percolation-Mean-cluster-density/D/percolation-mean-cluster-density.d new file mode 100644 index 0000000000..a19a8376dd --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/D/percolation-mean-cluster-density.d @@ -0,0 +1,90 @@ +import std.stdio, std.algorithm, std.random, std.math, std.array, + std.range, std.ascii; + +alias Cell = ubyte; +alias Grid = Cell[][]; +enum Cell notClustered = 1; // Filled cell, but not in a cluster. + +Grid initialize(Grid grid, in double prob, ref Xorshift rng) nothrow { + foreach (row; grid) + foreach (ref cell; row) + cell = Cell(rng.uniform01 < prob); + return grid; +} + +void show(in Grid grid) { + immutable static cell2char = " #" ~ letters; + writeln('+', "-".replicate(grid.length), '+'); + foreach (row; grid) { + write('|'); + row.map!(c => c < cell2char.length ? cell2char[c] : '@').write; + writeln('|'); + } + writeln('+', "-".replicate(grid.length), '+'); +} + +size_t countClusters(bool justCount=false)(Grid grid) +pure nothrow @safe @nogc { + immutable side = grid.length; + static if (justCount) + enum Cell clusterID = 2; + else + Cell clusterID = 1; + + void walk(in size_t r, in size_t c) nothrow @safe @nogc { + grid[r][c] = clusterID; // Fill grid. + + if (r < side - 1 && grid[r + 1][c] == notClustered) // Down. + walk(r + 1, c); + if (c < side - 1 && grid[r][c + 1] == notClustered) // Right. + walk(r, c + 1); + if (c > 0 && grid[r][c - 1] == notClustered) // Left. + walk(r, c - 1); + if (r > 0 && grid[r - 1][c] == notClustered) // Up. + walk(r - 1, c); + } + + size_t nClusters = 0; + + foreach (immutable r; 0 .. side) + foreach (immutable c; 0 .. side) + if (grid[r][c] == notClustered) { + static if (!justCount) + clusterID++; + nClusters++; + walk(r, c); + } + return nClusters; +} + +double clusterDensity(Grid grid, in double prob, ref Xorshift rng) { + return grid.initialize(prob, rng).countClusters!true / + double(grid.length ^^ 2); +} + +void showDemo(in size_t side, in double prob, ref Xorshift rng) { + auto grid = new Grid(side, side); + grid.initialize(prob, rng); + writefln("Found %d clusters in this %d by %d grid:\n", + grid.countClusters, side, side); + grid.show; +} + +void main() { + immutable prob = 0.5; + immutable nIters = 5; + auto rng = Xorshift(unpredictableSeed); + + showDemo(15, prob, rng); + writeln; + foreach (immutable i; iota(4, 14, 2)) { + immutable side = 2 ^^ i; + auto grid = new Grid(side, side); + immutable density = nIters + .iota + .map!(_ => grid.clusterDensity(prob, rng)) + .sum / nIters; + writefln("n_iters=%3d, p=%4.2f, n=%5d, sim=%7.8f", + nIters, prob, side, density); + } +} diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-1.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-1.j new file mode 100644 index 0000000000..65b06a8179 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-1.j @@ -0,0 +1 @@ +congeal=: |.@|:@((*@[*>.)/\.)^:4^:_ diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-10.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-10.j new file mode 100644 index 0000000000..4193cdcdf3 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-10.j @@ -0,0 +1,12 @@ + 6 trials 3 +0.1111111 0.1111111 0.2222222 0.1111111 0.1111111 0.3333333 + 6 trials 10 +0.16 0.12 0.09 0.1 0.1 0.03 + 6 trials 30 +0.05666667 0.1033333 0.08222222 0.07444444 0.08333333 0.07666667 + 6 trials 100 +0.069 0.0678 0.0666 0.0677 0.0653 0.0739 + 6 trials 300 +0.06563333 0.06663333 0.06713333 0.06727778 0.06658889 0.06664444 + 6 trials 1000 +0.066079 0.066492 0.065847 0.065943 0.066318 0.065998 diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-11.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-11.j new file mode 100644 index 0000000000..c1f3e073b5 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-11.j @@ -0,0 +1,13 @@ +mean=: +/%# + mean 8 trials 3 +0.1805556 + mean 8 trials 10 +0.0875 + mean 8 trials 30 +0.07486111 + mean 8 trials 100 +0.0690625 + mean 8 trials 300 +0.06749861 + mean 8 trials 1000 +0.06616738 diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-12.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-12.j new file mode 100644 index 0000000000..f92fb4ccd3 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-12.j @@ -0,0 +1 @@ +thru=: <./ + i.@(+*)@-~ diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-13.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-13.j new file mode 100644 index 0000000000..9905c88201 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-13.j @@ -0,0 +1,16 @@ + (idclust 0.5 > 0 ?@$~ 15 15) {'.', 'A' thru&.(a.&i.) 'Z' +A.......B..C... +AAAA...D..E.F.. +A..A.G.D.D.FFF. +AA..H..DDD.FF.I +AAA...J...FFF.. +..AAAA.A.K...AA +LL.A...A..A.AAA +.L.A..AAA.AAAAA +..AA.AAA.AAA.A. +AA.AAAAAA....A. +A.AAAA.AAAA.AA. +AAA...AAA.AAAAA +..AA..A.A...AAA +.M.A.AA.AA..AA. +.MM..A.N..O..A. diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-14.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-14.j new file mode 100644 index 0000000000..c1a3b104d4 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-14.j @@ -0,0 +1,11 @@ +congeal=: |.@|:@((*@[*>.)/\.)^:4^:_ +idclust=: $ $ [: (~. i.])&.(0&,)@,@congeal ] * 1 + i.@$ + +K=: (%&#~ }.@~.)&, + +experiment=: K@ idclust@: > 0 ?@$~ ,~ +trials=: 0.5&experiment"0@# + +mean=:+/ % # + +thru=: <./ + i.@(+*)@-~ diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-2.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-2.j new file mode 100644 index 0000000000..c674dc9ded --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-2.j @@ -0,0 +1,22 @@ + M=:0.4>?6 6$0 + M +1 0 0 0 0 0 +0 0 0 1 0 0 +0 0 0 1 0 0 +1 1 0 0 0 0 +0 0 0 1 0 1 +1 1 0 1 1 0 + M*p:i.$M + 2 0 0 0 0 0 + 0 0 0 29 0 0 + 0 0 0 53 0 0 + 67 71 0 0 0 0 + 0 0 0 107 0 113 +127 131 0 139 149 0 + congeal M*p:i.$M + 2 0 0 0 0 0 + 0 0 0 53 0 0 + 0 0 0 53 0 0 + 71 71 0 0 0 0 + 0 0 0 149 0 113 +131 131 0 149 149 0 diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-3.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-3.j new file mode 100644 index 0000000000..f38775e844 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-3.j @@ -0,0 +1 @@ +idclust=: $ $ [: (~. i.])&.(0&,)@,@congeal ] * 1 + i.@$ diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-4.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-4.j new file mode 100644 index 0000000000..83cc787d28 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-4.j @@ -0,0 +1,14 @@ + idclust M +1 0 0 0 0 0 +0 0 0 2 0 0 +0 0 0 2 0 0 +3 3 0 0 0 0 +0 0 0 4 0 5 +6 6 0 4 4 0 + (idclust M) {'.ABCDEFG' +A..... +...B.. +...B.. +CC.... +...D.E +FF.DD. diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-5.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-5.j new file mode 100644 index 0000000000..1d9f00c8a6 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-5.j @@ -0,0 +1 @@ +K=: (%&#~ }.@~.)&, diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-6.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-6.j new file mode 100644 index 0000000000..d30d9cedf2 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-6.j @@ -0,0 +1,2 @@ + K idclust M +0.1666667 diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-7.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-7.j new file mode 100644 index 0000000000..0dbf6f44bc --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-7.j @@ -0,0 +1 @@ +experiment=: K@ idclust@: > 0 ?@$~ ,~ diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-8.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-8.j new file mode 100644 index 0000000000..18471c1ba5 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-8.j @@ -0,0 +1,4 @@ + 0.4 experiment 6 +0.1666667 + 0.4 experiment 6 +0.1944444 diff --git a/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-9.j b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-9.j new file mode 100644 index 0000000000..d2ba546658 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/J/percolation-mean-cluster-density-9.j @@ -0,0 +1 @@ +trials=: 0.5&experiment"0@# diff --git a/Task/Percolation-Mean-cluster-density/Python/percolation-mean-cluster-density.py b/Task/Percolation-Mean-cluster-density/Python/percolation-mean-cluster-density.py new file mode 100644 index 0000000000..03aca6bd0b --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Python/percolation-mean-cluster-density.py @@ -0,0 +1,63 @@ +from __future__ import division +from random import random +import string +from math import fsum + +n_range, p, t = (2**n2 for n2 in range(4, 14, 2)), 0.5, 5 +N = M = 15 + +NOT_CLUSTERED = 1 # filled but not clustered cell +cell2char = ' #' + string.ascii_letters + +def newgrid(n, p): + return [[int(random() < p) for x in range(n)] for y in range(n)] + +def pgrid(cell): + for n in range(N): + print( '%i) ' % (n % 10) + + ' '.join(cell2char[cell[n][m]] for m in range(M))) + + +def cluster_density(n, p): + cc = clustercount(newgrid(n, p)) + return cc / n / n + +def clustercount(cell): + walk_index = 1 + for n in range(N): + for m in range(M): + if cell[n][m] == NOT_CLUSTERED: + walk_index += 1 + walk_maze(m, n, cell, walk_index) + return walk_index - 1 + + +def walk_maze(m, n, cell, indx): + # fill cell + cell[n][m] = indx + # down + if n < N - 1 and cell[n+1][m] == NOT_CLUSTERED: + walk_maze(m, n+1, cell, indx) + # right + if m < M - 1 and cell[n][m + 1] == NOT_CLUSTERED: + walk_maze(m+1, n, cell, indx) + # left + if m and cell[n][m - 1] == NOT_CLUSTERED: + walk_maze(m-1, n, cell, indx) + # up + if n and cell[n-1][m] == NOT_CLUSTERED: + walk_maze(m, n-1, cell, indx) + + +if __name__ == '__main__': + cell = newgrid(n=N, p=0.5) + print('Found %i clusters in this %i by %i grid\n' + % (clustercount(cell), N, N)) + pgrid(cell) + print('') + + for n in n_range: + N = M = n + sim = fsum(cluster_density(n, p) for i in range(t)) / t + print('t=%3i p=%4.2f n=%5i sim=%7.5f' + % (t, p, n, sim)) diff --git a/Task/Percolation-Mean-cluster-density/README b/Task/Percolation-Mean-cluster-density/README new file mode 100644 index 0000000000..69aa537aae --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Percolation/Mean_cluster_density diff --git a/Task/Percolation-Mean-cluster-density/Racket/percolation-mean-cluster-density.rkt b/Task/Percolation-Mean-cluster-density/Racket/percolation-mean-cluster-density.rkt new file mode 100644 index 0000000000..350464c306 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Racket/percolation-mean-cluster-density.rkt @@ -0,0 +1,97 @@ +#lang racket +(require srfi/14) ; character sets + +; much faster than safe fixnum functions +(require + racket/require ; for fancy require clause below + (filtered-in + (lambda (name) (regexp-replace #rx"unsafe-" name "")) + racket/unsafe/ops) + ; these aren't in racket/unsafe/ops + (only-in racket/fixnum for/fxvector in-fxvector fxvector-copy)) + +; ...(but less safe). if in doubt use this rather than the one above +; (require racket/fixnum) + +(define t (make-parameter 5)) + +(define (build-random-grid p M N) + (define p-num (numerator p)) + (define p-den (denominator p)) + (for/fxvector #:length (fx* M N) ((_ (in-range (* M N)))) + (if (< (random p-den) p-num) 1 0))) + +(define letters + (sort (char-set->list (char-set-intersection + char-set:letter + ; char-set:ascii + )) charchar + (match-lambda + (0 #\space) (1 #\.) + (c (list-ref letters (modulo (- c 2) n-letters))))) + +(define (draw-percol-grid M N . gs) + (for ((r N)) + (for ((g gs)) + (define row-str + (list->string + (for/list ((idx (in-range (* r M) (* (+ r 1) M)))) + (cell->char (fxvector-ref g idx))))) + (printf "|~a| " row-str)) + (newline))) + +(define (count-clusters! M N g) + (define (gather-cluster! k c) + (when (fx= 1 (fxvector-ref g k)) + (define k-r (fxquotient k M)) + (define k-c (fxremainder k M)) + (fxvector-set! g k c) + (define-syntax-rule (gather-surrounds range? k+) + (let ((idx k+)) + (when (and range? (fx= 1 (fxvector-ref g idx))) + (gather-cluster! idx c)))) + (gather-surrounds (fx> k-r 0) (fx- k M)) + (gather-surrounds (fx> k-c 0) (fx- k 1)) + (gather-surrounds (fx< k-c (fx- M 1)) (fx+ k 1)) + (gather-surrounds (fx< k-r (fx- N 1)) (fx+ k M)))) + + (define-values (rv _c) + (for/fold ((rv 0) (c 2)) + ((pos (in-range (fx* M N))) + #:when (fx= 1 (fxvector-ref g pos))) + (gather-cluster! pos c) + (values (fx+ rv 1) (fx+ c 1)))) + rv) + +(define (display-sample-clustering p) + (printf "Percolation cluster sample: p=~a~%" p) + (define g (build-random-grid p 15 15)) + (define g+ (fxvector-copy g)) + (define g-count (count-clusters! 15 15 g+)) + (draw-percol-grid 15 15 g g+) + (printf "~a clusters~%" g-count)) + +(define (experiment p n t) + (printf "Experiment: ~a ~a ~a\t" p n t) (flush-output) + (define sum-Cn + (for/sum ((run (in-range t))) + (printf "[~a" run) (flush-output) + (define g (build-random-grid p n n)) + (printf "*") (flush-output) + (define Cn (count-clusters! n n g)) + (printf "]") (flush-output) + Cn)) + (printf "\tmean K(p) = ~a~%" (real->decimal-string (/ sum-Cn t (sqr n)) 6))) + +(module+ main + (t 10) + (for ((n (in-list '(4000 1000 750 500 400 300 200 100 15)))) + (experiment 1/2 n (t))) + (display-sample-clustering 1/2)) + +(module+ test + (define grd (build-random-grid 1/2 1000 1000)) + (/ (for/sum ((g (in-fxvector grd)) #:when (zero? g)) 1) (fxvector-length grd)) + (display-sample-clustering 1/2)) diff --git a/Task/Percolation-Mean-cluster-density/Tcl/percolation-mean-cluster-density.tcl b/Task/Percolation-Mean-cluster-density/Tcl/percolation-mean-cluster-density.tcl new file mode 100644 index 0000000000..317a2a619b --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Tcl/percolation-mean-cluster-density.tcl @@ -0,0 +1,55 @@ +package require Tcl 8.6 + +proc determineClusters {w h p} { + # Construct the grid + set grid [lrepeat $h [lrepeat $w 0]] + for {set i 0} {$i < $h} {incr i} { + for {set j 0} {$j < $w} {incr j} { + lset grid $i $j [expr {rand() < $p ? -1 : 0}] + } + } + # Find (and count) the clusters + set cl 0 + for {set i 0} {$i < $h} {incr i} { + for {set j 0} {$j < $w} {incr j} { + if {[lindex $grid $i $j] == -1} { + incr cl + for {set q [list $i $j];set k 0} {$k<[llength $q]} {incr k} { + set y [lindex $q $k] + set x [lindex $q [incr k]] + if {[lindex $grid $y $x] != -1} continue + lset grid $y $x $cl + foreach dx {1 0 -1 0} dy {0 1 0 -1} { + set nx [expr {$x+$dx}] + set ny [expr {$y+$dy}] + if { + $nx >= 0 && $ny >= 0 && $nx < $w && $ny < $h && + [lindex $grid $ny $nx] == -1 + } then { + lappend q $ny $nx + } + } + } + } + } + } + return [list $cl $grid] +} + +# Print a sample 15x15 grid +lassign [determineClusters 15 15 0.5] n g +puts "15x15 grid, p=0.5, with $n clusters" +puts "+[string repeat - 15]+" +foreach r $g {puts |[join [lmap x $r {format %c [expr {$x==0?32:64+$x}]}] ""]|} +puts "+[string repeat - 15]+" + +# Determine the densities as the grid size increases +puts "p=0.5, iter=5" +foreach n {5 30 180 1080 6480} { + set tot 0 + for {set i 0} {$i < 5} {incr i} { + lassign [determineClusters $n $n 0.5] nC + incr tot $nC + } + puts "n=$n, K(p)=[expr {$tot/5.0/$n**2}]" +} diff --git a/Task/Percolation-Mean-run-density/00DESCRIPTION b/Task/Percolation-Mean-run-density/00DESCRIPTION new file mode 100644 index 0000000000..04cc0d1d16 --- /dev/null +++ b/Task/Percolation-Mean-run-density/00DESCRIPTION @@ -0,0 +1,28 @@ +{{Percolation Simulation}} +Let v be a vector of n values of either 1 or 0 where the probability of any +value being 1 is p, (and 0 is therefore 1-p). +Define a run of 1's as being a group of consecutive 1's in the vector bounded +either by the limits of the vector or by a 0. Let the number of runs in a +vector of length n be R_n. + +The following vector has R_{10} = 3 +
+[1 1 0 0 0 1 0 1 1 1]
+ ^^^       ^   ^^^^^
+
+Percolation theory states that + +:K(p) = \lim_{n\to\infty} R_n / n = p(1 - p) + +;Task + +Any calculation of R_n / n for finite n is subject to randomness so should be +computed as the average of t runs, where t \ge 100. + +For values of p of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying n +on the accuracy of simulated K(p). + +Show your output here + +;See also +* [http://mathworld.wolfram.com/s-Run.html s-Run] on Wolfram mathworld. diff --git a/Task/Percolation-Mean-run-density/00META.yaml b/Task/Percolation-Mean-run-density/00META.yaml new file mode 100644 index 0000000000..a345140340 --- /dev/null +++ b/Task/Percolation-Mean-run-density/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Percolation Simulations diff --git a/Task/Percolation-Mean-run-density/C++/percolation-mean-run-density.cpp b/Task/Percolation-Mean-run-density/C++/percolation-mean-run-density.cpp new file mode 100644 index 0000000000..05f40ce815 --- /dev/null +++ b/Task/Percolation-Mean-run-density/C++/percolation-mean-run-density.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include +#include +using VecIt = std::vector::const_iterator ; + +//creates vector of length n, based on probability p for 1 +std::vector createVector( int n, double p ) { + std::vector result( n ) ; + std::random_device rd ; + std::mt19937 gen( rd( ) ) ; + std::uniform_real_distribution<> dis( 0 , 1 ) ; + for ( int i = 0 ; i < n ; i++ ) { + double number = dis( gen ) ; + if ( number <= p ) + result[ i ] = 1 ; + else + result[ i ] = 0 ; + } + return result ; +} + +//find number of 1 runs in the vector +int find_Runs( const std::vector & numberVector ) { + int runs = 0 ; + VecIt found = numberVector.begin( ) ; + while ( ( found = std::find( found , numberVector.end( ) , 1 ) ) + != numberVector.end( ) ) { + runs++ ; + while ( found != numberVector.end( ) && ( *found == 1 ) ) + std::advance( found , 1 ) ; + if ( found == numberVector.end( ) ) + break ; + } + return runs ; +} + +int main( ) { + std::cout << "t = 100\n" ; + std::vector p_values { 0.1 , 0.3 , 0.5 , 0.7 , 0.9 } ; + for ( double p : p_values ) { + std::cout << "p = " << p << " , K(p) = " << p * ( 1 - p ) << std::endl ; + for ( int n = 10 ; n < 100000 ; n *= 10 ) { + std::vector runsFound ; + for ( int i = 0 ; i < 100 ; i++ ) { + std::vector ones_and_zeroes = createVector( n , p ) ; + runsFound.push_back( find_Runs( ones_and_zeroes ) / static_cast( n ) ) ; + } + double average = std::accumulate( runsFound.begin( ) , runsFound.end( ) , 0.0 ) / runsFound.size( ) ; + std::cout << " R(" << std::setw( 6 ) << std::right << n << ", p) = " << average << std::endl ; + } + } + return 0 ; +} diff --git a/Task/Percolation-Mean-run-density/C/percolation-mean-run-density.c b/Task/Percolation-Mean-run-density/C/percolation-mean-run-density.c new file mode 100644 index 0000000000..3fd6db1c79 --- /dev/null +++ b/Task/Percolation-Mean-run-density/C/percolation-mean-run-density.c @@ -0,0 +1,36 @@ +#include +#include + +// just generate 0s and 1s without storing them +double run_test(double p, int len, int runs) +{ + int r, x, y, i, cnt = 0, thresh = p * RAND_MAX; + + for (r = 0; r < runs; r++) + for (x = 0, i = len; i--; x = y) + cnt += x < (y = rand() < thresh); + + return (double)cnt / runs / len; +} + +int main(void) +{ + double p, p1p, K; + int ip, n; + + puts( "running 1000 tests each:\n" + " p\t n\tK\tp(1-p)\t diff\n" + "-----------------------------------------------"); + for (ip = 1; ip < 10; ip += 2) { + p = ip / 10., p1p = p * (1 - p); + + for (n = 100; n <= 100000; n *= 10) { + K = run_test(p, n, 1000); + printf("%.1f\t%6d\t%.4f\t%.4f\t%+.4f (%+.2f%%)\n", + p, n, K, p1p, K - p1p, (K - p1p) / p1p * 100); + } + putchar('\n'); + } + + return 0; +} diff --git a/Task/Percolation-Mean-run-density/D/percolation-mean-run-density.d b/Task/Percolation-Mean-run-density/D/percolation-mean-run-density.d new file mode 100644 index 0000000000..32371c2d5c --- /dev/null +++ b/Task/Percolation-Mean-run-density/D/percolation-mean-run-density.d @@ -0,0 +1,23 @@ +import std.stdio, std.range, std.algorithm, std.random, std.math; + +enum n = 100, p = 0.5, t = 500; + +double meanRunDensity(in size_t n, in double prob) { + return n.iota.map!(_ => uniform01 < prob) + .array.uniq.sum / double(n); +} + +void main() { + foreach (immutable p; iota(0.1, 1.0, 0.2)) { + immutable limit = p * (1 - p); + writeln; + foreach (immutable n2; iota(10, 16, 2)) { + immutable n = 2 ^^ n2; + immutable sim = t.iota.map!(_ => meanRunDensity(n, p)) + .sum / t; + writefln("t=%3d, p=%4.2f, n=%5d, p(1-p)=%5.5f, " ~ + "sim=%5.5f, delta=%3.1f%%", t, p, n, limit, sim, + limit ? abs(sim - limit) / limit * 100 : sim*100); + } + } +} diff --git a/Task/Percolation-Mean-run-density/Fortran/percolation-mean-run-density.f b/Task/Percolation-Mean-run-density/Fortran/percolation-mean-run-density.f new file mode 100644 index 0000000000..b97ed6ca16 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Fortran/percolation-mean-run-density.f @@ -0,0 +1,59 @@ +! loosely translated from python. We do not need to generate and store the entire vector at once. +! compilation: gfortran -Wall -std=f2008 -o thisfile thisfile.f08 + +program percolation_mean_run_density + implicit none + integer :: i, p10, n2, n, t + real :: p, limit, sim, delta + data n,p,t/100,0.5,500/ + write(6,'(a3,a5,4a7)')'t','p','n','p(1-p)','sim','delta%' + do p10=1,10,2 + p = p10/10.0 + limit = p*(1-p) + write(6,'()') + do n2=10,15,2 + n = 2**n2 + sim = 0 + do i=1,t + sim = sim + mean_run_density(n,p) + end do + sim = sim/t + if (limit /= 0) then + delta = abs(sim-limit)/limit + else + delta = sim + end if + delta = delta * 100 + write(6,'(i3,f5.2,i7,2f7.3,f5.1)')t,p,n,limit,sim,delta + end do + end do + +contains + + integer function runs(n, p) + integer, intent(in) :: n + real, intent(in) :: p + real :: harvest + logical :: q + integer :: count, i + count = 0 + q = .false. + do i=1,n + call random_number(harvest) + if (harvest < p) then + q = .true. + else + if (q) count = count+1 + q = .false. + end if + end do + runs = count + end function runs + + real function mean_run_density(n, p) + integer, intent(in) :: n + real, intent(in) :: p + mean_run_density = real(runs(n,p))/real(n) + end function mean_run_density + +end program percolation_mean_run_density diff --git a/Task/Percolation-Mean-run-density/Haskell/percolation-mean-run-density.hs b/Task/Percolation-Mean-run-density/Haskell/percolation-mean-run-density.hs new file mode 100644 index 0000000000..f4ad178805 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Haskell/percolation-mean-run-density.hs @@ -0,0 +1,28 @@ +import Control.Monad.Random +import Control.Applicative +import Text.Printf +import Control.Monad +import Data.Bits + +data OneRun = OutRun | InRun deriving (Eq, Show) + +randomList :: Int -> Double -> Rand StdGen [Int] +randomList n p = take n . map f <$> getRandomRs (0,1) + where f n = if (n > p) then 0 else 1 + +countRuns xs = fromIntegral . sum $ + zipWith (\x y -> x .&. xor y 1) xs (tail xs ++ [0]) + +calcK :: Int -> Double -> Rand StdGen Double +calcK n p = (/ fromIntegral n) . countRuns <$> randomList n p + +printKs :: StdGen -> Double -> IO () +printKs g p = do + printf "p= %.1f, K(p)= %.3f\n" p (p * (1 - p)) + forM_ [1..5] $ \n -> do + let est = evalRand (calcK (10^n) p) g + printf "n=%7d, estimated K(p)= %5.3f\n" (10^n::Int) est + +main = do + x <- newStdGen + forM_ [0.1,0.3,0.5,0.7,0.9] $ printKs x diff --git a/Task/Percolation-Mean-run-density/Icon/percolation-mean-run-density.icon b/Task/Percolation-Mean-run-density/Icon/percolation-mean-run-density.icon new file mode 100644 index 0000000000..75acabf3a4 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Icon/percolation-mean-run-density.icon @@ -0,0 +1,15 @@ +procedure main(A) + t := integer(A[2]) | 500 + + write(left("p",8)," ",left("n",8)," ",left("p(1-p)",10)," ",left("SimK(p)",10)) + every (p := 0.1 | 0.3 | 0.5 | 0.7 | 0.9, n := 1000 | 2000 | 3000) do { + Ka := 0.0 + every !t do { + every (v := "", !n) do v ||:= |((?0.1 > p,"0")|"1") + R := 0 + v ? while tab(upto('1')) do R +:= (tab(many('1')), 1) + Ka +:= real(R)/n + } + write(left(p,8)," ",left(n,8)," ",left(p*(1-p),10)," ",left(Ka/t, 10)) + } +end diff --git a/Task/Percolation-Mean-run-density/J/percolation-mean-run-density.j b/Task/Percolation-Mean-run-density/J/percolation-mean-run-density.j new file mode 100644 index 0000000000..d362d23d9e --- /dev/null +++ b/Task/Percolation-Mean-run-density/J/percolation-mean-run-density.j @@ -0,0 +1,21 @@ +NB. translation of python + +NB. 'N P T' =: 100 0.5 500 NB. silliness + +newv =: (> ?@(#&0))~ NB. generate a random binary vector. Use: N newv P +runs =: {: + [: +/ 1 0&E. NB. add the tail to the sum of 1 0 occurrences Use: runs V +mean_run_density =: [ %~ [: runs newv NB. perform experiment. Use: N mean_run_density P + +main =: 3 : 0 NB.Usage: main T + T =. y + smoutput' T P N P(1-P) SIM DELTA%' + for_P. 10 %~ >: +: i. 5 do. + LIMIT =. (* -.) P + smoutput '' + for_N. 2 ^ 10 + +: i. 3 do. + SIM =. T %~ +/ (N mean_run_density P"_)^:( 100; + +printf "t= %d\n", t; +for my $p (qw(.1 .3 .5 .7 .9)) { + printf "p= %f, K(p)= %f\n", $p, $p*(1-$p); + for my $n (qw(10 100 1000)) { + my $r; $r += R($n, $p) for 1 .. t; $r /= $n; + printf " R(n, p)= %f\n", $r / t; + } +} diff --git a/Task/Percolation-Mean-run-density/Python/percolation-mean-run-density.py b/Task/Percolation-Mean-run-density/Python/percolation-mean-run-density.py new file mode 100644 index 0000000000..22a30000ca --- /dev/null +++ b/Task/Percolation-Mean-run-density/Python/percolation-mean-run-density.py @@ -0,0 +1,24 @@ +from __future__ import division +from random import random +from math import fsum + +n, p, t = 100, 0.5, 500 + +def newv(n, p): + return [int(random() < p) for i in range(n)] + +def runs(v): + return sum((a & ~b) for a, b in zip(v, v[1:] + [0])) + +def mean_run_density(n, p): + return runs(newv(n, p)) / n + +for p10 in range(1, 10, 2): + p = p10 / 10 + limit = p * (1 - p) + print('') + for n2 in range(10, 16, 2): + n = 2**n2 + sim = fsum(mean_run_density(n, p) for i in range(t)) / t + print('t=%3i p=%4.2f n=%5i p(1-p)=%5.3f sim=%5.3f delta=%3.1f%%' + % (t, p, n, limit, sim, abs(sim - limit) / limit * 100 if limit else sim * 100)) diff --git a/Task/Percolation-Mean-run-density/README b/Task/Percolation-Mean-run-density/README new file mode 100644 index 0000000000..07cacdca97 --- /dev/null +++ b/Task/Percolation-Mean-run-density/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Percolation/Mean_run_density diff --git a/Task/Percolation-Mean-run-density/Racket/percolation-mean-run-density.rkt b/Task/Percolation-Mean-run-density/Racket/percolation-mean-run-density.rkt new file mode 100644 index 0000000000..441acd4995 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Racket/percolation-mean-run-density.rkt @@ -0,0 +1,32 @@ +#lang racket +(require racket/fixnum) +(define t (make-parameter 100)) + +(define (Rn v) + (define (inner-Rn rv idx b-1) + (define b (fxvector-ref v idx)) + (define rv+ (if (and (= b 1) (= b-1 0)) (add1 rv) rv)) + (if (zero? idx) rv+ (inner-Rn rv+ (sub1 idx) b))) + (inner-Rn 0 (sub1 (fxvector-length v)) 0)) + +(define ((make-random-bit-vector p) n) + (for/fxvector + #:length n ((i n)) + (if (<= (random) p) 1 0))) + +(define (Rn/n l->p n) (/ (Rn (l->p n)) n)) + +(for ((p (in-list '(1/10 3/10 1/2 7/10 9/10)))) + (define l->p (make-random-bit-vector p)) + (define Kp (* p (- 1 p))) + (printf "p = ~a\tK(p) =\t~a\t~a~%" p Kp (real->decimal-string Kp 4)) + (for ((n (in-list '(10 100 1000 10000)))) + (define sum-Rn/n (for/sum ((i (in-range (t)))) (Rn/n l->p n))) + (define sum-Rn/n/t (/ sum-Rn/n (t))) + (printf "mean(R_~a/~a) =\t~a\t~a~%" + n n sum-Rn/n/t (real->decimal-string sum-Rn/n/t 4))) + (newline)) + +(module+ test + (require rackunit) + (check-eq? (Rn (fxvector 1 1 0 0 0 1 0 1 1 1)) 3)) diff --git a/Task/Percolation-Mean-run-density/Tcl/percolation-mean-run-density.tcl b/Task/Percolation-Mean-run-density/Tcl/percolation-mean-run-density.tcl new file mode 100644 index 0000000000..4ba540c310 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Tcl/percolation-mean-run-density.tcl @@ -0,0 +1,33 @@ +proc randomString {length probability} { + for {set s ""} {[string length $s] < $length} {} { + append s [expr {rand() < $probability}] + } + return $s +} + +# By default, [regexp -all] gives the number of times that the RE matches +proc runs {str} { + regexp -all {1+} $str +} + +# Compute the mean run density +proc mrd {t p n} { + for {set i 0;set total 0.0} {$i < $t} {incr i} { + set run [randomString $n $p] + set total [expr {$total + double([runs $run])/$n}] + } + return [expr {$total / $t}] +} + +# Parameter sweep with nested [foreach] +set runs 500 +foreach p {0.10 0.30 0.50 0.70 0.90} { + foreach n {1024 4096 16384} { + set theory [expr {$p * (1 - $p)}] + set sim [mrd $runs $p $n] + set diffpc [expr {abs($theory-$sim)*100/$theory}] + puts [format "t=%d, p=%.2f, n=%5d, p(1-p)=%.3f, sim=%.3f, delta=%.2f%%" \ + $runs $p $n $theory $sim $diffpc] + } + puts "" +} diff --git a/Task/Percolation-Site-percolation/00DESCRIPTION b/Task/Percolation-Site-percolation/00DESCRIPTION new file mode 100644 index 0000000000..8fc90e54a7 --- /dev/null +++ b/Task/Percolation-Site-percolation/00DESCRIPTION @@ -0,0 +1,19 @@ +{{Percolation Simulation}} +Given an M \times N rectangular array of cells numbered \mathrm{cell}[0..M-1, 0..N-1]assume M is horizontal and N is downwards. + +Assume that the probability of any cell being filled is a constant p where +: 0.0 \le p \le 1.0 + +;The task: +Simulate creating the array of cells with probability p and then +testing if there is a route through adjacent filled cells from any on row 0 to any on row N, i.e. testing for site percolation. + +Given p repeat the percolation t times to estimate the proportion of times that the fluid can percolate to the bottom for any given p. + +Show how the probability of percolating through the random grid changes with p going from 0.0 to 1.0 in 0.1 increments and with the number of repetitions to estimate the fraction at any given p as t >= 100. + +Use an M=15, N=15 grid of cells for all cases. + +Optionally depict a percolation through a cell grid graphically. + +Show all output on this page. diff --git a/Task/Percolation-Site-percolation/00META.yaml b/Task/Percolation-Site-percolation/00META.yaml new file mode 100644 index 0000000000..a345140340 --- /dev/null +++ b/Task/Percolation-Site-percolation/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Percolation Simulations diff --git a/Task/Percolation-Site-percolation/C/percolation-site-percolation-1.c b/Task/Percolation-Site-percolation/C/percolation-site-percolation-1.c new file mode 100644 index 0000000000..07337283f0 --- /dev/null +++ b/Task/Percolation-Site-percolation/C/percolation-site-percolation-1.c @@ -0,0 +1,65 @@ +#include +#include +#include + +char *cell, *start, *end; +int m, n; + +void make_grid(int x, int y, double p) +{ + int i, j, thresh = p * RAND_MAX; + + m = x, n = y; + end = start = realloc(start, (x+1) * (y+1) + 1); + + memset(start, 0, m + 1); + + cell = end = start + m + 1; + for (i = 0; i < n; i++) { + for (j = 0; j < m; j++) + *end++ = rand() < thresh ? '+' : '.'; + *end++ = '\n'; + } + + end[-1] = 0; + end -= ++m; // end is the first cell of bottom row +} + +int ff(char *p) // flood fill +{ + if (*p != '+') return 0; + + *p = '#'; + return p >= end || ff(p+m) || ff(p+1) || ff(p-1) || ff(p-m); +} + +int percolate(void) +{ + int i; + for (i = 0; i < m && !ff(cell + i); i++); + return i < m; +} + +int main(void) +{ + make_grid(15, 15, .5); + percolate(); + + puts("15x15 grid:"); + puts(cell); + + puts("\nrunning 10,000 tests for each case:"); + + double p; + int ip, i, cnt; + for (ip = 0; ip <= 10; ip++) { + p = ip / 10.; + for (cnt = i = 0; i < 10000; i++) { + make_grid(15, 15, p); + cnt += percolate(); + } + printf("p=%.1f: %.4f\n", p, cnt / 10000.); + } + + return 0; +} diff --git a/Task/Percolation-Site-percolation/C/percolation-site-percolation-2.c b/Task/Percolation-Site-percolation/C/percolation-site-percolation-2.c new file mode 100644 index 0000000000..9c16962e33 --- /dev/null +++ b/Task/Percolation-Site-percolation/C/percolation-site-percolation-2.c @@ -0,0 +1,118 @@ +#include +#include +#include +#include +#include + +#define N_COLS 15 +#define N_ROWS 15 + +// Probability granularity 0.0, 0.1, ... 1.0 +#define N_STEPS 11 + +// Simulation tries +#define N_TRIES 100 + +typedef unsigned char Cell; +enum { EMPTY_CELL = ' ', + FILLED_CELL = '#', + VISITED_CELL = '.' }; +typedef Cell Grid[N_ROWS][N_COLS]; + +void initialize(Grid grid, const double probability) { + for (size_t r = 0; r < N_ROWS; r++) + for (size_t c = 0; c < N_COLS; c++) { + const double rnd = rand() / (double)RAND_MAX; + grid[r][c] = (rnd < probability) ? EMPTY_CELL : FILLED_CELL; + } +} + +void show(Grid grid) { + char line[N_COLS + 3]; + memset(&line[0], '-', N_COLS + 2); + line[0] = '+'; + line[N_COLS + 1] = '+'; + line[N_COLS + 2] = '\0'; + + printf("%s\n", line); + for (size_t r = 0; r < N_ROWS; r++) { + putchar('|'); + for (size_t c = 0; c < N_COLS; c++) + putchar(grid[r][c]); + puts("|"); + } + printf("%s\n", line); +} + +bool walk(Grid grid, const size_t r, const size_t c) { + const size_t bottom = N_ROWS - 1; + grid[r][c] = VISITED_CELL; + + if (r < bottom && grid[r + 1][c] == EMPTY_CELL) { // Down. + if (walk(grid, r + 1, c)) + return true; + } else if (r == bottom) + return true; + + if (c && grid[r][c - 1] == EMPTY_CELL) // Left. + if (walk(grid, r, c - 1)) + return true; + + if (c < N_COLS - 1 && grid[r][c + 1] == EMPTY_CELL) // Right. + if (walk(grid, r, c + 1)) + return true; + + if (r && grid[r - 1][c] == EMPTY_CELL) // Up. + if (walk(grid, r - 1, c)) + return true; + + return false; +} + +bool percolate(Grid grid) { + const size_t startR = 0; + for (size_t c = 0; c < N_COLS; c++) + if (grid[startR][c] == EMPTY_CELL) + if (walk(grid, startR, c)) + return true; + return false; +} + +typedef struct { + double prob; + size_t count; +} Counter; + +int main() { + const double probability_step = 1.0 / (N_STEPS - 1); + Counter counters[N_STEPS]; + for (size_t i = 0; i < N_STEPS; i++) + counters[i] = (Counter){ i * probability_step, 0 }; + + bool sample_shown = false; + static Grid grid; + srand(time(NULL)); + + for (size_t i = 0; i < N_STEPS; i++) { + for (size_t t = 0; t < N_TRIES; t++) { + initialize(grid, counters[i].prob); + if (percolate(grid)) { + counters[i].count++; + if (!sample_shown) { + printf("Percolating sample (%dx%d," + " probability =%5.2f):\n", + N_COLS, N_ROWS, counters[i].prob); + show(grid); + sample_shown = true; + } + } + } + } + + printf("\nFraction of %d tries that percolate through:\n", N_TRIES); + for (size_t i = 0; i < N_STEPS; i++) + printf("%1.1f %1.3f\n", counters[i].prob, + counters[i].count / (double)N_TRIES); + + return 0; +} diff --git a/Task/Percolation-Site-percolation/D/percolation-site-percolation.d b/Task/Percolation-Site-percolation/D/percolation-site-percolation.d new file mode 100644 index 0000000000..143ba834f0 --- /dev/null +++ b/Task/Percolation-Site-percolation/D/percolation-site-percolation.d @@ -0,0 +1,95 @@ +import std.stdio, std.random, std.array, std.datetime; + +enum size_t nCols = 15, + nRows = 15, + nSteps = 11, // Probability granularity. + nTries = 20_000; // Simulation tries. + +enum Cell : char { empty = ' ', filled = '#', visited = '.' } +alias Grid = Cell[nCols][nRows]; + +void initialize(ref Grid grid, in double probability, ref Xorshift rng) { + foreach (ref row; grid) + foreach (ref cell; row) + cell = (rng.uniform01 < probability) ? Cell.empty : Cell.filled; +} + +void show(in ref Grid grid) @safe { + writefln("%(|%(%c%)|\n%)|", grid); +} + +bool percolate(ref Grid grid) pure nothrow @safe @nogc { + bool walk(in size_t r, in size_t c) nothrow @safe @nogc { + enum bottom = nRows - 1; + grid[r][c] = Cell.visited; + + if (r < bottom && grid[r + 1][c] == Cell.empty) { // Down. + if (walk(r + 1, c)) + return true; + } else if (r == bottom) + return true; + + if (c && grid[r][c - 1] == Cell.empty) // Left. + if (walk(r, c - 1)) + return true; + + if (c < nCols - 1 && grid[r][c + 1] == Cell.empty) // Right. + if (walk(r, c + 1)) + return true; + + if (r && grid[r - 1][c] == Cell.empty) // Up. + if (walk(r - 1, c)) + return true; + + return false; + } + + enum startR = 0; + foreach (immutable c; 0 .. nCols) + if (grid[startR][c] == Cell.empty) + if (walk(startR, c)) + return true; + return false; +} + +void main() { + static struct Counter { + double prob; + size_t count; + } + + StopWatch sw; + sw.start; + + enum probabilityStep = 1.0 / (nSteps - 1); + Counter[nSteps] counters; + foreach (immutable i, ref co; counters) + co.prob = i * probabilityStep; + + Grid grid; + bool sampleShown = false; + auto rng = Xorshift(unpredictableSeed); + + foreach (ref co; counters) { + foreach (immutable _; 0 .. nTries) { + grid.initialize(co.prob, rng); + if (grid.percolate) { + co.count++; + if (!sampleShown) { + writefln("Percolating sample (%dx%d, probability =%5.2f):", + nCols, nRows, co.prob); + grid.show; + sampleShown = true; + } + } + } + } + sw.stop; + + writefln("\nFraction of %d tries that percolate through:", nTries); + foreach (const co; counters) + writefln("%1.3f %1.3f", co.prob, co.count / double(nTries)); + + writefln("\nSimulations and grid printing performed" ~ + " in %3.2f seconds.", sw.peek.msecs / 1000.0); +} diff --git a/Task/Percolation-Site-percolation/Fortran/percolation-site-percolation.f b/Task/Percolation-Site-percolation/Fortran/percolation-site-percolation.f new file mode 100644 index 0000000000..5be74f5aa8 --- /dev/null +++ b/Task/Percolation-Site-percolation/Fortran/percolation-site-percolation.f @@ -0,0 +1,123 @@ +! loosely translated from python. +! compilation: gfortran -Wall -std=f2008 thisfile.f08 + +!$ a=site && gfortran -o $a -g -O0 -Wall -std=f2008 $a.f08 && $a +!100 trials per +!Fill Fraction goal(%) simulated through paths(%) +! 0 0 +! 10 0 +! 20 0 +! 30 0 +! 40 0 +! 50 6 +! +! +! b b b b h j m m m +! b b b b b h h m m m m m +! b b b h h h m +! b h h h h h h h +! b b h h h h h h h h h +! b b b h h h h h h h h h h +! b b @ h h h h h h h +! @ @ h h h h h h h h +! @ @ @ @ h h h h +! @ @ @ @ h h h h h h +! @ @ @ h h h h h h h +! @ @ @ h h h h h h +! @ h h h h h h +! @ h h h h h h h +! @ @ h h h h h h h h h h +! 60 59 +! 70 97 +! 80 100 +! 90 100 +! 100 100 + +program percolation_site + implicit none + integer, parameter :: m=15,n=15,t=100 + !integer, parameter :: m=2,n=2,t=8 + integer(kind=1), dimension(m, n) :: grid + real :: p + integer :: i, ip, trial, successes + logical :: success, unseen, q + data unseen/.true./ + write(6,'(i3,a11)') t,' trials per' + write(6,'(a21,a30)') 'Fill Fraction goal(%)','simulated through paths(%)' + do ip=0, 10 + p = ip/10.0 + successes = 0 + do trial = 1, t + call newgrid(grid, p) + success = .false. + do i=1, m + q = walk(grid, i) ! deliberately compute all paths + success = success .or. q + end do + if ((ip == 6) .and. unseen) then + call display(grid) + unseen = .false. + end if + successes = successes + merge(1, 0, success) + end do + write(6,'(9x,i3,24x,i3)')ip*10,nint(100*real(successes)/real(t)) + end do + +contains + + logical function walk(grid, start) + integer(kind=1), dimension(m,n), intent(inout) :: grid + integer, intent(in) :: start + walk = rwalk(grid, 1, start, int(start+1,1)) + end function walk + + recursive function rwalk(grid, i, j, k) result(through) + logical :: through + integer(kind=1), dimension(m,n), intent(inout) :: grid + integer, intent(in) :: i, j + integer(kind=1), intent(in) :: k + logical, dimension(4) :: q + !out of bounds + through = .false. + if (i < 1) return + if (m < i) return + if (j < 1) return + if (n < j) return + !visited or non-pore + if (1_1 /= grid(i, j)) return + !update grid and recurse with neighbors. deny 'shortcircuit' evaluation + grid(i, j) = k + q(1) = rwalk(grid,i+0,j+1,k) + q(2) = rwalk(grid,i+0,j-1,k) + q(3) = rwalk(grid,i+1,j+0,k) + q(4) = rwalk(grid,i-1,j+0,k) + !newly discovered outlet + through = (i == m) .or. any(q) + end function rwalk + + subroutine newgrid(grid, probability) + implicit none + real :: probability + integer(kind=1), dimension(m,n), intent(out) :: grid + real, dimension(m,n) :: harvest + call random_number(harvest) + grid = merge(1_1, 0_1, harvest < probability) + end subroutine newgrid + + subroutine display(grid) + integer(kind=1), dimension(m,n), intent(in) :: grid + integer :: i, j, k, L + character(len=n*2) :: lineout + write(6,'(/)') + lineout = ' ' + do i=1,m + do j=1,n + k = j+j + L = grid(i,j)+1 + lineout(k:k) = ' @abcdefghijklmnopqrstuvwxyz'(L:L) + end do + write(6,*) lineout + end do + end subroutine display + +end program percolation_site diff --git a/Task/Percolation-Site-percolation/Go/percolation-site-percolation.go b/Task/Percolation-Site-percolation/Go/percolation-site-percolation.go new file mode 100644 index 0000000000..0d536e301a --- /dev/null +++ b/Task/Percolation-Site-percolation/Go/percolation-site-percolation.go @@ -0,0 +1,114 @@ +package main + +import ( + "bytes" + "fmt" + "math/rand" + "time" +) + +func main() { + const ( + m, n = 15, 15 + t = 1e4 + minp, maxp, Δp = 0, 1, 0.1 + ) + + rand.Seed(2) // Fixed seed for repeatable example grid + g := NewGrid(.5, m, n) + g.Percolate() + fmt.Println(g) + + rand.Seed(time.Now().UnixNano()) // could pick a better seed + for p := float64(minp); p < maxp; p += Δp { + count := 0 + for i := 0; i < t; i++ { + g := NewGrid(p, m, n) + if g.Percolate() { + count++ + } + } + fmt.Printf("p=%.2f, %.4f\n", p, float64(count)/t) + } +} + +const ( + full = '.' + used = '#' + empty = ' ' +) + +type grid struct { + cell [][]byte // row first, i.e. [y][x] +} + +func NewGrid(p float64, xsize, ysize int) *grid { + g := &grid{cell: make([][]byte, ysize)} + for y := range g.cell { + g.cell[y] = make([]byte, xsize) + for x := range g.cell[y] { + if rand.Float64() < p { + g.cell[y][x] = full + } else { + g.cell[y][x] = empty + } + } + } + return g +} + +func (g *grid) String() string { + var buf bytes.Buffer + // Don't really need to call Grow but it helps avoid multiple + // reallocations if the size is large. + buf.Grow((len(g.cell) + 2) * (len(g.cell[0]) + 3)) + + buf.WriteByte('+') + for _ = range g.cell[0] { + buf.WriteByte('-') + } + buf.WriteString("+\n") + + for y := range g.cell { + buf.WriteByte('|') + buf.Write(g.cell[y]) + buf.WriteString("|\n") + } + + buf.WriteByte('+') + ly := len(g.cell) - 1 + for x := range g.cell[ly] { + if g.cell[ly][x] == used { + buf.WriteByte(used) + } else { + buf.WriteByte('-') + } + } + buf.WriteByte('+') + return buf.String() +} + +func (g *grid) Percolate() bool { + for x := range g.cell[0] { + if g.use(x, 0) { + return true + } + } + return false +} + +func (g *grid) use(x, y int) bool { + if y < 0 || x < 0 || x >= len(g.cell[0]) || g.cell[y][x] != full { + return false // Off the edges, empty, or used + } + g.cell[y][x] = used + if y+1 == len(g.cell) { + return true // We're on the bottom + } + + // Try down, right, left, up in that order. + return g.use(x, y+1) || + g.use(x+1, y) || + g.use(x-1, y) || + g.use(x, y-1) +} diff --git a/Task/Percolation-Site-percolation/J/percolation-site-percolation.j b/Task/Percolation-Site-percolation/J/percolation-site-percolation.j new file mode 100644 index 0000000000..b48a21177e --- /dev/null +++ b/Task/Percolation-Site-percolation/J/percolation-site-percolation.j @@ -0,0 +1,42 @@ +any =: +./ +all =: *./ + +quickCheck =: [: all [: (any"1) 2 *./\ ] NB. a complete path requires connections between all row pairs + +percolate =: 15 15&$: : (dyad define) NB. returns 0 iff blocked Use: (N, M) percolate P + NB. make a binary grid + GRID =: y (> ?@($&0)) x + + NB. compute the return value + if. -. quickCheck GRID do. 0 return. end. + STARTING_SITES =. 0 ,. ({. GRID) # i. {: x NB. indexes of 1 in head row of GRID + any STARTING_SITES check GRID +) + + +NB. use local copy of GRID. Too slow. +check =: dyad define"1 2 NB. return 1 iff through path found use: START check GRID + GRID =. y + LOCATION =. x + if. 0 (= #) LOCATION do. 0 return. end. NB. no starting point? 0 + if. LOCATION any@:((>: , 0 > [) $) GRID do. 0 return. end. NB. off grid? 0 + INDEX =. : {. LOCATION) = (# GRID) do. 1 return. end. NB. Success! (display GRID here) + G =: GRID =. INDEX (>:@:{)`[`]}GRID + any GRID check~ LOCATION +"1 (, -)0 1,:1 0 +) + +NB. use global GRID. +check =: dyad define"1 2 NB. return 1 iff through path found use: START check GRID + LOCATION =. x + if. 0 (= #) LOCATION do. 0 return. end. NB. no starting point? 0 + if. LOCATION any@:((>: , 0 > [) $) GRID do. 0 return. end. NB. off grid? 0 + INDEX =. : {. LOCATION) = (# GRID) do. 1 return. end. NB. Success! (display GRID here) + GRID =: INDEX (>:@:{)`[`]}GRID + any GRID check~ LOCATION +"1 (, -)0 1,:1 0 +) + +simulate =: 100&$: : ([ %~ [: +/ [: percolate"0 #) NB. return fraction of connected cases. Use: T simulate P diff --git a/Task/Percolation-Site-percolation/Python/percolation-site-percolation.py b/Task/Percolation-Site-percolation/Python/percolation-site-percolation.py new file mode 100644 index 0000000000..f575719e59 --- /dev/null +++ b/Task/Percolation-Site-percolation/Python/percolation-site-percolation.py @@ -0,0 +1,71 @@ +from random import random +import string +from pprint import pprint as pp + +M, N, t = 15, 15, 100 + +cell2char = ' #' + string.ascii_letters +NOT_VISITED = 1 # filled cell not walked + +class PercolatedException(Exception): pass + +def newgrid(p): + return [[int(random() < p) for m in range(M)] for n in range(N)] # cell + +def pgrid(cell, percolated=None): + for n in range(N): + print( '%i) ' % (n % 10) + + ' '.join(cell2char[cell[n][m]] for m in range(M))) + if percolated: + where = percolated.args[0][0] + print('!) ' + ' ' * where + cell2char[cell[n][where]]) + +def check_from_top(cell): + n, walk_index = 0, 1 + try: + for m in range(M): + if cell[n][m] == NOT_VISITED: + walk_index += 1 + walk_maze(m, n, cell, walk_index) + except PercolatedException as ex: + return ex + return None + + +def walk_maze(m, n, cell, indx): + # fill cell + cell[n][m] = indx + # down + if n < N - 1 and cell[n+1][m] == NOT_VISITED: + walk_maze(m, n+1, cell, indx) + # THE bottom + elif n == N - 1: + raise PercolatedException((m, indx)) + # left + if m and cell[n][m - 1] == NOT_VISITED: + walk_maze(m-1, n, cell, indx) + # right + if m < M - 1 and cell[n][m + 1] == NOT_VISITED: + walk_maze(m+1, n, cell, indx) + # up + if n and cell[n-1][m] == NOT_VISITED: + walk_maze(m, n-1, cell, indx) + +if __name__ == '__main__': + sample_printed = False + pcount = {} + for p10 in range(11): + p = p10 / 10.0 + pcount[p] = 0 + for tries in range(t): + cell = newgrid(p) + percolated = check_from_top(cell) + if percolated: + pcount[p] += 1 + if not sample_printed: + print('\nSample percolating %i x %i, p = %5.2f grid\n' % (M, N, p)) + pgrid(cell, percolated) + sample_printed = True + print('\n p: Fraction of %i tries that percolate through\n' % t ) + + pp({p:c/float(t) for p, c in pcount.items()}) diff --git a/Task/Percolation-Site-percolation/README b/Task/Percolation-Site-percolation/README new file mode 100644 index 0000000000..d0e49acb7f --- /dev/null +++ b/Task/Percolation-Site-percolation/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Percolation/Site_percolation diff --git a/Task/Percolation-Site-percolation/Racket/percolation-site-percolation.rkt b/Task/Percolation-Site-percolation/Racket/percolation-site-percolation.rkt new file mode 100644 index 0000000000..480c1e3b51 --- /dev/null +++ b/Task/Percolation-Site-percolation/Racket/percolation-site-percolation.rkt @@ -0,0 +1,81 @@ +#lang racket +(require racket/require (only-in racket/fixnum for*/fxvector)) +(require (filtered-in (lambda (name) (regexp-replace #rx"unsafe-" name "")) + racket/unsafe/ops)) + +(define cell-empty 0) +(define cell-filled 1) +(define cell-wall 2) +(define cell-visited 3) +(define cell-exit 4) + +(define ((percol->generator p)) (if (< (random) p) cell-filled cell-empty)) + +(define t (make-parameter 1000)) + +(define ((make-percol-grid M N) p) + (define p->10 (percol->generator p)) + (define M+1 (fx+ 1 M)) + (define M+2 (fx+ 2 M)) + (for*/fxvector + #:length (fx* N M+2) + ((n (in-range N)) (m (in-range M+2))) + (cond + [(fx= 0 m) cell-wall] + [(fx= m M+1) cell-wall] + [else (p->10)]))) + +(define (cell->str c) (substring " #|+*" c (fx+ 1 c))) + +(define ((draw-percol-grid M N) g) + (define M+2 (fx+ M 2)) + (for ((row N)) + (for ((col (in-range M+2))) + (define idx (fx+ (fx* M+2 row) col)) + (printf "~a" (cell->str (fxvector-ref g idx)))) + (newline))) + +(define ((percolate-percol-grid?! M N) g) + (define M+2 (fx+ M 2)) + (define N-1 (fx- N 1)) + (define max-idx (fx* N M+2)) + (define (inner-percolate g idx) + (define row (fxquotient idx M+2)) + (cond + ((fx< idx 0) #f) + ((fx>= idx max-idx) #f) + ((fx= N-1 row) (fxvector-set! g idx cell-exit) #t) + ((fx= cell-filled (fxvector-ref g idx)) + (fxvector-set! g idx cell-visited) + (or + ; gravity first (thanks Mr Newton) + (inner-percolate g (fx+ idx M+2)) + ; stick-to-the-left + (inner-percolate g (fx- idx 1)) + (inner-percolate g (fx+ idx 1)) + ; go uphill only if we have to! + (inner-percolate g (fx- idx M+2)))) + (else #f))) + (for/first ((m (in-range 1 M+2)) #:when (inner-percolate g m)) g)) + +(define make-15x15-grid (make-percol-grid 15 15)) +(define draw-15x15-grid (draw-percol-grid 15 15)) +(define perc-15x15-grid?! (percolate-percol-grid?! 15 15)) + +(define (display-sample-percolation p) + (printf "Percolation sample: p=~a~%" p) + (for*/first + ((i (in-naturals)) + (g (in-value (make-15x15-grid 0.6))) + #:when (perc-15x15-grid?! g)) + (draw-15x15-grid g)) + (newline)) + +(display-sample-percolation 0.4) + +(for ((p (sequence-map (curry * 1/10) (in-range 0 (add1 10))))) + (define n-percolated-grids + (for/sum + ((i (in-range (t))) #:when (perc-15x15-grid?! (make-15x15-grid p))) 1)) + (define proportion-percolated (/ n-percolated-grids (t))) + (printf "p=~a\t->\t~a~%" p (real->decimal-string proportion-percolated 4))) diff --git a/Task/Percolation-Site-percolation/Tcl/percolation-site-percolation.tcl b/Task/Percolation-Site-percolation/Tcl/percolation-site-percolation.tcl new file mode 100644 index 0000000000..f6a28b7d66 --- /dev/null +++ b/Task/Percolation-Site-percolation/Tcl/percolation-site-percolation.tcl @@ -0,0 +1,77 @@ +package require Tcl 8.6 + +oo::class create SitePercolation { + variable cells w h + constructor {width height probability} { + set w $width + set h $height + for {set cells {}} {[llength $cells] < $h} {lappend cells $row} { + for {set row {}} {[llength $row] < $w} {lappend row $cell} { + set cell [expr {rand() < $probability}] + } + } + } + method print {out} { + array set map {0 "#" 1 " " -1 .} + puts "+[string repeat . $w]+" + foreach row $cells { + set s "|" + foreach cell $row { + append s $map($cell) + } + puts [append s "|"] + } + set outline [lrepeat $w "-"] + foreach index $out { + lset outline $index "." + } + puts "+[join $outline {}]+" + } + method percolate {} { + for {set work {}; set i 0} {$i < $w} {incr i} { + if {[lindex $cells 0 $i]} {lappend work 0 $i} + } + try { + my Fill $work + return {} + } trap PERCOLATED x { + return [list $x] + } + } + method Fill {queue} { + while {[llength $queue]} { + set queue [lassign $queue y x] + if {$y >= $h} {throw PERCOLATED $x} + if {$y < 0 || $x < 0 || $x >= $w} continue + if {[lindex $cells $y $x]<1} continue + lset cells $y $x -1 + lappend queue [expr {$y+1}] $x [expr {$y-1}] $x + lappend queue $y [expr {$x-1}] $y [expr {$x+1}] + } + } +} + +# Demonstrate one run +puts "Sample percolation, 15x15 p=0.6" +SitePercolation create bp 15 15 0.6 +bp print [bp percolate] +bp destroy +puts "" + +# Collect statistics +apply {{} { + puts "Percentage of tries that percolate, varying p" + set tries 100 + for {set pint 0} {$pint <= 10} {incr pint} { + set p [expr {$pint * 0.1}] + set tot 0 + for {set i 0} {$i < $tries} {incr i} { + set bp [SitePercolation new 15 15 $p] + if {[$bp percolate] ne ""} { + incr tot + } + $bp destroy + } + puts [format "p=%.2f: %2.1f%%" $p [expr {$tot*100./$tries}]] + } +}} diff --git a/Task/Permutations-Rank-of-a-permutation/00DESCRIPTION b/Task/Permutations-Rank-of-a-permutation/00DESCRIPTION new file mode 100644 index 0000000000..c39a7b1647 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/00DESCRIPTION @@ -0,0 +1,48 @@ +A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. +For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1). + +For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: + +
  PERMUTATION      RANK
+  (0, 1, 2, 3) ->  0
+  (0, 1, 3, 2) ->  1
+  (0, 2, 1, 3) ->  2
+  (0, 2, 3, 1) ->  3
+  (0, 3, 1, 2) ->  4
+  (0, 3, 2, 1) ->  5
+  (1, 0, 2, 3) ->  6
+  (1, 0, 3, 2) ->  7
+  (1, 2, 0, 3) ->  8
+  (1, 2, 3, 0) ->  9
+  (1, 3, 0, 2) -> 10
+  (1, 3, 2, 0) -> 11
+  (2, 0, 1, 3) -> 12
+  (2, 0, 3, 1) -> 13
+  (2, 1, 0, 3) -> 14
+  (2, 1, 3, 0) -> 15
+  (2, 3, 0, 1) -> 16
+  (2, 3, 1, 0) -> 17
+  (3, 0, 1, 2) -> 18
+  (3, 0, 2, 1) -> 19
+  (3, 1, 0, 2) -> 20
+  (3, 1, 2, 0) -> 21
+  (3, 2, 0, 1) -> 22
+  (3, 2, 1, 0) -> 23
+ +Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). + +One use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. + +A [http://stackoverflow.com/questions/12884428/generate-sample-of-1-000-000-random-permutations question on the Stack Overflow site] asked how to generate one million random and indivudual permutations of 144 items. +;This task is to: +# Create a function to generate a permutation from a rank. +# Create the inverse function that given the permutation generates its rank. +# Show that for n=3 the two functions are indeed inverses of each other. +# Compute and show here 4 random, individual, samples of permutations of 12 objects. +;Stretch goal: +* State how reasonable it would be to use your program to address the limits of the Stack Overflow question. + +;References: +# [http://webhome.cs.uvic.ca/~ruskey/Publications/RankPerm/RankPerm.html Ranking and Unranking Permutations in Linear Time] by Myrvold & Ruskey. (Also available via Google [https://docs.google.com/viewer?a=v&q=cache:t8G2xQ3-wlkJ:citeseerx.ist.psu.edu/viewdoc/download%3Fdoi%3D10.1.1.43.4521%26rep%3Drep1%26type%3Dpdf+&hl=en&gl=uk&pid=bl&srcid=ADGEESgDcCc4JVd_57ziRRFlhDFxpPxoy88eABf9UG_TLXMzfxiC8D__qx4xfY3JAhw_nuPDrZ9gSInX0MbpYjgh807ZfoNtLrl40wdNElw2JMdi94Znv1diM-XYo53D8uelCXnK053L&sig=AHIEtbQtx-sxcVzaZgy9uhniOmETuW4xKg here]). +# [http://www.davdata.nl/math/ranks.html Ranks] on the DevData site. +# [http://stackoverflow.com/a/1506337/10562 Another answer] on Stack Overflow to a different question that explains its algorithm in detail. diff --git a/Task/Permutations-Rank-of-a-permutation/C/permutations-rank-of-a-permutation.c b/Task/Permutations-Rank-of-a-permutation/C/permutations-rank-of-a-permutation.c new file mode 100644 index 0000000000..6545411dab --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/C/permutations-rank-of-a-permutation.c @@ -0,0 +1,68 @@ +#include +#include + +#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) + +void _mr_unrank1(int rank, int n, int *vec) { + int t, q, r; + if (n < 1) return; + + q = rank / n; + r = rank % n; + SWAP(vec[r], vec[n-1]); + _mr_unrank1(q, n-1, vec); +} + +int _mr_rank1(int n, int *vec, int *inv) { + int s, t; + if (n < 2) return 0; + + s = vec[n-1]; + SWAP(vec[n-1], vec[inv[n-1]]); + SWAP(inv[s], inv[n-1]); + return s + n * _mr_rank1(n-1, vec, inv); +} + +/* Fill the integer array (of size ) with the + * permutation at rank . + */ +void get_permutation(int rank, int n, int *vec) { + int i; + for (i = 0; i < n; ++i) vec[i] = i; + _mr_unrank1(rank, n, vec); +} + +/* Return the rank of the current permutation of array + * (of size ). + */ +int get_rank(int n, int *vec) { + int i, r, *v, *inv; + + v = malloc(n * sizeof(int)); + inv = malloc(n * sizeof(int)); + + for (i = 0; i < n; ++i) { + v[i] = vec[i]; + inv[vec[i]] = i; + } + r = _mr_rank1(n, v, inv); + free(inv); + free(v); + return r; +} + +int main(int argc, char *argv[]) { + int i, r, tv[4]; + + for (r = 0; r < 24; ++r) { + printf("%3d: ", r); + get_permutation(r, 4, tv); + + for (i = 0; i < 4; ++i) { + if (0 == i) printf("[ "); + else printf(", "); + printf("%d", tv[i]); + } + printf(" ] = %d\n", get_rank(4, tv)); + } +} diff --git a/Task/Permutations-Rank-of-a-permutation/D/permutations-rank-of-a-permutation.d b/Task/Permutations-Rank-of-a-permutation/D/permutations-rank-of-a-permutation.d new file mode 100644 index 0000000000..f573513ee8 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/D/permutations-rank-of-a-permutation.d @@ -0,0 +1,63 @@ +import std.stdio, std.algorithm, std.range; + +alias TRank = ulong; + +TRank factorial(in uint n) pure nothrow { + TRank result = 1; + foreach (immutable i; 2 .. n + 1) + result *= i; + return result; +} + +/// Fill the integer array with the permutation at rank . +void computePermutation(size_t N)(ref uint[N] vec, TRank rank) +pure nothrow if (N > 0 && N < 22) { + N.iota.copy(vec[]); + + foreach_reverse (immutable n; 1 .. N + 1) { + immutable size_t r = rank % n; + rank /= n; + swap(vec[r], vec[n - 1]); + } +} + +/// Return the rank of the current permutation. +TRank computeRank(size_t N)(in ref uint[N] vec) pure nothrow +if (N > 0 && N < 22) { + uint[N] vec2, inv = void; + + TRank mrRank1(in uint n) nothrow { + if (n < 2) + return 0; + + immutable s = vec2[n - 1]; + swap(vec2[n - 1], vec2[inv[n - 1]]); + swap(inv[s], inv[n - 1]); + return s + n * mrRank1(n - 1); + } + + vec2[] = vec[]; + foreach (immutable i; 0 .. N) + inv[vec[i]] = i; + return mrRank1(N); +} + +void main() { + import std.random; + + uint[4] items1 = void; + immutable rMax1 = items1.length.factorial; + for (TRank rank = 0; rank < rMax1; rank++) { + items1.computePermutation(rank); + writefln("%3d: %s = %d", rank, items1, items1.computeRank); + } + writeln; + + uint[21] items2 = void; + immutable rMax2 = items2.length.factorial; + foreach (immutable _; 0 .. 5) { + immutable rank = uniform(0, rMax2); + items2.computePermutation(rank); + writefln("%20d: %s = %d", rank, items2, items2.computeRank); + } +} diff --git a/Task/Permutations-Rank-of-a-permutation/Go/permutations-rank-of-a-permutation.go b/Task/Permutations-Rank-of-a-permutation/Go/permutations-rank-of-a-permutation.go new file mode 100644 index 0000000000..8774905de8 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Go/permutations-rank-of-a-permutation.go @@ -0,0 +1,82 @@ +package main + +import ( + "fmt" + "math/rand" +) + +// returns permutation q of n items, using Myrvold-Ruskey rank. +func MRPerm(q, n int) []int { + p := ident(n) + var r int + for n > 0 { + q, r = q/n, q%n + n-- + p[n], p[r] = p[r], p[n] + } + return p +} + +// returns identity permutation of n items. +func ident(n int) []int { + p := make([]int, n) + for i := range p { + p[i] = i + } + return p +} + +// returns Myrvold-Ruskey rank of permutation p +func MRRank(p []int) (r int) { + p = append([]int{}, p...) + inv := inverse(p) + for i := len(p) - 1; i > 0; i-- { + s := p[i] + p[inv[i]] = s + inv[s] = inv[i] + } + for i := 1; i < len(p); i++ { + r = r*(i+1) + p[i] + } + return +} + +// returns inverse of a permutation. +func inverse(p []int) []int { + r := make([]int, len(p)) + for i, x := range p { + r[x] = i + } + return r +} + +// returns n! +func fact(n int) (f int) { + for f = n; n > 2; { + n-- + f *= n + } + return +} + +func main() { + n := 3 + fmt.Println("permutations of", n, "items") + f := fact(n) + for i := 0; i < f; i++ { + p := MRPerm(i, n) + fmt.Println(i, p, MRRank(p)) + } + n = 12 + fmt.Println("permutations of", n, "items") + f = fact(n) + m := map[int]bool{} + for len(m) < 4 { + r := rand.Intn(f) + if m[r] { + continue + } + m[r] = true + fmt.Println(r, MRPerm(r, n)) + } +} diff --git a/Task/Permutations-Rank-of-a-permutation/Haskell/permutations-rank-of-a-permutation.hs b/Task/Permutations-Rank-of-a-permutation/Haskell/permutations-rank-of-a-permutation.hs new file mode 100644 index 0000000000..9dd77baf2f --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Haskell/permutations-rank-of-a-permutation.hs @@ -0,0 +1,14 @@ +fact n = foldr (*) 1 [1..n] + +-- always assume elements are unique +rankPerm [] _ = [] +rankPerm list n = c:rankPerm (a++b) r where + (q,r) = n `divMod` fact (length list - 1) + (a,c:b) = splitAt q list + +permRank [] = 0 +permRank (x:xs) = length(filter ( " + Arrays.toString(permutation) + " --> " + getRank(permutation)); + } + Random rnd = new Random(); + for (int n : new int[] { 12, 144 }) + { + BigInteger factorial = BigInteger.ONE; + for (int i = 2; i <= n; i++) + factorial = factorial.multiply(BigInteger.valueOf(i)); + // Create 5 random samples + System.out.println("n = " + n); + for (int i = 0; i < 5; i++) + { + BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); + rank = rank.mod(factorial); + int[] permutation = getPermutation(n, rank); + System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); + } + } + } + +} diff --git a/Task/Permutations-Rank-of-a-permutation/Mathematica/permutations-rank-of-a-permutation.math b/Task/Permutations-Rank-of-a-permutation/Mathematica/permutations-rank-of-a-permutation.math new file mode 100644 index 0000000000..b47f1ae6b5 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Mathematica/permutations-rank-of-a-permutation.math @@ -0,0 +1,14 @@ +fromrank[list_, 0] := list; +fromrank[list_, n_] := + Prepend[fromrank[DeleteCases[list, #], + Mod[n, (Length@list - 1)!]], #] &@ + RankedMin[list, Quotient[n, (Length@list - 1)!] + 1]; + +rank[{}] = 0; +rank[{x_, y___}] := Count[{y}, _?(# < x &)] Length@{y}! + rank[{y}]; + +Print /@ Table[{n, fromrank[{0, 1, 2, 3}, n], + rank@fromrank[{0, 1, 2, 3}, n]}, {n, 0, 23}]; + +Do[Print@fromrank[Range[0, 12 - 1], RandomInteger[12!]], {4}]; +Do[Print@fromrank[Range[0, 144 - 1], RandomInteger[144!]], {4}]; diff --git a/Task/Permutations-Rank-of-a-permutation/PARI-GP/permutations-rank-of-a-permutation.pari b/Task/Permutations-Rank-of-a-permutation/PARI-GP/permutations-rank-of-a-permutation.pari new file mode 100644 index 0000000000..6167be9d71 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/PARI-GP/permutations-rank-of-a-permutation.pari @@ -0,0 +1,3 @@ +vector(3!,i,permtonum(numtoperm(3,i-1)))==vector(3!,i,i-1) +vector(4,i,numtoperm(12,random(12!))) +for(i=1,1e6,numtoperm(144,random(144!))) diff --git a/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-1.py b/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-1.py new file mode 100644 index 0000000000..409eeed76e --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-1.py @@ -0,0 +1,86 @@ +from math import factorial as fact +from random import randrange +from textwrap import wrap + +def identity_perm(n): + return list(range(n)) + +def unranker1(n, r, pi): + while n > 0: + n1, (rdivn, rmodn) = n-1, divmod(r, n) + pi[n1], pi[rmodn] = pi[rmodn], pi[n1] + n = n1 + r = rdivn + return pi + +def init_pi1(n, pi): + pi1 = [-1] * n + for i in range(n): + pi1[pi[i]] = i + return pi1 + +def ranker1(n, pi, pi1): + if n == 1: + return 0 + n1 = n-1 + s = pi[n1] + pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] + pi1[s], pi1[n1] = pi1[n1], pi1[s] + return s + n * ranker1(n1, pi, pi1) + +def unranker2(n, r, pi): + while n > 0: + n1 = n-1 + s, rmodf = divmod(r, fact(n1)) + pi[n1], pi[s] = pi[s], pi[n1] + n = n1 + r = rmodf + return pi + +def ranker2(n, pi, pi1): + if n == 1: + return 0 + n1 = n-1 + s = pi[n1] + pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] + pi1[s], pi1[n1] = pi1[n1], pi1[s] + return s * fact(n1) + ranker2(n1, pi, pi1) + +def get_random_ranks(permsize, samplesize): + perms = fact(permsize) + ranks = set() + while len(ranks) < samplesize: + ranks |= set( randrange(perms) + for r in range(samplesize - len(ranks)) ) + return ranks + +def test1(comment, unranker, ranker): + n, samplesize, n2 = 3, 4, 12 + print(comment) + perms = [] + for r in range(fact(n)): + pi = identity_perm(n) + perm = unranker(n, r, pi) + perms.append((r, perm)) + for r, pi in perms: + pi1 = init_pi1(n, pi) + print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1))) + print('\n %i random individual samples of %i items:' % (samplesize, n2)) + for r in get_random_ranks(n2, samplesize): + pi = identity_perm(n2) + print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi))) + print('') + +def test2(comment, unranker): + samplesize, n2 = 4, 144 + print(comment) + print(' %i random individual samples of %i items:' % (samplesize, n2)) + for r in get_random_ranks(n2, samplesize): + pi = identity_perm(n2) + print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi))))) + print('') + +if __name__ == '__main__': + test1('First ordering:', unranker1, ranker1) + test1('Second ordering:', unranker2, ranker2) + test2('First ordering, large number of perms:', unranker1) diff --git a/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-2.py b/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-2.py new file mode 100644 index 0000000000..de5f6cf4a4 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Python/permutations-rank-of-a-permutation-2.py @@ -0,0 +1,17 @@ +def ranker1(n, pi, pi1): + if n == 1: + return 0 + n1 = n-1 + s = pi[n1] + pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] + pi1[s], pi1[n1] = pi1[n1], pi1[s] + return s + n * ranker1(n1, pi, pi1) + +def ranker2(n, pi, pi1): + result = 0 + for i in range(n-1, 0, -1): + s = pi[i] + pi[i], pi[pi1[i]] = pi[pi1[i]], pi[i] + pi1[s], pi1[i] = pi1[i], pi1[s] + result += s * fact(i) + return result diff --git a/Task/Permutations-Rank-of-a-permutation/README b/Task/Permutations-Rank-of-a-permutation/README new file mode 100644 index 0000000000..92f0d48b20 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation diff --git a/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx b/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx new file mode 100644 index 0000000000..484d0a178c --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx @@ -0,0 +1,33 @@ +/*REXX program shows permutations of N number of objects (1,2,3, ...).*/ +parse arg N seed .; if N=='' then N=3 /*Not specified? Assume default*/ +permutes=permsets(N) /*returns N! (# of permutations)*/ +w=length(permutes) /*used for aligning the SAY stuff*/ + + do what=0 to permutes-1 /*traipse through each permute. */ + z=permsets(N, what) /*get the "what" permuation. */ + say N 'items, permute' right(what,w) "=" z ' rank=' permsets(N,,z) + end /*what*/ + +say; if seed\=='' then call random ,,seed /*seed ≡ repeatability.*/ +N=12 + do 4; ?=random(0, N**4) /*REXX has a 100k RANDOM range.*/ + say N 'items, permute' right(?,6) " is " permsets(N,?) + end /*rand*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────PERMSETS subroutine─────────────────*/ +permsets: procedure expose @. #; #=0; parse arg x,r,c; c=space(c); xm=x-1 + + do j=1 for x; @.j=j-1; end /*j*/; _=0; do u=2 for xm; _=_ @.u; end /*u*/ + if r==# then return _; if c==_ then return # + + do while .permsets(x,0); #=#+1; _=@.1; do u=2 for xm; _=_ @.u; end /*u*/ + if r==# then return _; if c==_ then return # + end /*while···*/ +return #+1 + +.permsets: procedure expose @.; parse arg p,q; pm=p-1 + do k=pm by -1 for pm; kp=k+1; if @.k<@.kp then do; q=k; leave; end; end + do j=q+1 while j #{prm=perm.unrank(num)} --> #{perm.rank(prm)}"} + +puts "\n4 random samples of 12 items from and back to rank." +perm = Permutation.new(12) +4.times{ puts "%9d --> %s --> %9d" % [r=rand(perm.size), prm=perm.unrank(r), perm.rank(prm)]} + +puts "\n4 random uniq samples of 144 items:" +perm, rands = Permutation.new(144), {} +# generate 1_000_000 unique random numbers in the range (0...144!) (takes about 2.5 seconds) +rands[rand(perm.size)] = true until rands.size == 1_000_000 + +random_perms = rands.each_key.lazy{|k| perm.unrank(k)} +# random_perms is lazy. Generate permutations one by one: +4.times do + p r = random_perms.next + p prm = perm.unrank(r) + p perm.rank(prm) == r +end diff --git a/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-1.tcl b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-1.tcl new file mode 100644 index 0000000000..2c2c6db6fb --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-1.tcl @@ -0,0 +1,34 @@ +# A functional swap routine +proc swap {v idx1 idx2} { + lset v $idx2 [lindex $v $idx1][lset v $idx1 [lindex $v $idx2];subst ""] +} + +# Fill the integer array with the permutation at rank +proc computePermutation {vecName rank} { + upvar 1 $vecName vec + if {![info exist vec] || ![llength $vec]} return + set N [llength $vec] + for {set n 0} {$n < $N} {incr n} {lset vec $n $n} + for {set n $N} {$n>=1} {incr n -1} { + set r [expr {$rank % $n}] + set rank [expr {$rank / $n}] + set vec [swap $vec $r [expr {$n-1}]] + } +} + +# Return the rank of the current permutation. +proc computeRank {vec} { + if {![llength $vec]} return + set inv [lrepeat [llength $vec] 0] + set i -1 + foreach v $vec {lset inv $v [incr i]} + # First argument is lambda term + set mrRank1 {{f n vec inv} { + if {$n < 2} {return 0} + set s [lindex $vec [set n1 [expr {$n - 1}]]] + set vec [swap $vec $n1 [lindex $inv $n1]] + set inv [swap $inv $s $n1] + return [expr {$s + $n * [apply $f $f $n1 $vec $inv]}] + }} + return [apply $mrRank1 $mrRank1 [llength $vec] $vec $inv] +} diff --git a/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-2.tcl b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-2.tcl new file mode 100644 index 0000000000..356f8e193f --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-2.tcl @@ -0,0 +1,24 @@ +proc factorial {n} { + for {set result 1; set i 2} {$i <= $n} {incr i} { + set result [expr {$result * $i}] + } + return $result +} + +set items1 [lrepeat 4 ""] +set rMax1 [factorial [llength $items1]] +for {set rank 0} {$rank < $rMax1} {incr rank} { + computePermutation items1 $rank + puts [format "%3d: \[%s\] = %d" \ + $rank [join $items1 ", "] [computeRank $items1]] +} +puts "" +set items2 [lrepeat 21 ""] +set rMax2 [factorial [llength $items2]] +foreach _ {1 2 3 4} { + # Note that we're casting to (potential) bignum, so entier() not int() + set rank [expr {entier(rand() * $rMax2)}] + computePermutation items2 $rank + puts [format "%20lld: \[%s\] = %lld" \ + $rank [join $items2 ", "] [computeRank $items2]] +} diff --git a/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-3.tcl b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-3.tcl new file mode 100644 index 0000000000..73bcf26a05 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Tcl/permutations-rank-of-a-permutation-3.tcl @@ -0,0 +1,7 @@ +proc uniform {limit} { + set bits [expr {ceil(log($limit)/log(2))+10}] + for {set b [set r 0]} {$b < $bits} {incr b 16} { + incr r [expr {2**$b * int(rand() * 2**16)}] + } + return [expr {$r % $limit}] +} diff --git a/Task/Pernicious-numbers/00DESCRIPTION b/Task/Pernicious-numbers/00DESCRIPTION new file mode 100644 index 0000000000..4b0169e942 --- /dev/null +++ b/Task/Pernicious-numbers/00DESCRIPTION @@ -0,0 +1,12 @@ +A ''[[wp:Pernicious number|pernicious number]]'' is a positive integer whose [[population count]] is a prime. +
The ''population count'' (also known as ''pop count'') is the number of 1's (ones) in the binary representation of a non-negative integer.
+For example, 22 (which is 10110 in binary) has a population count of 3, which is prime and so 22 is a pernicious number. + +;Task requirements +* display the first 25 pernicious numbers. +* display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive). +* display each list of integers on one line (which may or may not include a title). + +;See also +* Sequence [[oeis:A052294|A052294 pernicious numbers]] on The On-Line Encyclopedia of Integer Sequences. +* Rosetta Code entry [[Population_count|population count, evil numbers, odious numbers]]. diff --git a/Task/Pernicious-numbers/00META.yaml b/Task/Pernicious-numbers/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Pernicious-numbers/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Pernicious-numbers/Ada/pernicious-numbers-1.ada b/Task/Pernicious-numbers/Ada/pernicious-numbers-1.ada new file mode 100644 index 0000000000..d870ab0af3 --- /dev/null +++ b/Task/Pernicious-numbers/Ada/pernicious-numbers-1.ada @@ -0,0 +1,40 @@ +with Ada.Text_IO, Population_Count; use Population_Count; + +procedure Pernicious is + + Prime: array(0 .. 64) of Boolean; + -- we are using 64-bit numbers, so the population count is between 0 and 64 + X: Num; use type Num; + Cnt: Positive; +begin + -- initialize array Prime; Prime(I) must be true if and only if I is a prime + Prime := (0 => False, 1 => False, others => True); + for I in 2 .. 8 loop + if Prime(I) then + Cnt := I + I; + while Cnt <= 64 loop + Prime(Cnt) := False; + Cnt := Cnt + I; + end loop; + end if; + end loop; + + -- print first 25 pernicious numbers + X := 1; + for I in 1 .. 25 loop + while not Prime(Pop_Count(X)) loop + X := X + 1; + end loop; + Ada.Text_IO.Put(Num'Image(X)); + X := X + 1; + end loop; + Ada.Text_IO.New_Line; + + -- print pernicious numbers between 888_888_877 and 888_888_888 (inclusive) + for Y in Num(888_888_877) .. 888_888_888 loop + if Prime(Pop_Count(Y)) then + Ada.Text_IO.Put(Num'Image(Y)); + end if; + end loop; + Ada.Text_IO.New_Line; +end; diff --git a/Task/Pernicious-numbers/Ada/pernicious-numbers-2.ada b/Task/Pernicious-numbers/Ada/pernicious-numbers-2.ada new file mode 100644 index 0000000000..efc5871208 --- /dev/null +++ b/Task/Pernicious-numbers/Ada/pernicious-numbers-2.ada @@ -0,0 +1,14 @@ + Counter: Natural; +begin + -- initialize array Prime; Prime(I) must be true if and only if I is a prime + ... + + Counter := 0; + -- count p. numbers below 2**32 + for Y in Num(2) .. 2**32 loop + if Prime(Pop_Count(Y)) then + Counter := Counter + 1; + end if; + end loop; + Ada.Text_IO.Put_Line(Natural'Image(Counter)); +end Count_Pernicious; diff --git a/Task/Pernicious-numbers/AutoHotkey/pernicious-numbers.ahk b/Task/Pernicious-numbers/AutoHotkey/pernicious-numbers.ahk new file mode 100644 index 0000000000..2534c4e8a9 --- /dev/null +++ b/Task/Pernicious-numbers/AutoHotkey/pernicious-numbers.ahk @@ -0,0 +1,16 @@ +c := 0 +while c < 25 + if IsPern(A_Index) + Out1 .= A_Index " ", c++ +Loop, 12 + if IsPern(n := 888888876 + A_Index) + Out2 .= n " " +MsgBox, % Out1 "`n" Out2 + +IsPern(x) { ;https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation + static p := {2:1, 3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1} + x -= (x >> 1) & 0x5555555555555555 + , x := (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333) + , x := (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f + return p[(x * 0x0101010101010101) >> 56] +} diff --git a/Task/Pernicious-numbers/C++/pernicious-numbers.cpp b/Task/Pernicious-numbers/C++/pernicious-numbers.cpp new file mode 100644 index 0000000000..6ec2c6a466 --- /dev/null +++ b/Task/Pernicious-numbers/C++/pernicious-numbers.cpp @@ -0,0 +1,51 @@ +#include +#include +#include + +using namespace std; + +class pernNumber +{ +public: + void displayFirst( unsigned cnt ) + { + unsigned pn = 3; + while( cnt ) + { + if( isPernNumber( pn ) ) + { + cout << pn << " "; cnt--; + } + pn++; + } + } + void displayFromTo( unsigned a, unsigned b ) + { + for( unsigned p = a; p <= b; p++ ) + if( isPernNumber( p ) ) + cout << p << " "; + } + +private: + bool isPernNumber( unsigned p ) + { + string bin = bitset<64>( p ).to_string(); + unsigned c = count( bin.begin(), bin.end(), '1' ); + return isPrime( c ); + } + bool isPrime( unsigned p ) + { + if( p == 2 ) return true; + if( p < 2 || !( p % 2 ) ) return false; + for( unsigned x = 3; ( x * x ) <= p; x += 2 ) + if( !( p % x ) ) return false; + return true; + } +}; +int main( int argc, char* argv[] ) +{ + pernNumber p; + p.displayFirst( 25 ); cout << endl; + p.displayFromTo( 888888877, 888888888 ); cout << endl; + return 0; +} diff --git a/Task/Pernicious-numbers/C/pernicious-numbers.c b/Task/Pernicious-numbers/C/pernicious-numbers.c new file mode 100644 index 0000000000..19f3441b35 --- /dev/null +++ b/Task/Pernicious-numbers/C/pernicious-numbers.c @@ -0,0 +1,25 @@ +#include + +typedef unsigned uint; +uint is_pern(uint n) +{ + uint c = 2693408940u; // int with all prime-th bits set + while (n) c >>= 1, n &= (n - 1); // take out lowerest set bit one by one + return c & 1; +} + +int main(void) +{ + uint i, c; + for (i = c = 0; c < 25; i++) + if (is_pern(i)) + printf("%u ", i), ++c; + putchar('\n'); + + for (i = 888888877u; i <= 888888888u; i++) + if (is_pern(i)) + printf("%u ", i); + putchar('\n'); + + return 0; +} diff --git a/Task/Pernicious-numbers/Common-Lisp/pernicious-numbers.lisp b/Task/Pernicious-numbers/Common-Lisp/pernicious-numbers.lisp new file mode 100644 index 0000000000..36a9072762 --- /dev/null +++ b/Task/Pernicious-numbers/Common-Lisp/pernicious-numbers.lisp @@ -0,0 +1,11 @@ +(format T "~{~a ~}~%" + (loop for n = 1 then (1+ n) + when (primep (logcount n)) + collect n into numbers + when (= (length numbers) 25) + return numbers)) + +(format T "~{~a ~}~%" + (loop for n from 888888877 to 888888888 + when (primep (logcount n)) + collect n)) diff --git a/Task/Pernicious-numbers/D/pernicious-numbers-1.d b/Task/Pernicious-numbers/D/pernicious-numbers-1.d new file mode 100644 index 0000000000..98a72a3f85 --- /dev/null +++ b/Task/Pernicious-numbers/D/pernicious-numbers-1.d @@ -0,0 +1,7 @@ +void main() { + import std.stdio, std.algorithm, std.range, core.bitop; + + immutable pernicious = (in uint n) => (2 ^^ n.popcnt) & 0xA08A28AC; + uint.max.iota.filter!pernicious.take(25).writeln; + iota(888_888_877, 888_888_889).filter!pernicious.writeln; +} diff --git a/Task/Pernicious-numbers/D/pernicious-numbers-2.d b/Task/Pernicious-numbers/D/pernicious-numbers-2.d new file mode 100644 index 0000000000..30380e81d1 --- /dev/null +++ b/Task/Pernicious-numbers/D/pernicious-numbers-2.d @@ -0,0 +1 @@ +uint.max.iota.filter!pernicious.walkLength.writeln; diff --git a/Task/Pernicious-numbers/Go/pernicious-numbers.go b/Task/Pernicious-numbers/Go/pernicious-numbers.go new file mode 100644 index 0000000000..a96a721bd6 --- /dev/null +++ b/Task/Pernicious-numbers/Go/pernicious-numbers.go @@ -0,0 +1,33 @@ +package main + +import "fmt" + +func pernicious(w uint32) bool { + const ( + ff = 1<<32 - 1 + mask1 = ff / 3 + mask3 = ff / 5 + maskf = ff / 17 + maskp = ff / 255 + ) + w -= w >> 1 & mask1 + w = w&mask3 + w>>2&mask3 + w = (w + w>>4) & maskf + return 0xa08a28ac>>(w*maskp>>24)&1 != 0 +} + +func main() { + for i, n := 0, uint32(1); i < 25; n++ { + if pernicious(n) { + fmt.Printf("%d ", n) + i++ + } + } + fmt.Println() + for n := uint32(888888877); n <= 888888888; n++ { + if pernicious(n) { + fmt.Printf("%d ", n) + } + } + fmt.Println() +} diff --git a/Task/Pernicious-numbers/Haskell/pernicious-numbers.hs b/Task/Pernicious-numbers/Haskell/pernicious-numbers.hs new file mode 100644 index 0000000000..d8f97c85cf --- /dev/null +++ b/Task/Pernicious-numbers/Haskell/pernicious-numbers.hs @@ -0,0 +1,17 @@ +module Pernicious + where + +isPernicious :: Integer -> Bool +isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num + +isPrime :: Integer -> Bool +isPrime number = divisors number == [1, number] + where + divisors :: Integer -> [Integer] + divisors number = [ m | m <- [1 .. number] , number `mod` m == 0 ] + +toBinary :: Integer -> [Integer] +toBinary num = reverse $ map ( `mod` 2 ) ( takeWhile ( /= 0 ) $ iterate ( `div` 2 ) num ) + +solution1 = take 25 $ filter isPernicious [1 ..] +solution2 = filter isPernicious [888888877 .. 888888888] diff --git a/Task/Pernicious-numbers/Icon/pernicious-numbers.icon b/Task/Pernicious-numbers/Icon/pernicious-numbers.icon new file mode 100644 index 0000000000..f33e6affd7 --- /dev/null +++ b/Task/Pernicious-numbers/Icon/pernicious-numbers.icon @@ -0,0 +1,16 @@ +link "factors" + +procedure main(A) + every writes((pernicious(seq())\25||" ") | "\n") + every writes((pernicious(888888877 to 888888888)||" ") | "\n") +end + +procedure pernicious(n) + return (isprime(c1bits(n)),n) +end + +procedure c1bits(n) + c := 0 + while n > 0 do c +:= 1(n%2, n/:=2) + return c +end diff --git a/Task/Pernicious-numbers/J/pernicious-numbers-1.j b/Task/Pernicious-numbers/J/pernicious-numbers-1.j new file mode 100644 index 0000000000..d58c5c2a2d --- /dev/null +++ b/Task/Pernicious-numbers/J/pernicious-numbers-1.j @@ -0,0 +1,3 @@ +ispernicious=: 1 p: +/"1@#: + +thru=: <./ + i.@(+*)@-~ diff --git a/Task/Pernicious-numbers/J/pernicious-numbers-2.j b/Task/Pernicious-numbers/J/pernicious-numbers-2.j new file mode 100644 index 0000000000..bfbba8a2fd --- /dev/null +++ b/Task/Pernicious-numbers/J/pernicious-numbers-2.j @@ -0,0 +1,4 @@ + 25{.I.ispernicious i.100 +3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36 + 888888877 + I. ispernicious 888888877 thru 888888888 +888888877 888888878 888888880 888888883 888888885 888888886 diff --git a/Task/Pernicious-numbers/Java/pernicious-numbers.java b/Task/Pernicious-numbers/Java/pernicious-numbers.java new file mode 100644 index 0000000000..cb8f37f19d --- /dev/null +++ b/Task/Pernicious-numbers/Java/pernicious-numbers.java @@ -0,0 +1,29 @@ +public class Pernicious{ + //very simple isPrime since x will be <= Long.SIZE + public static boolean isPrime(int x){ + if(x < 2) return false; + for(int i = 2; i < x; i++){ + if(x % i == 0) return false; + } + return true; + } + + public static int popCount(long x){ + return Long.bitCount(x); + } + + public static void main(String[] args){ + for(long i = 1, n = 0; n < 25; i++){ + if(isPrime(popCount(i))){ + System.out.print(i + " "); + n++; + } + } + + System.out.println(); + + for(long i = 888888877; i <= 888888888; i++){ + if(isPrime(popCount(i))) System.out.print(i + " "); + } + } +} diff --git a/Task/Pernicious-numbers/Mathematica/pernicious-numbers-1.math b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-1.math new file mode 100644 index 0000000000..722ed152e3 --- /dev/null +++ b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-1.math @@ -0,0 +1,17 @@ +popcount[n_Integer] := IntegerDigits[n, 2] // Total +perniciousQ[n_Integer] := popcount[n] // PrimeQ +perniciouscount = 0; +perniciouslist = {}; +i = 0; +While[perniciouscount < 25, + If[perniciousQ[i], AppendTo[perniciouslist, i]; perniciouscount++]; + i++] +Print["first 25 pernicious numbers"] +perniciouslist +(*******) +perniciouslist2 = {}; +Do[ + If[perniciousQ[i], AppendTo[perniciouslist2, i]] + , {i, 888888877, 888888888}] +Print["Pernicious numbers between 888,888,877 and 888,888,888 (inclusive)"] +perniciouslist2 diff --git a/Task/Pernicious-numbers/Mathematica/pernicious-numbers-2.math b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-2.math new file mode 100644 index 0000000000..72f74f6f22 --- /dev/null +++ b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-2.math @@ -0,0 +1 @@ +perniciousQ[n_Integer] := PrimeQ@Total@IntegerDigits[n, 2] diff --git a/Task/Pernicious-numbers/Mathematica/pernicious-numbers-3.math b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-3.math new file mode 100644 index 0000000000..c43b4bf46a --- /dev/null +++ b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-3.math @@ -0,0 +1 @@ +n = 0; NestWhile[Flatten@{#, If[perniciousQ[++n], n, {}]} &, {}, Length@# < 25 &] diff --git a/Task/Pernicious-numbers/Mathematica/pernicious-numbers-4.math b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-4.math new file mode 100644 index 0000000000..047a87edad --- /dev/null +++ b/Task/Pernicious-numbers/Mathematica/pernicious-numbers-4.math @@ -0,0 +1 @@ +Cases[Range[888888877, 888888888], _?(perniciousQ@# &)] diff --git a/Task/Pernicious-numbers/PARI-GP/pernicious-numbers.pari b/Task/Pernicious-numbers/PARI-GP/pernicious-numbers.pari new file mode 100644 index 0000000000..7c128ac4b8 --- /dev/null +++ b/Task/Pernicious-numbers/PARI-GP/pernicious-numbers.pari @@ -0,0 +1,3 @@ +pern(n)=isprime(hammingweight(n)) +select(pern, [1..36]) +select(pern,[888888877..888888888]) diff --git a/Task/Pernicious-numbers/Pascal/pernicious-numbers.pascal b/Task/Pernicious-numbers/Pascal/pernicious-numbers.pascal new file mode 100644 index 0000000000..f29ee472d3 --- /dev/null +++ b/Task/Pernicious-numbers/Pascal/pernicious-numbers.pascal @@ -0,0 +1,65 @@ +program pernicious; +{$IFDEF FPC} + {$OPTIMIZATION ON,Regvar,ASMCSE,CSE,PEEPHOLE}// 3x speed up +{$ENDIF} +uses + sysutils;//only used for time + +type + tbArr = array[0..64] of byte; +{ + PrimeTil64 : array[0..64] of byte = + (0,0,2,3,0,5,0, 7,0,0,0,11,0,13,0,0,0,17,0,19,0,0,0,23,0,0,0,0,0,29,0, + 31,0,0,0,0,0,37,0,0,0,41,0,43,0,0,0,47,0, 0,0,0,0,53,0,0,0,0,0,59,0, + 61,0,0,0); +} +const + PrimeTil64 : tbArr = + (0,0,1,1,0,1,0, 1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0, + 1,0,0,0,0,0, 1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0, + 1,0,0,0); + +function popcnt32(n:Uint32):NativeUint; +//https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation +const + K1 = $0101010101010101; + K33 = $3333333333333333; + K55 = $5555555555555555; + KF1 = $0F0F0F0F0F0F0F0F; +begin + n := n- (n shr 1) AND NativeUint(K55); + n := (n AND NativeUint(K33))+ ((n shr 2) AND NativeUint(K33)); + n := (n + (n shr 4)) AND NativeUint(KF1); + n := (n*NativeUint(K1)) SHR 24; + popcnt32 := n; +end; + +var + t : TDAteTime; + i, + k : LongWord; + +Begin + writeln('the 25 first pernicious numbers'); + I:=1;k:=0; + repeat + IF PrimeTil64[popCnt32(i)] <> 0 then Begin + inc(k); write(i,' ');end; + inc(i); + until k >= 25; + writeln; + + writeln('pernicious numbers in [888888877..888888888]'); + For i := 888888877 to 888888888 do + IF PrimeTil64[popCnt32(i)] <> 0 then + write(i,' '); + writeln; + + //speedtest of popcount + t:= time; + k := 0; + For i := High(i) downto 0 do + k := k+PrimeTil64[popCnt32(i)]; + t := time-t; + writeln(k,' pernicious numbers in [0..2^32-1] takes ',t*86400:0:3,' seconds'); + end. diff --git a/Task/Pernicious-numbers/Perl-6/pernicious-numbers.pl6 b/Task/Pernicious-numbers/Perl-6/pernicious-numbers.pl6 new file mode 100644 index 0000000000..08837cb59f --- /dev/null +++ b/Task/Pernicious-numbers/Perl-6/pernicious-numbers.pl6 @@ -0,0 +1,6 @@ +sub is-pernicious(Int $n --> Bool) { + is-prime [+] $n.base(2).comb; +} + +say (grep &is-pernicious, 0 .. *)[^25]; +say grep &is-pernicious, 888_888_877 .. 888_888_888; diff --git a/Task/Pernicious-numbers/Perl/pernicious-numbers-1.pl b/Task/Pernicious-numbers/Perl/pernicious-numbers-1.pl new file mode 100644 index 0000000000..c135bd9eba --- /dev/null +++ b/Task/Pernicious-numbers/Perl/pernicious-numbers-1.pl @@ -0,0 +1,22 @@ +sub is_pernicious { + my $n = shift; + my $c = 2693408940; # primes < 32 as set bits + while ($n) { $c >>= 1; $n &= ($n - 1); } + $c & 1; +} + +my ($i, @p) = 0; +while (@p < 25) { + push @p, $i if is_pernicious($i); + $i++; +} + +print join ' ', @p; +print "\n"; +($i, @p) = (888888877,); +while ($i < 888888888) { + push @p, $i if is_pernicious($i); + $i++; +} + +print join ' ', @p; diff --git a/Task/Pernicious-numbers/Perl/pernicious-numbers-2.pl b/Task/Pernicious-numbers/Perl/pernicious-numbers-2.pl new file mode 100644 index 0000000000..58063a80b3 --- /dev/null +++ b/Task/Pernicious-numbers/Perl/pernicious-numbers-2.pl @@ -0,0 +1,5 @@ +use ntheory qw/is_prime hammingweight/; +my $i = 1; +my @pern = map { $i++ while !is_prime(hammingweight($i)); $i++; } 1..25; +print "@pern\n"; +print join(" ", grep { is_prime(hammingweight($_)) } 888888877 .. 888888888), "\n"; diff --git a/Task/Pernicious-numbers/Python/pernicious-numbers.py b/Task/Pernicious-numbers/Python/pernicious-numbers.py new file mode 100644 index 0000000000..8b16e64092 --- /dev/null +++ b/Task/Pernicious-numbers/Python/pernicious-numbers.py @@ -0,0 +1,20 @@ +>>> def popcount(n): return bin(n).count("1") + +>>> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61} +>>> p, i = [], 0 +>>> while len(p) < 25: + if popcount(i) in primes: p.append(i) + i += 1 + + +>>> p +[3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 31, 33, 34, 35, 36] +>>> p, i = [], 888888877 +>>> while i <= 888888888: + if popcount(i) in primes: p.append(i) + i += 1 + + +>>> p +[888888877, 888888878, 888888880, 888888883, 888888885, 888888886] +>>> diff --git a/Task/Pernicious-numbers/README b/Task/Pernicious-numbers/README new file mode 100644 index 0000000000..c5d1f39fc1 --- /dev/null +++ b/Task/Pernicious-numbers/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Pernicious_numbers diff --git a/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx new file mode 100644 index 0000000000..ddd383d0f9 --- /dev/null +++ b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx @@ -0,0 +1,31 @@ +/*REXX program displays a number of pernicious numbers and also a range.*/ +numeric digits 30 /*be able to handle large numbers*/ +parse arg N L H . /*get optional arguments: N, L, H*/ +if N=='' | N==',' then N=25 /*N given? Then use the default.*/ +if L=='' | L==',' then L=888888877 /*L " ? " " " " */ +if H=='' | H==',' then H=888888888 /*H " ? " " " " */ +say 'The 1st ' N " pernicious numbers are:" /*display a nice title.*/ +say pernicious(1,,N) /*get all pernicious # from 1──►N*/ +say /*display a blank line for a sep.*/ +say 'Pernicious numbers between ' L " and " H ' (inclusive) are:' +say pernicious(L,H) /*get all pernicious # from L──►H*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────D2B subroutine──────────────────────*/ +d2b: return word(strip(x2b(d2x(arg(1))),'L',0) 0,1) /*convert dec──►bin*/ +/*──────────────────────────────────PERNICIOUS subroutine───────────────*/ +pernicious: procedure; parse arg bot,top,m /*get the bot & top #s, limit*/ +_ = 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 +!.=0; do k=1 until p=''; p=word(_,k); !.p=1; end /*gen low prime array*/ +if m=='' then m=999999999 /*assume an "infinite" limit. */ +if top=='' then top=999999999 /*assume an "infinite" top limit.*/ +#=0 /*number of pernicious #s so far.*/ +$=; do j=bot to top until #==m /*gen pernicious until satisfied.*/ + pc=popCount(j) /*obtain population count for J.*/ + if \!.pc then iterate /*if popCount ¬ in !.prime, skip.*/ + $=$ j /*append a pernicious # to list.*/ + #=#+1 /*bump the pernicious # count. */ + end /*j*/ /* [↑] append popCount to a list*/ +return substr($,2) /*return results, sans 1st blank.*/ +/*──────────────────────────────────POPCOUNT subroutine─────────────────*/ +popCount: procedure;_=d2b(abs(arg(1))) /*convert the # passed to binary.*/ +return length(_)-length(space(translate(_,,1),0)) /*count the one bits.*/ diff --git a/Task/Pernicious-numbers/Racket/pernicious-numbers.rkt b/Task/Pernicious-numbers/Racket/pernicious-numbers.rkt new file mode 100644 index 0000000000..9a47ad0944 --- /dev/null +++ b/Task/Pernicious-numbers/Racket/pernicious-numbers.rkt @@ -0,0 +1,21 @@ +#lang racket +(require math/number-theory rnrs/arithmetic/bitwise-6) + +(define pernicious? (compose prime? bitwise-bit-count)) + +(define (dnl . strs) + (for-each displayln strs)) + +(define (show-sequence seq) + (string-join (for/list ((v (in-values*-sequence seq))) (~a ((if (list? v) car values) v))) ", ")) + +(dnl + "Task requirements:" + "display the first 25 pernicious numbers." + (show-sequence (in-parallel (sequence-filter pernicious? (in-naturals 1)) (in-range 25))) + "display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive)." + (show-sequence (sequence-filter pernicious? (in-range 888888877 (add1 888888888))))) + +(module+ test + (require rackunit) + (check-true (pernicious? 22))) diff --git a/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb b/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb new file mode 100644 index 0000000000..43f33d7d70 --- /dev/null +++ b/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb @@ -0,0 +1,16 @@ +require "prime" + +class Integer + + def popcount + to_s(2).count("1") + end + + def pernicious? + popcount.prime? + end + +end + +p 1.step.lazy.select(&:pernicious?).take(25).to_a +p ( 888888877..888888888).select(&:pernicious?) diff --git a/Task/Pernicious-numbers/Scala/pernicious-numbers.scala b/Task/Pernicious-numbers/Scala/pernicious-numbers.scala new file mode 100644 index 0000000000..2621a2d569 --- /dev/null +++ b/Task/Pernicious-numbers/Scala/pernicious-numbers.scala @@ -0,0 +1,8 @@ +def isPernicious( v:Long ) : Boolean = BigInt(v.toBinaryString.toList.filter( _ == '1' ).length).isProbablePrime(16) + +// Generate the output +{ + val (a,b1,b2) = (25,888888877L,888888888L) + println( Stream.from(2).filter( isPernicious(_) ).take(a).toList.mkString(",") ) + println( {for( i <- b1 to b2 if( isPernicious(i) ) ) yield i}.mkString(",") ) +} diff --git a/Task/Pernicious-numbers/Tcl/pernicious-numbers.tcl b/Task/Pernicious-numbers/Tcl/pernicious-numbers.tcl new file mode 100644 index 0000000000..2f1676c71c --- /dev/null +++ b/Task/Pernicious-numbers/Tcl/pernicious-numbers.tcl @@ -0,0 +1,14 @@ +package require math::numtheory + +proc pernicious {n} { + ::math::numtheory::isprime [tcl::mathop::+ {*}[split [format %b $n] ""]] +} + +for {set n 0;set p {}} {[llength $p] < 25} {incr n} { + if {[pernicious $n]} {lappend p $n} +} +puts [join $p ","] +for {set n 888888877; set p {}} {$n <= 888888888} {incr n} { + if {[pernicious $n]} {lappend p $n} +} +puts [join $p ","] diff --git a/Task/Phrase-reversals/00DESCRIPTION b/Task/Phrase-reversals/00DESCRIPTION new file mode 100644 index 0000000000..9edd77576a --- /dev/null +++ b/Task/Phrase-reversals/00DESCRIPTION @@ -0,0 +1,12 @@ +Given a string of space separated words containing the following phrase: +:''"rosetta code phrase reversal"'' + +# Reverse the string. +# Reverse each individual word in the string, maintaining original string order. +# Reverse the order of each word of the phrase, maintaining the order of characters in each word. + +Show your output here. + +;See also: +* [[Reverse a string]] +* [[Reverse words in a string]] diff --git a/Task/Phrase-reversals/AWK/phrase-reversals.awk b/Task/Phrase-reversals/AWK/phrase-reversals.awk new file mode 100644 index 0000000000..ff3c2c88ab --- /dev/null +++ b/Task/Phrase-reversals/AWK/phrase-reversals.awk @@ -0,0 +1,18 @@ +# Usage: awk -f phrase_revers.awk +function rev(s, del, n,i,a,r) { + n = split(s, a, del) + r = a[1] + for(i=2; i <= n; i++) {r = a[i] del r } + return r +} + +BEGIN { + p0 = "Rosetta Code Phrase Reversal" + + fmt = "%-20s: %s\n" + printf( fmt, "input", p0 ) + printf( fmt, "string reversed", rev(p0, "") ) + wr = rev(p0, " ") + printf( fmt, "word-order reversed", wr ) + printf( fmt, "each word reversed", rev(wr) ) +} diff --git a/Task/Phrase-reversals/Ada/phrase-reversals.ada b/Task/Phrase-reversals/Ada/phrase-reversals.ada new file mode 100644 index 0000000000..650d17977a --- /dev/null +++ b/Task/Phrase-reversals/Ada/phrase-reversals.ada @@ -0,0 +1,43 @@ + S'Last then -- Word holds the last word + return Reverse_String(Word); + else + return Reverse_String(Word) & " " & Reverse_Words(S(Cursor .. S'Last)); + end if; + end Reverse_Words; + + function Reverse_Order(S: String) return String is + Cursor: Positive := S'First; + Word: String := Simple_Parse.Next_Word(S, Cursor); + begin + if Cursor > S'Last then -- Word holds the last word + return Word; + else + return Reverse_Order(S(Cursor .. S'Last)) & " " & Word; + end if; + end Reverse_Order; + + Phrase: String := "rosetta code phrase reversal"; + use Ada.Text_IO; +begin + Put_Line("0. The original phrase: """ & Phrase & """"); + Put_Line("1. Reverse the entire phrase: """ & Reverse_String(Phrase) & """"); + Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """"); + Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """"); +end Phrase_Reversal; diff --git a/Task/Phrase-reversals/AutoHotkey/phrase-reversals.ahk b/Task/Phrase-reversals/AutoHotkey/phrase-reversals.ahk new file mode 100644 index 0000000000..5b9006758f --- /dev/null +++ b/Task/Phrase-reversals/AutoHotkey/phrase-reversals.ahk @@ -0,0 +1,34 @@ +var = +( +Rosetta Code Phrase Reversal +) + +array := strsplit(var, " ") + +loop, % array.maxindex() + string .= array[array.maxindex() - A_index + 1] . " " + +loop, % array.maxindex() +{ + m := array[A_index] + array2 := strsplit(m, "") + Loop, % array2.maxindex() + string2 .= array2[array2.maxindex() - A_index + 1] + string2 .= " " +} + +array := strsplit(string, " " ) + +loop, % array.maxindex() +{ + m := array[A_index] + array3 := strsplit(m, "") + Loop, % array3.maxindex() + string3 .= array3[array3.maxindex() - A_index + 1] + string3 .= " " +} + +MsgBox % var . "`n" . string3 . "`n" . String . "`n" . string2 +ExitApp + +esc::ExitApp diff --git a/Task/Phrase-reversals/Bracmat/phrase-reversals.bracmat b/Task/Phrase-reversals/Bracmat/phrase-reversals.bracmat new file mode 100644 index 0000000000..9d78446718 --- /dev/null +++ b/Task/Phrase-reversals/Bracmat/phrase-reversals.bracmat @@ -0,0 +1,16 @@ +( "rosetta code phrase reversal":?text +& rev$!text:?output1 +& get$(!text,MEM):?words +& :?output2:?output3 +& whl + ' ( !words:%?word %?words + & !output2 rev$!word " ":?output2 + & " " !word !output3:?output3 + ) +& str$(!output2 rev$!words):?output2 +& str$(!words !output3):?output3 +& out + $ ( str + $ ("0:\"" !text "\"\n1:\"" !output1 "\"\n2:\"" !output2 "\"\n3:\"" !output3 \"\n) + ) +); diff --git a/Task/Phrase-reversals/C++/phrase-reversals.cpp b/Task/Phrase-reversals/C++/phrase-reversals.cpp new file mode 100644 index 0000000000..93cff86dcb --- /dev/null +++ b/Task/Phrase-reversals/C++/phrase-reversals.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include + +void string_to_vector ( const std::string & input , std::vector & words ) { + boost::tokenizer<> tok( input ) ; + for ( boost::tokenizer<>::iterator beg = tok.begin( ) ; beg != tok.end( ) ; ++beg ) + words.push_back( *beg ) ; +} + +int main( ) { + std::string startphrase ( "rosetta code phrase reversal" ) ; + std::cout << "Input : " << startphrase << '\n' ; + std::string local_copy ( startphrase ) ; + std::reverse ( local_copy.begin( ) , local_copy.end( ) ) ; + std::cout << "Input reversed : " << local_copy << '\n' ; + std::vector words ; + string_to_vector ( startphrase , words ) ; + //copy the vector with the original words to reverse their order later + std::vector original_words ( words ) ; + //reverse each word in the string + std::cout << "Each word reversed : " ; + for ( std::string word : words ) { + std::reverse ( word.begin( ) , word.end( ) ) ; + std::cout << word << " " ; + } + std::cout << '\n' ; + std::cout << "Original word order reversed : " ; + for ( std::vector::const_reverse_iterator cri = original_words.rbegin( ) ; + cri != original_words.rend( ) ; cri++ ) { + std::cout << *cri << " " ; + } + std::cout << '\n' ; + return 0 ; +} diff --git a/Task/Phrase-reversals/C/phrase-reversals.c b/Task/Phrase-reversals/C/phrase-reversals.c new file mode 100644 index 0000000000..986c534a3a --- /dev/null +++ b/Task/Phrase-reversals/C/phrase-reversals.c @@ -0,0 +1,70 @@ +#include +#include + +/* The functions used are destructive, so after each call the string needs + * to be copied over again. One could easily allocate new strings as + * required, but this way allows the caller to manage memory themselves */ + +char* reverse_section(char *s, size_t length) +{ + if (length == 0) return s; + + size_t i; char temp; + for (i = 0; i < length / 2 + 1; ++i) + temp = s[i], s[i] = s[length - i], s[length - i] = temp; + return s; +} + +char* reverse_words_in_order(char *s, char delim) +{ + if (!strlen(s)) return s; + + size_t i, j; + for (i = 0; i < strlen(s) - 1; ++i) { + for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j) + ; + reverse_section(s + i, j - 1); + s += j; + } + return s; +} + +char* reverse_string(char *s) +{ + return strlen(s) ? reverse_section(s, strlen(s) - 1) : s; +} + +char* reverse_order_of_words(char *s, char delim) +{ + reverse_string(s); + reverse_words_in_order(s, delim); + return s; +} + +int main(void) +{ + char str[] = "rosetta code phrase reversal"; + size_t lenstr = sizeof(str) / sizeof(str[0]); + char scopy[lenstr]; + char delim = ' '; + + /* Original String */ + printf("Original: \"%s\"\n", str); + + /* Reversed string */ + strncpy(scopy, str, lenstr); + reverse_string(scopy); + printf("Reversed: \"%s\"\n", scopy); + + /* Reversed words in string */ + strncpy(scopy, str, lenstr); + reverse_words_in_order(scopy, delim); + printf("Reversed words: \"%s\"\n", scopy); + + /* Reversed order of words in string */ + strncpy(scopy, str, lenstr); + reverse_order_of_words(scopy, delim); + printf("Reversed order: \"%s\"\n", scopy); + + return 0; +} diff --git a/Task/Phrase-reversals/D/phrase-reversals.d b/Task/Phrase-reversals/D/phrase-reversals.d new file mode 100644 index 0000000000..7427ffe1f2 --- /dev/null +++ b/Task/Phrase-reversals/D/phrase-reversals.d @@ -0,0 +1,8 @@ +void main() @safe { + import std.stdio, std.range, std.algorithm; + + immutable phrase = "rosetta code phrase reversal"; + phrase.retro.writeln; // Reversed string. + phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed. + phrase.split.retro.joiner(" ").writeln; // Word order reversed. +} diff --git a/Task/Phrase-reversals/Go/phrase-reversals-1.go b/Task/Phrase-reversals/Go/phrase-reversals-1.go new file mode 100644 index 0000000000..59d59314f7 --- /dev/null +++ b/Task/Phrase-reversals/Go/phrase-reversals-1.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "strings" +) + +const phrase = "rosetta code phrase reversal" + +func revStr(s string) string { + rs := make([]rune, len(s)) + i := len(s) + for _, r := range s { + i-- + rs[i] = r + } + return string(rs[i:]) +} + +func main() { + fmt.Println("Reversed: ", revStr(phrase)) + + ws := strings.Fields(phrase) + for i, w := range ws { + ws[i] = revStr(w) + } + fmt.Println("Words reversed: ", strings.Join(ws, " ")) + + ws = strings.Fields(phrase) + last := len(ws) - 1 + for i, w := range ws[:len(ws)/2] { + ws[i], ws[last-i] = ws[last-i], w + } + fmt.Println("Word order reversed:", strings.Join(ws, " ")) +} diff --git a/Task/Phrase-reversals/Go/phrase-reversals-2.go b/Task/Phrase-reversals/Go/phrase-reversals-2.go new file mode 100644 index 0000000000..0fa1eb5bb3 --- /dev/null +++ b/Task/Phrase-reversals/Go/phrase-reversals-2.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "regexp" + "sort" + "strings" +) + +const phrase = "rosetta code phrase reversal" + +type reversible interface { + Len() int + Swap(i, j int) +} + +func reverse(p reversible) { + mid := p.Len() / 2 + last := p.Len() - 1 + for i := 0; i < mid; i++ { + p.Swap(i, last-i) + } +} + +type runeSlice []rune + +func (p runeSlice) Len() int { return len(p) } +func (p runeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +func reverseString(s string) string { + r := runeSlice(s) + reverse(r) + return string(r) +} + +var rx = regexp.MustCompile(`\S*`) + +func reverseWords(s string) string { + return rx.ReplaceAllStringFunc(s, func(m string) string { + return reverseString(m) + }) +} + +func reverseWordOrder(s string) string { + l := sort.StringSlice(strings.Fields(s)) + reverse(l) + return strings.Join(l, " ") +} + +func main() { + fmt.Println("Reversed: ", reverseString(phrase)) + fmt.Println("Words reversed: ", reverseWords(phrase)) + fmt.Println("Word order reversed:", reverseWordOrder(phrase)) +} diff --git a/Task/Phrase-reversals/Groovy/phrase-reversals.groovy b/Task/Phrase-reversals/Groovy/phrase-reversals.groovy new file mode 100644 index 0000000000..42dbf9c99e --- /dev/null +++ b/Task/Phrase-reversals/Groovy/phrase-reversals.groovy @@ -0,0 +1,7 @@ +def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')} + +def text = 'rosetta code phrase reversal' +println "Original: $text" +println "Reversed: ${phaseReverse(text) { it.reverse().collect { it.reverse() } } }" +println "Reversed Words: ${phaseReverse(text) { it.collect { it.reverse() } } }" +println "Reversed Order: ${phaseReverse(text) { it.reverse() } }" diff --git a/Task/Phrase-reversals/Haskell/phrase-reversals.hs b/Task/Phrase-reversals/Haskell/phrase-reversals.hs new file mode 100644 index 0000000000..7e028929ea --- /dev/null +++ b/Task/Phrase-reversals/Haskell/phrase-reversals.hs @@ -0,0 +1,6 @@ +phrase = "rosetta code phrase reversal" + +main = do + putStrLn $ reverse phrase + putStrLn $ unwords . map reverse . words $ phrase + putStrLn $ unwords . reverse . words $ phrase diff --git a/Task/Phrase-reversals/J/phrase-reversals-1.j b/Task/Phrase-reversals/J/phrase-reversals-1.j new file mode 100644 index 0000000000..1ad0d3c8c3 --- /dev/null +++ b/Task/Phrase-reversals/J/phrase-reversals-1.j @@ -0,0 +1,4 @@ + getWords=: (' '&splitstring) :. (' '&joinstring) + reverseString=: |. + reverseWords=: |.&.>&.getWords + reverseWordOrder=: |.&.getWords diff --git a/Task/Phrase-reversals/J/phrase-reversals-2.j b/Task/Phrase-reversals/J/phrase-reversals-2.j new file mode 100644 index 0000000000..3d37e28436 --- /dev/null +++ b/Task/Phrase-reversals/J/phrase-reversals-2.j @@ -0,0 +1,5 @@ + phrase=: 'rosetta code phrase reversal' + (reverseWordOrder , reverseWords ,: reverseString) phrase +reversal phrase code rosetta +attesor edoc esarhp lasrever +lasrever esarhp edoc attesor diff --git a/Task/Phrase-reversals/Java/phrase-reversals.java b/Task/Phrase-reversals/Java/phrase-reversals.java new file mode 100644 index 0000000000..52110bd73b --- /dev/null +++ b/Task/Phrase-reversals/Java/phrase-reversals.java @@ -0,0 +1,36 @@ +import java.util.Arrays; + +public class PhraseRev{ + private static String reverse(String x){ + return new StringBuilder(x).reverse().toString(); + } + + private static T[] reverse(T[] x){ + T[] rev = Arrays.copyOf(x, x.length); + for(int i = x.length - 1; i >= 0; i--){ + rev[x.length - 1 - i] = x[i]; + } + return rev; + } + + private static String join(String[] arr, String joinStr){ + StringBuilder joined = new StringBuilder(); + for(int i = 0; i < arr.length; i++){ + joined.append(arr[i]); + if(i < arr.length - 1) joined.append(joinStr); + } + return joined.toString(); + } + + public static void main(String[] args){ + String str = "rosetta code phrase reversal"; + + System.out.println("Straight-up reversed: " + reverse(str)); + String[] words = str.split(" "); + for(int i = 0; i < words.length; i++){ + words[i] = reverse(words[i]); + } + System.out.println("Reversed words: " + join(words, " ")); + System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " ")); + } +} diff --git a/Task/Phrase-reversals/Mathematica/phrase-reversals.math b/Task/Phrase-reversals/Mathematica/phrase-reversals.math new file mode 100644 index 0000000000..72b90cb905 --- /dev/null +++ b/Task/Phrase-reversals/Mathematica/phrase-reversals.math @@ -0,0 +1,13 @@ +phrase = "Rosetta Code Phrase Reversal"; + +reverseWords[phrase_String] := + StringJoin @@ Riffle[Reverse@StringSplit@phrase, " "] + +reverseLetters[phrase_String] := + + StringJoin @@ + Riffle[Map[StringJoin @@ Reverse[Characters@#] &, + StringSplit@phrase], " "] + +{phrase, reverseWords@phrase, reverseLetters@phrase, + reverseWords@reverseLetters@phrase} // TableForm diff --git a/Task/Phrase-reversals/PHP/phrase-reversals.php b/Task/Phrase-reversals/PHP/phrase-reversals.php new file mode 100644 index 0000000000..c44fea1205 --- /dev/null +++ b/Task/Phrase-reversals/PHP/phrase-reversals.php @@ -0,0 +1,28 @@ +=0; $i--) + $str_word_order_reversed .= $temp[$i]." "; + +// Show the reversal of the word order while leaving the words in order +echo "Word order reversed: ".$str_word_order_reversed."\n"; diff --git a/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 b/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 new file mode 100644 index 0000000000..8d02db3d7c --- /dev/null +++ b/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 @@ -0,0 +1,6 @@ +my $s = 'rosetta code phrase reversal'; + +say 'Input : ', $s; +say 'String reversed : ', $s.flip; +say 'Each word reversed : ', $s.words».flip; +say 'Word-order reversed : ', $s.words.reverse; diff --git a/Task/Phrase-reversals/Perl/phrase-reversals.pl b/Task/Phrase-reversals/Perl/phrase-reversals.pl new file mode 100644 index 0000000000..157404e13d --- /dev/null +++ b/Task/Phrase-reversals/Perl/phrase-reversals.pl @@ -0,0 +1,9 @@ +my $s = "rosetta code phrase reversal"; +my $rev_s = reverse($s); +my $rev_ew = join(" ", reverse split(/ /,reverse $s)); +my $rev_wo = join(" ", reverse split(/ /,$s)); + +printf "0. %-20s: %s\n", "input", $s; +printf "1. %-20s: %s\n", "string reversed", $rev_s; +printf "2. %-20s: %s\n", "each word reversed", $rev_ew; +printf "3. %-20s: %s\n", "word-order reversed", $rev_wo; diff --git a/Task/Phrase-reversals/Python/phrase-reversals.py b/Task/Phrase-reversals/Python/phrase-reversals.py new file mode 100644 index 0000000000..ec89d1e698 --- /dev/null +++ b/Task/Phrase-reversals/Python/phrase-reversals.py @@ -0,0 +1,8 @@ +>>> phrase = "rosetta code phrase reversal" +>>> phrase[::-1] # Reversed. +'lasrever esarhp edoc attesor' +>>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed. +'attesor edoc esarhp lasrever' +>>> ' '.join(word for word in phrase.split()[::-1]) # Word order reversed. +'reversal phrase code rosetta' +>>> diff --git a/Task/Phrase-reversals/README b/Task/Phrase-reversals/README new file mode 100644 index 0000000000..7fc3ca5db4 --- /dev/null +++ b/Task/Phrase-reversals/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Phrase_reversals diff --git a/Task/Phrase-reversals/REXX/phrase-reversals-1.rexx b/Task/Phrase-reversals/REXX/phrase-reversals-1.rexx new file mode 100644 index 0000000000..ee90674d50 --- /dev/null +++ b/Task/Phrase-reversals/REXX/phrase-reversals-1.rexx @@ -0,0 +1,16 @@ +s='rosetta code phrase reversal' +r1=reverse(s) +r2='' +Do i=1 To words(s) + r2=r2 reverse(word(s,i)) + End +r2=strip(r2) +r3='' +Do i=words(s) To 1 By -1 + r3=r3 word(s,i) + End +r3=strip(r3) +Say "input : " s +say "string reversed : " r1 +say "each word reversed : " r2 +say "word-order reversed : " r3 diff --git a/Task/Phrase-reversals/REXX/phrase-reversals-2.rexx b/Task/Phrase-reversals/REXX/phrase-reversals-2.rexx new file mode 100644 index 0000000000..8c1c87dbe6 --- /dev/null +++ b/Task/Phrase-reversals/REXX/phrase-reversals-2.rexx @@ -0,0 +1,9 @@ +/*REXX pgm reverses words and/or letters in a string in various ways. */ +i=; p=; parse arg $; if $='' then $="rosetta code phrase reversal" + do j=1 for words($); _=word($,j) + i=i reverse(_) ; p=_ p + end /*j*/ +say ' the original phrase used: ' $ +say ' original phrase reversed: ' reverse($) +say 'reversed individual words: ' strip(i) +say 'reversed words in phrases: ' p /*stick a fork in it, we're done.*/ diff --git a/Task/Phrase-reversals/Racket/phrase-reversals.rkt b/Task/Phrase-reversals/Racket/phrase-reversals.rkt new file mode 100644 index 0000000000..f4f8ad8651 --- /dev/null +++ b/Task/Phrase-reversals/Racket/phrase-reversals.rkt @@ -0,0 +1,12 @@ +#lang racket/base +(require + (only-in srfi/13 string-reverse) + (only-in racket/string string-split string-join)) + +(define (phrase-reversal s) + (list + (string-reverse s) + (string-join (map string-reverse (string-split s))) + (string-join (reverse (string-split s))))) + +(for-each displayln (phrase-reversal "rosetta code phrase reversal")) diff --git a/Task/Phrase-reversals/Ruby/phrase-reversals.rb b/Task/Phrase-reversals/Ruby/phrase-reversals.rb new file mode 100644 index 0000000000..f8116b59f3 --- /dev/null +++ b/Task/Phrase-reversals/Ruby/phrase-reversals.rb @@ -0,0 +1,5 @@ +str = "rosetta code phrase reversal" + +puts str.reverse # Reversed string. +puts str.split.map(&:reverse).join(" ") # Words reversed. +puts str.split.reverse.join(" ") # Word order reversed. diff --git a/Task/Phrase-reversals/Tcl/phrase-reversals.tcl b/Task/Phrase-reversals/Tcl/phrase-reversals.tcl new file mode 100644 index 0000000000..e4848f8710 --- /dev/null +++ b/Task/Phrase-reversals/Tcl/phrase-reversals.tcl @@ -0,0 +1,7 @@ +set s "rosetta code phrase reversal" +# Reverse all characters +puts [string reverse $s] +# Reverse characters in each word +puts [lmap word $s {string reverse $word}] +# Reverse the words but not the characters +puts [lreverse $s] diff --git a/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-1.sh b/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-1.sh new file mode 100644 index 0000000000..34f0ab53ad --- /dev/null +++ b/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-1.sh @@ -0,0 +1,14 @@ +s1="rosetta code phrase reversal" +echo "Original string ----------------------> "$s1 + +echo -n "1.) Reverse the string ---------------> " +echo $s1|rev + +echo -n "2.) Reverse characters of each word --> " +echo $s1|tr " " "\n"|rev|tr "\n" " ";echo + +echo -n "3.) Reverse word order ---------------> " +word_num=$(echo $s1|wc -w) +while [ $word_num != 0 ];do +echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " +word_num=$(expr $word_num - 1);done;echo diff --git a/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-2.sh b/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-2.sh new file mode 100644 index 0000000000..45194cba99 --- /dev/null +++ b/Task/Phrase-reversals/UNIX-Shell/phrase-reversals-2.sh @@ -0,0 +1,26 @@ +s1="rosetta code phrase reversal" +echo "Original string --> "$s1 + +echo -n "1.) Reverse the string --> " +length=$(echo $s1|wc -c) +while [ $length != 0 ];do +echo $s1|cut -c$length|tr -d "\n" +length=$(expr $length - 1) +done;echo + +echo -n "2.) Reverse characters of each word --> " +word_quantity=$(echo $s1|wc -w) +word_quantity=$(expr $word_quantity + 1) +word_num=1 +while [ $word_num != $word_quantity ];do +length=$(echo $s1|cut -d " " -f $word_num|wc -c) +while [ $length != 0 ];do +echo $s1|cut -d " " -f $word_num|cut -c$length|tr -d "\n" +length=$(expr $length - 1);done;echo -n " " +word_num=$(expr $word_num + 1);done;echo + +echo -n "3.) Reverse word order --> " +word_num=$(echo $s1|wc -w) +while [ $word_num != 0 ];do +echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " +word_num=$(expr $word_num - 1);done;echo diff --git a/Task/Quickselect-algorithm/00DESCRIPTION b/Task/Quickselect-algorithm/00DESCRIPTION new file mode 100644 index 0000000000..ec98e0dedc --- /dev/null +++ b/Task/Quickselect-algorithm/00DESCRIPTION @@ -0,0 +1,5 @@ +Use the [[wp:Quickselect|quickselect algorithm]] on the vector +: [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] +To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. + +* Note: Quick''sort'' has a separate [[Sorting algorithms/Quicksort|task]]. diff --git a/Task/Quickselect-algorithm/AutoHotkey/quickselect-algorithm.ahk b/Task/Quickselect-algorithm/AutoHotkey/quickselect-algorithm.ahk new file mode 100644 index 0000000000..89c109c08b --- /dev/null +++ b/Task/Quickselect-algorithm/AutoHotkey/quickselect-algorithm.ahk @@ -0,0 +1,39 @@ +MyList := [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] +Loop, 10 + Out .= Select(MyList, 1, MyList.MaxIndex(), A_Index) (A_Index = MyList.MaxIndex() ? "" : ", ") +MsgBox, % Out +return + +Partition(List, Left, Right, PivotIndex) { + PivotValue := List[PivotIndex] + , Swap(List, pivotIndex, Right) + , StoreIndex := Left + , i := Left - 1 + Loop, % Right - Left + if (List[j := i + A_Index] <= PivotValue) + Swap(List, StoreIndex, j) + , StoreIndex++ + Swap(List, Right, StoreIndex) + return StoreIndex +} + +Select(List, Left, Right, n) { + if (Left = Right) + return List[Left] + Loop { + PivotIndex := (Left + Right) // 2 + , PivotIndex := Partition(List, Left, Right, PivotIndex) + if (n = PivotIndex) + return List[n] + else if (n < PivotIndex) + Right := PivotIndex - 1 + else + Left := PivotIndex + 1 + } +} + +Swap(List, i1, i2) { + t := List[i1] + , List[i1] := List[i2] + , List[i2] := t +} diff --git a/Task/Quickselect-algorithm/C++/quickselect-algorithm-1.cpp b/Task/Quickselect-algorithm/C++/quickselect-algorithm-1.cpp new file mode 100644 index 0000000000..f97ad44f2c --- /dev/null +++ b/Task/Quickselect-algorithm/C++/quickselect-algorithm-1.cpp @@ -0,0 +1,14 @@ +#include +#include + +int main() { + for (int i = 0; i < 10; i++) { + int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; + std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); + std::cout << a[i]; + if (i < 9) std::cout << ", "; + } + std::cout << std::endl; + + return 0; +} diff --git a/Task/Quickselect-algorithm/C++/quickselect-algorithm-2.cpp b/Task/Quickselect-algorithm/C++/quickselect-algorithm-2.cpp new file mode 100644 index 0000000000..35df80f84b --- /dev/null +++ b/Task/Quickselect-algorithm/C++/quickselect-algorithm-2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include + +template +Iterator select(Iterator begin, Iterator end, int n) { + typedef typename std::iterator_traits::value_type T; + while (true) { + Iterator pivotIt = begin + std::rand() % std::distance(begin, end); + std::iter_swap(pivotIt, end-1); // Move pivot to end + pivotIt = std::partition(begin, end-1, std::bind2nd(std::less(), *(end-1))); + std::iter_swap(end-1, pivotIt); // Move pivot to its final place + if (n == pivotIt - begin) { + return pivotIt; + } else if (n < pivotIt - begin) { + end = pivotIt; + } else { + n -= pivotIt+1 - begin; + begin = pivotIt+1; + } + } +} + +int main() { + std::srand(std::time(NULL)); + for (int i = 0; i < 10; i++) { + int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; + std::cout << *select(a, a + sizeof(a)/sizeof(*a), i); + if (i < 9) std::cout << ", "; + } + std::cout << std::endl; + + return 0; +} diff --git a/Task/Quickselect-algorithm/C/quickselect-algorithm.c b/Task/Quickselect-algorithm/C/quickselect-algorithm.c new file mode 100644 index 0000000000..a49caf20d4 --- /dev/null +++ b/Task/Quickselect-algorithm/C/quickselect-algorithm.c @@ -0,0 +1,35 @@ +#include +#include + +int qselect(int *v, int len, int k) +{ +# define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } + int i, st, tmp; + + for (st = i = 0; i < len - 1; i++) { + if (v[i] > v[len-1]) continue; + SWAP(i, st); + st++; + } + + SWAP(len-1, st); + + return k == st ?v[st] + :st > k ? qselect(v, st, k) + : qselect(v + st, len - st, k - st); +} + +int main(void) +{ +# define N (sizeof(x)/sizeof(x[0])) + int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; + int y[N]; + + int i; + for (i = 0; i < 10; i++) { + memcpy(y, x, sizeof(x)); // qselect modifies array + printf("%d: %d\n", i, qselect(y, 10, i)); + } + + return 0; +} diff --git a/Task/Quickselect-algorithm/COBOL/quickselect-algorithm.cobol b/Task/Quickselect-algorithm/COBOL/quickselect-algorithm.cobol new file mode 100644 index 0000000000..ade2a66bda --- /dev/null +++ b/Task/Quickselect-algorithm/COBOL/quickselect-algorithm.cobol @@ -0,0 +1,95 @@ + CLASS-ID MainProgram. + + METHOD-ID Partition STATIC USING T. + CONSTRAINTS. + CONSTRAIN T IMPLEMENTS type IComparable. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 pivot-val T. + + PROCEDURE DIVISION USING VALUE arr AS T OCCURS ANY, + left-idx AS BINARY-LONG, right-idx AS BINARY-LONG, + pivot-idx AS BINARY-LONG + RETURNING ret AS BINARY-LONG. + MOVE arr (pivot-idx) TO pivot-val + INVOKE self::Swap(arr, pivot-idx, right-idx) + DECLARE store-idx AS BINARY-LONG = left-idx + PERFORM VARYING i AS BINARY-LONG FROM left-idx BY 1 + UNTIL i > right-idx + IF arr (i) < pivot-val + INVOKE self::Swap(arr, i, store-idx) + ADD 1 TO store-idx + END-IF + END-PERFORM + INVOKE self::Swap(arr, right-idx, store-idx) + + MOVE store-idx TO ret + END METHOD. + + METHOD-ID Quickselect STATIC USING T. + CONSTRAINTS. + CONSTRAIN T IMPLEMENTS type IComparable. + + PROCEDURE DIVISION USING VALUE arr AS T OCCURS ANY, + left-idx AS BINARY-LONG, right-idx AS BINARY-LONG, + n AS BINARY-LONG + RETURNING ret AS T. + IF left-idx = right-idx + MOVE arr (left-idx) TO ret + GOBACK + END-IF + + DECLARE rand AS TYPE Random = NEW Random() + DECLARE pivot-idx AS BINARY-LONG = rand::Next(left-idx, right-idx) + DECLARE pivot-new-idx AS BINARY-LONG + = self::Partition(arr, left-idx, right-idx, pivot-idx) + DECLARE pivot-dist AS BINARY-LONG = pivot-new-idx - left-idx + 1 + + EVALUATE TRUE + WHEN pivot-dist = n + MOVE arr (pivot-new-idx) TO ret + + WHEN n < pivot-dist + INVOKE self::Quickselect(arr, left-idx, pivot-new-idx - 1, n) + RETURNING ret + + WHEN OTHER + INVOKE self::Quickselect(arr, pivot-new-idx + 1, right-idx, + n - pivot-dist) RETURNING ret + END-EVALUATE + END METHOD. + + METHOD-ID Swap STATIC USING T. + CONSTRAINTS. + CONSTRAIN T IMPLEMENTS type IComparable. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 temp T. + + PROCEDURE DIVISION USING arr AS T OCCURS ANY, + VALUE idx-1 AS BINARY-LONG, idx-2 AS BINARY-LONG. + IF idx-1 <> idx-2 + MOVE arr (idx-1) TO temp + MOVE arr (idx-2) TO arr (idx-1) + MOVE temp TO arr (idx-2) + END-IF + END METHOD. + + METHOD-ID Main STATIC. + PROCEDURE DIVISION. + DECLARE input-array AS BINARY-LONG OCCURS ANY + = TABLE OF BINARY-LONG(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) + DISPLAY "Loop quick select 10 times." + PERFORM VARYING i AS BINARY-LONG FROM 1 BY 1 UNTIL i > 10 + DISPLAY self::Quickselect(input-array, 1, input-array::Length, i) + NO ADVANCING + + IF i < 10 + DISPLAY ", " NO ADVANCING + END-IF + END-PERFORM + DISPLAY SPACE + END METHOD. + END CLASS. diff --git a/Task/Quickselect-algorithm/D/quickselect-algorithm-1.d b/Task/Quickselect-algorithm/D/quickselect-algorithm-1.d new file mode 100644 index 0000000000..46aa7ad1a3 --- /dev/null +++ b/Task/Quickselect-algorithm/D/quickselect-algorithm-1.d @@ -0,0 +1,9 @@ +void main() { + import std.stdio, std.algorithm; + + auto a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]; + foreach (immutable i; 0 .. a.length) { + a.topN(i); + write(a[i], " "); + } +} diff --git a/Task/Quickselect-algorithm/D/quickselect-algorithm-2.d b/Task/Quickselect-algorithm/D/quickselect-algorithm-2.d new file mode 100644 index 0000000000..69a13590e3 --- /dev/null +++ b/Task/Quickselect-algorithm/D/quickselect-algorithm-2.d @@ -0,0 +1,48 @@ +import std.stdio, std.random, std.algorithm, std.range; + +T quickSelect(T)(T[] arr, size_t n) +in { + assert(n < arr.length); +} body { + static size_t partition(T[] sub, in size_t pivot) pure nothrow + in { + assert(!sub.empty); + assert(pivot < sub.length); + } body { + auto pivotVal = sub[pivot]; + sub[pivot].swap(sub.back); + size_t storeIndex = 0; + foreach (ref si; sub[0 .. $ - 1]) { + if (si < pivotVal) { + si.swap(sub[storeIndex]); + storeIndex++; + } + } + sub.back.swap(sub[storeIndex]); + return storeIndex; + } + + size_t left = 0; + size_t right = arr.length - 1; + while (right > left) { + assert(left < arr.length); + assert(right < arr.length); + immutable pivotIndex = left + partition(arr[left .. right + 1], + uniform(0U, right - left + 1)); + if (pivotIndex - left == n) { + right = left = pivotIndex; + } else if (pivotIndex - left < n) { + n -= pivotIndex - left + 1; + left = pivotIndex + 1; + } else { + right = pivotIndex - 1; + } + } + + return arr[left]; +} + +void main() { + auto a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]; + a.length.iota.map!(i => a.quickSelect(i)).writeln; +} diff --git a/Task/Quickselect-algorithm/Go/quickselect-algorithm-1.go b/Task/Quickselect-algorithm/Go/quickselect-algorithm-1.go new file mode 100644 index 0000000000..9512fc3794 --- /dev/null +++ b/Task/Quickselect-algorithm/Go/quickselect-algorithm-1.go @@ -0,0 +1,41 @@ +package main + +import "fmt" + +func quickselect(list []int, k int) int { + for { + // partition + px := len(list) / 2 + pv := list[px] + last := len(list) - 1 + list[px], list[last] = list[last], list[px] + i := 0 + for j := 0; j < last; j++ { + if list[j] < pv { + list[i], list[j] = list[j], list[i] + i++ + } + } + // select + if i == k { + return pv + } + if k < i { + list = list[:i] + } else { + list[i], list[last] = list[last], list[i] + list = list[i+1:] + k -= i + 1 + } + } +} + +func main() { + for i := 0; ; i++ { + v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4} + if i == len(v) { + return + } + fmt.Println(quickselect(v, i)) + } +} diff --git a/Task/Quickselect-algorithm/Go/quickselect-algorithm-2.go b/Task/Quickselect-algorithm/Go/quickselect-algorithm-2.go new file mode 100644 index 0000000000..d36bea2d4b --- /dev/null +++ b/Task/Quickselect-algorithm/Go/quickselect-algorithm-2.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "sort" + "math/rand" +) + +func partition(a sort.Interface, first int, last int, pivotIndex int) int { + a.Swap(first, pivotIndex) // move it to beginning + left := first+1 + right := last + for left <= right { + for left <= last && a.Less(left, first) { + left++ + } + for right >= first && a.Less(first, right) { + right-- + } + if left <= right { + a.Swap(left, right) + left++ + right-- + } + } + a.Swap(first, right) // swap into right place + return right +} + +func quickselect(a sort.Interface, n int) int { + first := 0 + last := a.Len()-1 + for { + pivotIndex := partition(a, first, last, + rand.Intn(last - first + 1) + first) + if n == pivotIndex { + return pivotIndex + } else if n < pivotIndex { + last = pivotIndex-1 + } else { + first = pivotIndex+1 + } + } + panic("bad index") +} + +func main() { + for i := 0; ; i++ { + v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4} + if i == len(v) { + return + } + fmt.Println(v[quickselect(sort.IntSlice(v), i)]) + } +} diff --git a/Task/Quickselect-algorithm/Haskell/quickselect-algorithm.hs b/Task/Quickselect-algorithm/Haskell/quickselect-algorithm.hs new file mode 100644 index 0000000000..bf20f5440b --- /dev/null +++ b/Task/Quickselect-algorithm/Haskell/quickselect-algorithm.hs @@ -0,0 +1,13 @@ +import Data.List (partition) + +quickselect :: Ord a => Int -> [a] -> a +quickselect k (x:xs) | k < l = quickselect k ys + | k > l = quickselect (k-l-1) zs + | otherwise = x + where (ys, zs) = partition (< x) xs + l = length ys + +main :: IO () +main = do + let v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] + print $ map (\i -> quickselect i v) [0 .. length v-1] diff --git a/Task/Quickselect-algorithm/Icon/quickselect-algorithm.icon b/Task/Quickselect-algorithm/Icon/quickselect-algorithm.icon new file mode 100644 index 0000000000..2be74e0c1a --- /dev/null +++ b/Task/Quickselect-algorithm/Icon/quickselect-algorithm.icon @@ -0,0 +1,21 @@ +procedure main(A) + every writes(" ",select(1 to *A, A, 1, *A)|"\n") +end + +procedure select(k,A,min,max) + repeat { + pNI := partition(?(max-min)+min, A, min, max) + pD := pNI - min + 1 + if pD = k then return A[pNI] + if k < pD then max := pNI-1 + else (k -:= pD, min := pNI+1) + } +end + +procedure partition(pivot,A,min,max) + pV := (A[max] :=: A[pivot]) + sI := min + every A[i := min to max-1] <= pV do (A[sI] :=: A[i], sI +:= 1) + A[max] :=: A[sI] + return sI +end diff --git a/Task/Quickselect-algorithm/J/quickselect-algorithm-1.j b/Task/Quickselect-algorithm/J/quickselect-algorithm-1.j new file mode 100644 index 0000000000..e5b95bbec8 --- /dev/null +++ b/Task/Quickselect-algorithm/J/quickselect-algorithm-1.j @@ -0,0 +1,14 @@ +quickselect=:4 :0 + if. 0=#y do. _ return. end. + n=.?#y + m=.n{y + if. x < m do. + x quickselect (m>y)#y + else. + if. x > m do. + x quickselect (m> int partition(E[] arr, int left, int right, int pivot) { + E pivotVal = arr[pivot]; + swap(arr, pivot, right); + int storeIndex = left; + for (int i = left; i < right; i++) { + if (arr[i].compareTo(pivotVal) < 0) { + swap(arr, i, storeIndex); + storeIndex++; + } + } + swap(arr, right, storeIndex); + return storeIndex; + } + + private static > E select(E[] arr, int n) { + int left = 0; + int right = arr.length - 1; + Random rand = new Random(); + while (right >= left) { + int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left); + if (pivotIndex == n) { + return arr[pivotIndex]; + } else if (pivotIndex < n) { + left = pivotIndex + 1; + } else { + right = pivotIndex - 1; + } + } + return null; + } + + private static void swap(Object[] arr, int i1, int i2) { + if (i1 != i2) { + Object temp = arr[i1]; + arr[i1] = arr[i2]; + arr[i2] = temp; + } + } + + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; + System.out.print(select(input, i)); + if (i < 9) System.out.print(", "); + } + System.out.println(); + } + +} diff --git a/Task/Quickselect-algorithm/NetRexx/quickselect-algorithm.netrexx b/Task/Quickselect-algorithm/NetRexx/quickselect-algorithm.netrexx new file mode 100644 index 0000000000..6aeb54d90d --- /dev/null +++ b/Task/Quickselect-algorithm/NetRexx/quickselect-algorithm.netrexx @@ -0,0 +1,97 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +/** @see http://en.wikipedia.org/wiki/Quickselect */ + +runSample(arg) +return + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +method qpartition(list, ileft, iright, pivotIndex) private static + pivotValue = list[pivotIndex] + list = swap(list, pivotIndex, iright) -- Move pivot to end + storeIndex = ileft + loop i_ = ileft to iright - 1 + if list[i_] <= pivotValue then do + list = swap(list, storeIndex, i_) + storeIndex = storeIndex + 1 + end + end i_ + list = swap(list, iright, storeIndex) -- Move pivot to its final place + return storeIndex + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +method qselectInPlace(list, k_, ileft = -1, iright = -1) public static + if ileft = -1 then ileft = 1 + if iright = -1 then iright = list[0] + + loop label inplace forever + pivotIndex = Random().nextInt(iright - ileft + 1) + ileft -- select pivotIndex between left and right + pivotNewIndex = qpartition(list, ileft, iright, pivotIndex) + pivotDist = pivotNewIndex - ileft + 1 + select + when pivotDist = k_ then do + returnVal = list[pivotNewIndex] + leave inplace + end + when k_ < pivotDist then + iright = pivotNewIndex - 1 + otherwise do + k_ = k_ - pivotDist + ileft = pivotNewIndex + 1 + end + end + end inplace + return returnVal + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +method swap(list, i1, i2) private static + if i1 \= i2 then do + t1 = list[i1] + list[i1] = list[i2] + list[i2] = t1 + end + return list + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg samplelist + if samplelist = '' | samplelist = '.' then samplelist = 9 8 7 6 5 0 1 2 3 4 + items = samplelist.words + say 'Input:' + say ' 'samplelist.space(1, ',').changestr(',', ', ') + say + + say 'Using in-place version of the algorithm:' + iv = '' + loop k_ = 1 to items + iv = iv qselectInPlace(buildIndexedString(samplelist), k_) + end k_ + say ' 'iv.space(1, ',').changestr(',', ', ') + say + + say 'Find the 4 smallest:' + iv = '' + loop k_ = 1 to 4 + iv = iv qselectInPlace(buildIndexedString(samplelist), k_) + end k_ + say ' 'iv.space(1, ',').changestr(',', ', ') + say + + say 'Find the 3 largest:' + iv = '' + loop k_ = items - 2 to items + iv = iv qselectInPlace(buildIndexedString(samplelist), k_) + end k_ + say ' 'iv.space(1, ',').changestr(',', ', ') + say + + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method buildIndexedString(samplelist) private static + list = 0 + list[0] = samplelist.words() + loop k_ = 1 to list[0] + list[k_] = samplelist.word(k_) + end k_ + return list diff --git a/Task/Quickselect-algorithm/OCaml/quickselect-algorithm.ocaml b/Task/Quickselect-algorithm/OCaml/quickselect-algorithm.ocaml new file mode 100644 index 0000000000..e641ccb051 --- /dev/null +++ b/Task/Quickselect-algorithm/OCaml/quickselect-algorithm.ocaml @@ -0,0 +1,10 @@ +let rec quickselect k = function + [] -> failwith "empty" + | x :: xs -> let ys, zs = List.partition ((>) x) xs in + let l = List.length ys in + if k < l then + quickselect k ys + else if k > l then + quickselect (k-l-1) zs + else + x diff --git a/Task/Quickselect-algorithm/PARI-GP/quickselect-algorithm.pari b/Task/Quickselect-algorithm/PARI-GP/quickselect-algorithm.pari new file mode 100644 index 0000000000..62a25be222 --- /dev/null +++ b/Task/Quickselect-algorithm/PARI-GP/quickselect-algorithm.pari @@ -0,0 +1,28 @@ +part(list, left, right, pivotIndex)={ + my(pivotValue=list[pivotIndex],storeIndex=left,t); + t=list[pivotIndex]; + list[pivotIndex]=list[right]; + list[right]=t; + for(i=left,right-1, + if(list[i] <= pivotValue, + t=list[storeIndex]; + list[storeIndex]=list[i]; + list[i]=t; + storeIndex++ + ) + ); + t=list[right]; + list[right]=list[storeIndex]; + list[storeIndex]=t; + storeIndex +}; +quickselect(list, left, right, n)={ + if(left==right,return(list[left])); + my(pivotIndex=part(list, left, right, random(right-left)+left)); + if(pivotIndex==n,return(list[n])); + if(n < pivotIndex, + quickselect(list, left, pivotIndex - 1, n) + , + quickselect(list, pivotIndex + 1, right, n) + ) +}; diff --git a/Task/Quickselect-algorithm/PL-I/quickselect-algorithm.pli b/Task/Quickselect-algorithm/PL-I/quickselect-algorithm.pli new file mode 100644 index 0000000000..466d3b5522 --- /dev/null +++ b/Task/Quickselect-algorithm/PL-I/quickselect-algorithm.pli @@ -0,0 +1,59 @@ +quick: procedure options (main); /* 4 April 2014 */ + +partition: procedure (list, left, right, pivot_Index) returns (fixed binary); + declare list (*) fixed binary; + declare (left, right, pivot_index) fixed binary; + declare (store_index, pivot_value) fixed binary; + declare I fixed binary; + + pivot_Value = list(pivot_Index); + call swap (pivot_Index, right); /* Move pivot to end */ + store_Index = left; + do i = left to right-1; + if list(i) < pivot_Value then + do; + call swap (store_Index, i); + store_Index = store_index + 1; + end; + end; + call swap (right, store_Index); /* Move pivot to its final place */ + return (store_Index); + +swap: procedure (i, j); + declare (i, j) fixed binary; declare t fixed binary; + + t = list(i); list(i) = list(j); list(j) = t; +end swap; +end partition; + +/* Returns the n-th smallest element of list within left..right inclusive */ +/* (i.e. left <= n <= right). */ +quick_select: procedure (list, left, right, n) recursive returns (fixed binary); + declare list(*) fixed binary; + declare (left, right, n) fixed binary; + declare pivot_index fixed binary; + + if left = right then /* If the list contains only one element */ + return ( list(left) ); /* Return that element */ + pivot_Index = (left+right)/2; + /* select a pivot_Index between left and right, */ + /* e.g. left + Math.floor(Math.random() * (right - left + 1)) */ + pivot_Index = partition(list, left, right, pivot_Index); + /* The pivot is in its final sorted position. */ + if n = pivot_Index then + return ( list(n) ); + else if n < pivot_Index then + return ( quick_select(list, left, pivot_Index - 1, n) ); + else + return ( quick_select(list, pivot_Index + 1, right, n) ); + +end quick_select; + + declare a(10) fixed binary static initial (9, 8, 7, 6, 5, 0, 1, 2, 3, 4); + declare I fixed binary; + + do i = 1 to 10; + put skip edit ('The ', trim(i), '-th element is ', quick_select((a), 1, 10, (i) )) (a); + end; + +end quick; diff --git a/Task/Quickselect-algorithm/Perl-6/quickselect-algorithm.pl6 b/Task/Quickselect-algorithm/Perl-6/quickselect-algorithm.pl6 new file mode 100644 index 0000000000..1b03c0d1bb --- /dev/null +++ b/Task/Quickselect-algorithm/Perl-6/quickselect-algorithm.pl6 @@ -0,0 +1,42 @@ +my @v = <9 8 7 6 5 0 1 2 3 4>; +say map { select(@v, $_) }, 1 .. 10; + +sub partition(@vector, $left, $right, $pivot-index) { + my $pivot-value = @vector[$pivot-index]; + @vector[$pivot-index, $right] = @vector[$right, $pivot-index]; + my $store-index = $left; + for $left ..^ $right -> $i { + if @vector[$i] < $pivot-value { + @vector[$store-index, $i] = @vector[$i, $store-index]; + $store-index++; + } + } + @vector[$right, $store-index] = @vector[$store-index, $right]; + return $store-index; +} + +sub select( @vector, + \k where 1 .. @vector, + \l where 0 .. @vector = 0, + \r where l .. @vector = @vector.end ) { + + my ($k, $left, $right) = k, l, r; + + loop { + my $pivot-index = ($left..$right).pick; + my $pivot-new-index = partition(@vector, $left, $right, $pivot-index); + my $pivot-dist = $pivot-new-index - $left + 1; + given $pivot-dist <=> $k { + when Same { + return @vector[$pivot-new-index]; + } + when Decrease { + $right = $pivot-new-index - 1; + } + when Increase { + $k -= $pivot-dist; + $left = $pivot-new-index + 1; + } + } + } +} diff --git a/Task/Quickselect-algorithm/Perl/quickselect-algorithm.pl b/Task/Quickselect-algorithm/Perl/quickselect-algorithm.pl new file mode 100644 index 0000000000..2fe002da1c --- /dev/null +++ b/Task/Quickselect-algorithm/Perl/quickselect-algorithm.pl @@ -0,0 +1,19 @@ +my @list = qw(9 8 7 6 5 0 1 2 3 4); +print join ' ', map { qselect(\@list, $_) } 1 .. 10 and print "\n"; + +sub qselect +{ + my ($list, $k) = @_; + my $pivot = @$list[int rand @{ $list } - 1]; + my @left = grep { $_ < $pivot } @$list; + my @right = grep { $_ > $pivot } @$list; + if ($k <= @left) + { + return qselect(\@left, $k); + } + elsif ($k > @left + 1) + { + return qselect(\@right, $k - @left - 1); + } + else { $pivot } +} diff --git a/Task/Quickselect-algorithm/Python/quickselect-algorithm.py b/Task/Quickselect-algorithm/Python/quickselect-algorithm.py new file mode 100644 index 0000000000..6a1d1586d0 --- /dev/null +++ b/Task/Quickselect-algorithm/Python/quickselect-algorithm.py @@ -0,0 +1,45 @@ +import random + +def partition(vector, left, right, pivotIndex): + pivotValue = vector[pivotIndex] + vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] # Move pivot to end + storeIndex = left + for i in range(left, right): + if vector[i] < pivotValue: + vector[storeIndex], vector[i] = vector[i], vector[storeIndex] + storeIndex += 1 + vector[right], vector[storeIndex] = vector[storeIndex], vector[right] # Move pivot to its final place + return storeIndex + +def _select(vector, left, right, k): + "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." + while True: + pivotIndex = random.randint(left, right) # select pivotIndex between left and right + pivotNewIndex = partition(vector, left, right, pivotIndex) + pivotDist = pivotNewIndex - left + if pivotDist == k: + return vector[pivotNewIndex] + elif k < pivotDist: + right = pivotNewIndex - 1 + else: + k -= pivotDist + 1 + left = pivotNewIndex + 1 + +def select(vector, k, left=None, right=None): + """\ + Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1]. + left, right default to (0, len(vector) - 1) if omitted + """ + if left is None: + left = 0 + lv1 = len(vector) - 1 + if right is None: + right = lv1 + assert vector and k >= 0, "Either null vector or k < 0 " + assert 0 <= left <= lv1, "left is out of range" + assert left <= right <= lv1, "right is out of range" + return _select(vector, left, right, k) + +if __name__ == '__main__': + v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] + print([select(v, i) for i in range(10)]) diff --git a/Task/Quickselect-algorithm/README b/Task/Quickselect-algorithm/README new file mode 100644 index 0000000000..bdf8803c08 --- /dev/null +++ b/Task/Quickselect-algorithm/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Quickselect_algorithm diff --git a/Task/Quickselect-algorithm/REXX/quickselect-algorithm.rexx b/Task/Quickselect-algorithm/REXX/quickselect-algorithm.rexx new file mode 100644 index 0000000000..e6e15e359f --- /dev/null +++ b/Task/Quickselect-algorithm/REXX/quickselect-algorithm.rexx @@ -0,0 +1,30 @@ +/*REXX program sorts a list (which may be numbers) using quick select.*/ +parse arg list; if list='' then list=9 8 7 6 5 0 1 2 3 4 /*default?*/ + do #=1 for words(list); @.#=word(list,#); end /*#*/; #=#-1 + /* [↓] #=number of items in list*/ + do j=1 for # /*show 1 ──► # place and value.*/ + say ' item' right(j,length(#))", value: " qSel(1,#,j) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────QPART subroutine────────────────────*/ +qPart: procedure expose @.; parse arg L 1 ?,R,pivotIndex;pVal=@.pivotIndex +parse value @.pivotIndex @.R with @.R @.pivotIndex /*swap 2 items*/ + do k=L to R-1 /*process the left side of list. */ + if @.k>pVal then iterate /*when item>pivotValue, skip it. */ + parse value @.? @.k with @.k @.? /*swap 2 items*/ + ?=?+1 /*next item. */ + end /*k*/ +parse value @.R @.? with @.? @.R /*swap 2 items*/ +return ? +/*──────────────────────────────────QSEL subroutine─────────────────────*/ +qSel: procedure expose @.; parse arg L,R,z; if L==R then return @.L + do forever /*keep looping until all done. */ + pivotNewIndex=qPart(L, R, (L+R)%2) /*partition the list into ≈ ½. */ + pivotDist=pivotNewIndex-L+1 + if pivotDist==z then return @.pivotNewIndex + else if z pivot) A)) + (define A2 (filter (curry < pivot) A)) + (cond + [(<= k (length A1)) (quickselect A1 k)] + [(> k (- (length A) (length A2))) (quickselect A2 (- k (- (length A) (length A2))))] + [else pivot])) + +(define a '(9 8 7 6 5 0 1 2 3 4)) +(display (string-join (map number->string (for/list ([k 10]) (quickselect a (+ 1 k)))) ", ")) diff --git a/Task/Quickselect-algorithm/Ruby/quickselect-algorithm.rb b/Task/Quickselect-algorithm/Ruby/quickselect-algorithm.rb new file mode 100644 index 0000000000..7d430c8f19 --- /dev/null +++ b/Task/Quickselect-algorithm/Ruby/quickselect-algorithm.rb @@ -0,0 +1,18 @@ +def quickselect(a, k) + arr = a.dup # we will be modifying it + loop do + pivot = arr.delete_at(rand(arr.length)) + left, right = arr.partition { |x| x < pivot } + if k == left.length + return pivot + elsif k < left.length + arr = left + else + k = k - left.length - 1 + arr = right + end + end +end + +v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] +p v.each_index.map { |i| quickselect(v, i) } diff --git a/Task/Quickselect-algorithm/Scala/quickselect-algorithm.scala b/Task/Quickselect-algorithm/Scala/quickselect-algorithm.scala new file mode 100644 index 0000000000..cf9f8503e6 --- /dev/null +++ b/Task/Quickselect-algorithm/Scala/quickselect-algorithm.scala @@ -0,0 +1,20 @@ +import scala.util.Random + +object QuickSelect { + def quickSelect[A <% Ordered[A]](seq: Seq[A], n: Int, rand: Random = new Random): A = { + val pivot = rand.nextInt(seq.length); + val (left, right) = seq.partition(_ < seq(pivot)) + if (left.length == n) { + seq(pivot) + } else if (left.length < n) { + quickSelect(right, n - left.length, rand) + } else { + quickSelect(left, n, rand) + } + } + + def main(args: Array[String]): Unit = { + val v = Array(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) + println((0 until v.length).map(quickSelect(v, _)).mkString(", ")) + } +} diff --git a/Task/Quickselect-algorithm/Standard-ML/quickselect-algorithm.ml b/Task/Quickselect-algorithm/Standard-ML/quickselect-algorithm.ml new file mode 100644 index 0000000000..5a7e4a2ae6 --- /dev/null +++ b/Task/Quickselect-algorithm/Standard-ML/quickselect-algorithm.ml @@ -0,0 +1,12 @@ +fun quickselect (_, _, []) = raise Fail "empty" + | quickselect (k, cmp, x :: xs) = let + val (ys, zs) = List.partition (fn y => cmp (y, x) = LESS) xs + val l = length ys + in + if k < l then + quickselect (k, cmp, ys) + else if k > l then + quickselect (k-l-1, cmp, zs) + else + x + end diff --git a/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-1.tcl b/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-1.tcl new file mode 100644 index 0000000000..45a6c2de68 --- /dev/null +++ b/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-1.tcl @@ -0,0 +1,50 @@ +# Swap the values at two indices of a list +proc swap {list i j} { + upvar 1 $list l + set tmp [lindex $l $i] + lset l $i [lindex $l $j] + lset l $j $tmp +} + +proc quickselect {vector k {left 0} {right ""}} { + set last [expr {[llength $vector] - 1}] + if {$right eq ""} { + set right $last + } + # Sanity assertions + if {![llength $vector] || $k <= 0} { + error "Either empty vector, or k <= 0" + } elseif {![tcl::mathop::<= 0 $left $last]} { + error "left is out of range" + } elseif {![tcl::mathop::<= $left $right $last]} { + error "right is out of range" + } + + # the _select core, inlined + while 1 { + set pivotIndex [expr {int(rand()*($right-$left))+$left}] + + # the partition core, inlined + set pivotValue [lindex $vector $pivotIndex] + swap vector $pivotIndex $right + set storeIndex $left + for {set i $left} {$i <= $right} {incr i} { + if {[lindex $vector $i] < $pivotValue} { + swap vector $storeIndex $i + incr storeIndex + } + } + swap vector $right $storeIndex + set pivotNewIndex $storeIndex + + set pivotDist [expr {$pivotNewIndex - $left + 1}] + if {$pivotDist == $k} { + return [lindex $vector $pivotNewIndex] + } elseif {$k < $pivotDist} { + set right [expr {$pivotNewIndex - 1}] + } else { + set k [expr {$k - $pivotDist}] + set left [expr {$pivotNewIndex + 1}] + } + } +} diff --git a/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-2.tcl b/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-2.tcl new file mode 100644 index 0000000000..9fd1e39153 --- /dev/null +++ b/Task/Quickselect-algorithm/Tcl/quickselect-algorithm-2.tcl @@ -0,0 +1,4 @@ +set v {9 8 7 6 5 0 1 2 3 4} +foreach i {1 2 3 4 5 6 7 8 9 10} { + puts "$i => [quickselect $v $i]" +} diff --git a/Task/RSA-code/00DESCRIPTION b/Task/RSA-code/00DESCRIPTION new file mode 100644 index 0000000000..266884ce93 --- /dev/null +++ b/Task/RSA-code/00DESCRIPTION @@ -0,0 +1,37 @@ +Given an [[wp:RSA|RSA]] key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. + +'''Background''' + +RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “n” and “e” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “d” is kept secret, so that only the recipient can read the encrypted plaintext. + +The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a=01,b=02,...,z=26). This yields a string of numbers, generally referred to as "numerical plaintext", “P”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 0805 1212 1523 1518 1204. + +The plaintext must also be split into blocks so that the numerical plaintext is smaller than n otherwise the decryption will fail. + +The ciphertext, C, is then computed by taking each block of P, and computing +: C \equiv P^e \mod n +Similarly, to decode, one computes +: P \equiv C^d \mod n + +To generate a key, one finds 2 (ideally large) primes p and q. the value “n” is simply: n = p \times q. +One must then choose an “e” such that \gcd(e, (p-1)\times(q-1) ) = 1. That is to say, e and (p-1)\times(q-1) are relatively prime to each other. + +The decryption value d is then found by solving +: d\times e \equiv 1 \mod (p-1)\times(q-1) + +The security of the code is based on the secrecy of the Private Key (decryption exponent) “d” and the difficulty in factoring “n”. Research into RSA facilitated advances in factoring and a number of [http://www.rsa.com/rsalabs/node.asp?id=2092 factoring challenges]. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see [[wp:Key_size#Asymmetric_algorithm_key_lengths|Asymmetric algorithm key lengths]] or [http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57-Part1-revised2_Mar08-2007.pdf NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes]). + +'''Summary of the task requirements:''' + +* Encrypt and Decrypt a short message or two using RSA with a demonstration key. +* Implement RSA do not call a library. +* Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). +* Either support blocking or give an error if the message would require blocking) +* Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: +:: n = 9516311845790656153499716760847001433441357 +:: e = 65537 +:: d = 5617843187844953170308463622230283376298685 +* Messages can be hard-coded into the program, there is no need for elaborate input coding. +* Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. + +{{alertbox|#ffff70|'''Warning'''
Rosetta Code is '''not''' a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to [[Talk:RSA_code#Difference_from_practical_cryptographical_version]].}} diff --git a/Task/RSA-code/00META.yaml b/Task/RSA-code/00META.yaml new file mode 100644 index 0000000000..fdbbfe89ad --- /dev/null +++ b/Task/RSA-code/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Encryption diff --git a/Task/RSA-code/Common-Lisp/rsa-code.lisp b/Task/RSA-code/Common-Lisp/rsa-code.lisp new file mode 100644 index 0000000000..d9d6229468 --- /dev/null +++ b/Task/RSA-code/Common-Lisp/rsa-code.lisp @@ -0,0 +1,32 @@ +(defparameter *n* 9516311845790656153499716760847001433441357) +(defparameter *e* 65537) +(defparameter *d* 5617843187844953170308463622230283376298685) + +;; magic +(defun encode-string (message) + (parse-integer (reduce #'(lambda (x y) (concatenate 'string x y)) + (loop for c across message collect (format nil "~2,'0d" (- (char-code c) 32)))))) + +;; sorcery +(defun decode-string (message) (coerce (loop for (a b) on + (loop for char across (write-to-string message) collect char) + by #'cddr collect (code-char (+ (parse-integer (coerce (list a b) 'string)) 32))) 'string)) + +;; ACTUAL RSA ALGORITHM STARTS HERE ;; + +;; fast modular exponentiation: runs in O(log exponent) +;; acc is initially 1 and contains the result by the end +(defun mod-exp (base exponent modulus acc) + (if (= exponent 0) acc + (mod-exp (mod (* base base) modulus) (ash exponent -1) modulus + (if (= (mod exponent 2) 1) (mod (* acc base) modulus) acc)))) + +;; to encode a message, we first convert it to its integer form. +;; then, we raise it to the *e* power, modulo *n* +(defun encode-rsa (message) + (mod-exp (encode-string message) *e* *n* 1)) + +;; to decode a message, we raise it to *d* power, modulo *n* +;; and then convert it back into a string +(defun decode-rsa (message) + (decode-string (mod-exp message *d* *n* 1))) diff --git a/Task/RSA-code/D/rsa-code.d b/Task/RSA-code/D/rsa-code.d new file mode 100644 index 0000000000..3271e7151b --- /dev/null +++ b/Task/RSA-code/D/rsa-code.d @@ -0,0 +1,35 @@ +void main() { + import std.stdio, std.bigint, std.algorithm, std.string, std.range, + modular_exponentiation; + + immutable txt = "Rosetta Code"; + writeln("Plain text: ", txt); + + // A key set big enough to hold 16 bytes of plain text in + // a single block (to simplify the example) and also big enough + // to demonstrate efficiency of modular exponentiation. + immutable BigInt n = "2463574872878749457479".BigInt * + "3862806018422572001483".BigInt; + immutable BigInt e = 2 ^^ 16 + 1; + immutable BigInt d = "5617843187844953170308463622230283376298685"; + + // Convert plain text to a number. + immutable txtN = reduce!q{ (a << 8) | uint(b) }(0.BigInt, txt); + if (txtN >= n) + return writeln("Plain text message too long."); + writeln("Plain text as a number: ", txtN); + + // Encode a single number. + immutable enc = txtN.powMod(e, n); + writeln("Encoded: ", enc); + + // Decode a single number. + auto dec = enc.powMod(d, n); + writeln("Decoded: ", dec); + + // Convert number to text. + char[] decTxt; + for (; dec; dec >>= 8) + decTxt ~= (dec & 0xff).toInt; + writeln("Decoded number as text: ", decTxt.retro); +} diff --git a/Task/RSA-code/Go/rsa-code.go b/Task/RSA-code/Go/rsa-code.go new file mode 100644 index 0000000000..c370d936f4 --- /dev/null +++ b/Task/RSA-code/Go/rsa-code.go @@ -0,0 +1,48 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + var n, e, d, bb, ptn, etn, dtn big.Int + pt := "Rosetta Code" + fmt.Println("Plain text: ", pt) + + // a key set big enough to hold 16 bytes of plain text in + // a single block (to simplify the example) and also big enough + // to demonstrate efficiency of modular exponentiation. + n.SetString("9516311845790656153499716760847001433441357", 10) + e.SetString("65537", 10) + d.SetString("5617843187844953170308463622230283376298685", 10) + + // convert plain text to a number + for _, b := range []byte(pt) { + ptn.Or(ptn.Lsh(&ptn, 8), bb.SetInt64(int64(b))) + } + if ptn.Cmp(&n) >= 0 { + fmt.Println("Plain text message too long") + return + } + fmt.Println("Plain text as a number:", &ptn) + + // encode a single number + etn.Exp(&ptn, &e, &n) + fmt.Println("Encoded: ", &etn) + + // decode a single number + dtn.Exp(&etn, &d, &n) + fmt.Println("Decoded: ", &dtn) + + // convert number to text + var db [16]byte + dx := 16 + bff := big.NewInt(0xff) + for dtn.BitLen() > 0 { + dx-- + db[dx] = byte(bb.And(&dtn, bff).Int64()) + dtn.Rsh(&dtn, 8) + } + fmt.Println("Decoded number as text:", string(db[dx:])) +} diff --git a/Task/RSA-code/Icon/rsa-code.icon b/Task/RSA-code/Icon/rsa-code.icon new file mode 100644 index 0000000000..730fd467c7 --- /dev/null +++ b/Task/RSA-code/Icon/rsa-code.icon @@ -0,0 +1,65 @@ +procedure main() # rsa demonstration + + n := 9516311845790656153499716760847001433441357 + e := 65537 + d := 5617843187844953170308463622230283376298685 + b := 2^integer(log(n,2)) # for blocking + write("RSA Demo using\n n = ",n,"\n e = ",e,"\n d = ",d,"\n b = ",b) + + every m := !["Rosetta Code", "Hello Word!", + "This message is too long.", repl("x",*decode(n+1))] do { + write("\nMessage = ",image(m)) + write( "Encoded = ",m := encode(m)) + if m := rsa(m,e,n) then { # unblocked + write( "Encrypt = ",m) + write( "Decrypt = ",m := rsa(m,d,n)) + } + else { # blocked + every put(C := [], rsa(!block(m,b),e,n)) + writes("Encrypt = ") ; every writes(!C," ") ; write() + every put(P := [], rsa(!C,d,n)) + writes("Decrypt = ") ; every writes(!P," ") ; write() + write("Unblocked = ",m := unblock(P,b)) + } + write( "Decoded = ",image(decode(m))) + } +end + +procedure mod_power(base, exponent, modulus) # fast modular exponentation + result := 1 + while exponent > 0 do { + if exponent % 2 = 1 then + result := (result * base) % modulus + exponent /:= 2 + base := base ^ 2 % modulus + } + return result +end + +procedure rsa(text,e,n) # return rsa encryption of numerically encoded message; fail if text < n +return mod_power(text,e,text < n) +end + +procedure encode(text) # numerically encode ascii text as int + every (message := 0) := ord(!text) + 256 * message + return message +end + +procedure decode(message) # numerically decode int to ascii text + text := "" + while text ||:= char((0 < message) % 256) do + message /:= 256 + return reverse(text) +end + +procedure block(m,b) # break lg int into blocks of size b + M := [] + while push(M, x := (0 < m) % b) do + m /:= b + return M +end + +procedure unblock(M,b) # reassemble blocks of size b into lg int + every (m := 0) := !M + b * m + return m +end diff --git a/Task/RSA-code/J/rsa-code.j b/Task/RSA-code/J/rsa-code.j new file mode 100644 index 0000000000..91aa87aaf0 --- /dev/null +++ b/Task/RSA-code/J/rsa-code.j @@ -0,0 +1,16 @@ + N=: 9516311845790656153499716760847001433441357x + E=: 65537x + D=: 5617843187844953170308463622230283376298685x + + ] text=: 'Rosetta Code' +Rosetta Code + ] num=: 256x #. a.i.text +25512506514985639724585018469 + num >: N NB. check if blocking is necessary (0 means no) +0 + ] enc=: N&|@^&E num +916709442744356653386978770799029131264344 + ] dec=: N&|@^&D enc +25512506514985639724585018469 + ] final=: a. {~ 256x #.inv dec +Rosetta Code diff --git a/Task/RSA-code/Perl-6/rsa-code.pl6 b/Task/RSA-code/Perl-6/rsa-code.pl6 new file mode 100644 index 0000000000..8fbd956560 --- /dev/null +++ b/Task/RSA-code/Perl-6/rsa-code.pl6 @@ -0,0 +1,44 @@ +constant $n = 9516311845790656153499716760847001433441357; +constant $e = 65537; +constant $d = 5617843187844953170308463622230283376298685; + +my $secret-message = "ROSETTA CODE"; + +package Message { + my @alphabet = 'A' .. 'Z', ' '; + my $rad = +@alphabet; + my %code = @alphabet Z=> 0 .. *; + subset Text of Str where /^^ @alphabet+ $$/; + our sub encode(Text $t) { + [+] %code{$t.flip.comb} Z* (1, $rad, $rad*$rad ... *); + } + our sub decode(Int $n is copy) { + @alphabet[ + gather loop { + take $n % $rad; + last if $n < $rad; + $n div= $rad; + } + ].join.flip; + } +} + +use Test; +plan 1; + +say "Secret message is $secret-message"; +say "Secret message in integer form is $_" given + my $numeric-message = Message::encode $secret-message; +say "After exponentiation with public exponent we get: $_" given + my $numeric-cipher = expmod $numeric-message, $e, $n; +say "This turns into the string $_" given + my $text-cipher = Message::decode $numeric-cipher; + +say "If we re-encode it in integer form we get $_" given + my $numeric-cipher2 = Message::encode $text-cipher; +say "After exponentiation with SECRET exponent we get: $_" given + my $numeric-message2 = expmod $numeric-cipher2, $d, $n; +say "This turns into the string $_" given + my $secret-message2 = Message::decode $numeric-message2; + +is $secret-message, $secret-message2, "the message has been correctly decrypted"; diff --git a/Task/RSA-code/PicoLisp/rsa-code.l b/Task/RSA-code/PicoLisp/rsa-code.l new file mode 100644 index 0000000000..e9a32fe866 --- /dev/null +++ b/Task/RSA-code/PicoLisp/rsa-code.l @@ -0,0 +1,116 @@ +### This is a copy of "lib/rsa.l" ### + +# Generate long random number +(de longRand (N) + (use (R D) + (while (=0 (setq R (abs (rand))))) + (until (> R N) + (unless (=0 (setq D (abs (rand)))) + (setq R (* R D)) ) ) + (% R N) ) ) + +# X power Y modulus N +(de **Mod (X Y N) + (let M 1 + (loop + (when (bit? 1 Y) + (setq M (% (* M X) N)) ) + (T (=0 (setq Y (>> 1 Y))) + M ) + (setq X (% (* X X) N)) ) ) ) + +# Probabilistic prime check +(de prime? (N) + (and + (> N 1) + (bit? 1 N) + (let (Q (dec N) K 0) + (until (bit? 1 Q) + (setq + Q (>> 1 Q) + K (inc K) ) ) + (do 50 + (NIL (_prim? N Q K)) + T ) ) ) ) + +# (Knuth Vol.2, p.379) +(de _prim? (N Q K) + (use (X J Y) + (while (> 2 (setq X (longRand N)))) + (setq + J 0 + Y (**Mod X Q N) ) + (loop + (T + (or + (and (=0 J) (= 1 Y)) + (= Y (dec N)) ) + T ) + (T + (or + (and (> J 0) (= 1 Y)) + (<= K (inc 'J)) ) + NIL ) + (setq Y (% (* Y Y) N)) ) ) ) + +# Find a prime number with `Len' digits +(de prime (Len) + (let P (longRand (** 10 (*/ Len 2 3))) + (unless (bit? 1 P) + (inc 'P) ) + (until (prime? P) # P: Prime number of size 2/3 Len + (inc 'P 2) ) + # R: Random number of size 1/3 Len + (let (R (longRand (** 10 (/ Len 3))) K (+ R (% (- P R) 3))) + (when (bit? 1 K) + (inc 'K 3) ) + (until (prime? (setq R (inc (* K P)))) + (inc 'K 6) ) + R ) ) ) + +# Generate RSA key +(de rsaKey (N) #> (Encrypt . Decrypt) + (let (P (prime (*/ N 5 10)) Q (prime (*/ N 6 10))) + (cons + (* P Q) + (/ + (inc (* 2 (dec P) (dec Q))) + 3 ) ) ) ) + +# Encrypt a list of characters +(de encrypt (Key Lst) + (let Siz (>> 1 (size Key)) + (make + (while Lst + (let N (char (pop 'Lst)) + (while (> Siz (size N)) + (setq N (>> -16 N)) + (inc 'N (char (pop 'Lst))) ) + (link (**Mod N 3 Key)) ) ) ) ) ) + +# Decrypt a list of numbers +(de decrypt (Keys Lst) + (mapcan + '((N) + (let Res NIL + (setq N (**Mod N (cdr Keys) (car Keys))) + (until (=0 N) + (push 'Res (char (& `(dec (** 2 16)) N))) + (setq N (>> 16 N)) ) + Res ) ) + Lst ) ) +### End of "lib/rsa.l" ### + +# Generate 100-digit keys (private . public) +: (setq Keys (rsaKey 100)) +-> (14394597526321726957429995133376978449624406217727317004742182671030.... + +# Encrypt +: (setq CryptText + (encrypt (car Keys) + (chop "The quick brown fox jumped over the lazy dog's back") ) ) +-> (72521958974980041245760752728037044798830723189142175108602418861716... + +# Decrypt +: (pack (decrypt Keys CryptText)) +-> "The quick brown fox jumped over the lazy dog's back" diff --git a/Task/RSA-code/Python/rsa-code-1.py b/Task/RSA-code/Python/rsa-code-1.py new file mode 100644 index 0000000000..d33a1364b0 --- /dev/null +++ b/Task/RSA-code/Python/rsa-code-1.py @@ -0,0 +1,222 @@ +from tkinter import * +import random +import time + +letter = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q", + "r","s","t","u","v","w","x","y","z",",",".","!","?",' '] +number = ["01","02","03","04","05","06","07","08","09","10","11","12","13", + "14","15","16","17","18","19","20","21","22","23","24","25","26","27", + "28","29","30",'31'] + +n = 2537 +e = 13 +d = 937 +def decrypt(F,d): + # performs the decryption function on an block of ciphertext + if d == 0: + return 1 + if d == 1: + return F + w,r = divmod(d,2) + if r == 1: + return decrypt(F*F%n,w)*F%n + else: + return decrypt(F*F%n,w) + +def correct(): + # Checks to see if the numerical ciphertext block should have started with a 0 (by seeing if the 0 is missing), if it is, it then adds the 0. + # example - 0102 is output as 102, which would lead the computer to think the first letter is 10, not 01. This ensures this does not happen. + for i in range(len(D)): + if len(str(P[i]))%2 !=0: + y = str(0)+str(P[i]) + P.remove(str(P[i])) + P.insert(i,y) + +def cipher(b,e): + # Performs the Encryption function on a block of ciphertext + if e == 0: + return 1 + if e == 1: + return b + w,r = divmod(e,2) + if r == 1: + return cipher(b*b%n,w)*b%n + else: + return cipher(b*b%n,w) + +def group(j,h,z): + # Places the plaintext numbers into blocks for encryption + for i in range(int(j)): + y = 0 + for n in range(h): + y += int(numP[(h*i)+n])*(10**(z-2*n)) + X.append(int(y)) + + + +class App: + # Creates a Tkineter window, for ease of operation + def __init__(self, master): + + frame = Frame(master) + frame.grid() + + #create a button with the quit command, and tell it where to go + quitbutton = Button(frame, text = "quit", fg ="red", + command = root.quit, width = 10) + quitbutton.grid(row = 0, column =3) + + #create an entry box, tell it where it goes, and how large it is + entry = Entry(frame, width = 100) + entry.grid(row = 0, column = 0) + + #set initial content of the entry box + self.contents = StringVar() + self.contents.set("Type message here") + entry["textvariable"] = self.contents + + # Create a button which initializes the decryption of ciphertext + decrypt = Button(frame,text = "Decrypt", fg = "blue", + command = self.Decrypt) + decrypt.grid(row = 2, column = 1) + + #create a label to display the number of ciphertext blocks in an encoded message + label = Label(frame, text = "# of blocks") + label.grid(row = 1, column = 1) + + #creates a button which initializes the encryption of plaintext + encrypt = Button(frame, text="Encrypt", fg = "blue", + command = self.Encrypt) + encrypt.grid(row =0, column =1) + + #create an entry box for the value of "n" + nbox = Entry(frame, width = 100) + nbox.grid(row = 3, column = 0) + + self.n = StringVar() + self.n.set(n) + nbox["textvar"] = self.n + nbox.bind('', self.set_n) #key binding, when you press "return", the value of "n" is changed to the value now in the box + + nlabel = Label(frame, text = "the value of 'n'") + nlabel.grid(row = 3, column = 1) + + #create an entry box for the value of "e" + ebox = Entry(frame, width = 100) + ebox.grid(row = 4, column = 0) + + self.e = StringVar() + self.e.set(e) + ebox["textvar"] = self.e + ebox.bind('', self.set_e) + + elabel = Label(frame, text = "the value of 'e'") + elabel.grid(row = 4, column = 1) + + #create an entry box for the value of "d" + dbox = Entry(frame, width = 100) + dbox.grid(row =5, column = 0) + + self.d = StringVar() + self.d.set(d) + dbox["textvar"] = self.d + dbox.bind('', self.set_d) + + dlabel = Label(frame, text = "the value of 'd'") + dlabel.grid(row = 5, column =1) + + blocks = Label(frame, width = 100) + blocks.grid(row = 1, column =0) + + self.block = StringVar() + self.block.set("number of blocks") + blocks["textvar"] = self.block + + output = Entry(frame, width = 100) + output.grid(row = 2, column = 0) + + self.answer = StringVar() + self.answer.set("Ciphertext") + output["textvar"] = self.answer + + # The commands of all the buttons are defined below + def set_n(self,event): + global n + n = int(self.n.get()) + print("n set to", n) + + def set_e(self, event): + global e + e = int(self.e.get()) + print("e set to",e) + + def set_d(self,event): + global d + d = int(self.d.get()) + print("d set to", d) + + def Decrypt(self): + #decrypts an encoded message + global m,P,D,x,h,p,Text,y,w,PText + P = [] + D = str(self.answer.get()) #Pulls the ciphertext out of the ciphertext box + D = D.lstrip('[') #removes the bracket "[" from the left side of the string + D = D.rstrip(']') + D = D.split(',') #splits the string into a list of strings, separating at each comma. + for i in range(len(D)): #decrypts each block in the list of strings "D" + x = decrypt(int(D[i]),d) + P.append(str(x)) + correct() #ensures each block is not missing a 0 at the start + h = len(P[0]) + p = [] + for i in range(len(D)): #further separates the list P into individual characters, i.e. "0104" becomes "01,04" + for n in range(int(h/2)): + p.append(str(P[i][(2*n):((2*n)+2)])) # grabs every 2 character group from the larger block. It gets characters between 2*n, and (2*n)+2, i.e. characters 0,1 then 2,3 etc... + + Text = [] + for i in range(len(p)): # converts each block back to text characters + for j in range(len(letter)): + if str(p[i]) == number[j]: + Text.append(letter[j]) + PText = str() + for i in range(len(Text)): #places all text characters in one string + PText = PText + str(Text[i]) + self.contents.set(str(PText)) #places the decrypted plaintext in the plaintext box + + + def Encrypt(self): + #encrypts a plaintext message using the current key + global plaintext,numP,q,j,z,X,C + plaintext = self.contents.get() #pulls the plaintext out of the entry box for use + plaintext = plaintext.lower() #places all plaintext in lower case + numP = [] + for i in range(len(plaintext)): # converts letters and symbols to their numerical values + for j in range(len(letter)): + if plaintext[i] == letter[j]: + numP.append(number[j]) + h = (len(str(n))//2)-1 # This sets the block length for the code in question, based on the value of "n" + q = len(numP)%h + for i in range(h-q): + numP.append(number[random.randint(0,25)]) # Ensures the final block of plaintext is filled with letters, and is not a single orphaned letter. + j = len(numP) / h + X = [] + z = 0 + for m in range(h-1): + z+=2 + group(j,h,z) # This sets the numerical plaintext into blocks of appropriate size, and places them in the list "X" + k = len(X) + C = [] + for i in range(k): # performs the cipher function for each block in the list of plaintext blocks + b = X[i] + r = cipher(b,e) + C.append(r) + self.answer.set(C) + self.block.set(len(C)) #places the ciphertext into the ciphertext box + + +root = Tk() + +app = App(root) + +root.mainloop() +root.destroy() diff --git a/Task/RSA-code/Python/rsa-code-2.py b/Task/RSA-code/Python/rsa-code-2.py new file mode 100644 index 0000000000..5c87bb15c4 --- /dev/null +++ b/Task/RSA-code/Python/rsa-code-2.py @@ -0,0 +1,186 @@ +import random +import time + +def decrypt(F,d): + if d == 0: + return 1 + if d == 1: + return F + w,r = divmod(d,2) + if r == 1: + return decrypt(F*F%n,w)*F%n + else: + return decrypt(F*F%n,w) + +def correct(): + for i in range(len(C)): + if len(str(P[i]))%2 !=0: + y = str(0)+str(P[i]) + P.remove(str(P[i])) + P.insert(i,y) + +def cipher(b,e): + if e == 0: + return 1 + if e == 1: + return b + w,r = divmod(e,2) + if r == 1: + return cipher(b*b%n,w)*b%n + else: + return cipher(b*b%n,w) + +def group(j,h,z): + for i in range(int(j)): + y = 0 + for n in range(h): + y += int(numP[(h*i)+n])*(10**(z-2*n)) + X.append(int(y)) + +def gcd(a, b): + while b != 0: + (a, b) = (b, a%b) + return a + + + +letter = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q", + "r","s","t","u","v","w","x","y","z",",",".","!","?"," "] +number = ["01","02","03","04","05","06","07","08","09","10","11","12","13", + "14","15","16","17","18","19","20","21","22","23","24","25","26","27", + "28","29","30","31"] + + +print( '\n' ) +def Decrypt(): + #decrypts an encoded message + global m,P,C,x,h,p,Text,y,w + P = [] + C = str(input("Enter ciphertext blocks:")) + C = C.lstrip('[') + C = C.rstrip(']') + C = C.split(',') + for i in range(len(C)): + x = decrypt(int(C[i]),d) + P.append(str(x)) + correct() + #print(P) + h = len(P[0]) + p = [] + for i in range(len(C)): + for n in range(int(h/2)): + p.append(str(P[i][(2*n):((2*n)+2)])) + + Text = [] + for i in range(len(p)): + for j in range(len(letter)): + if str(p[i]) == number[j]: + Text.append(letter[j]) + PText = str() + for i in range(len(Text)): + PText = PText + str(Text[i]) + print("Plaintext is:", PText) + +def Encrypt(): + #encrypts a plaintext message using the current key + global plaintext,numP,q,j,z,X,C + plaintext =(input("Enter Plaintext :")) + plaintext = plaintext.lower() + numP = [] + for i in range(len(plaintext)): + for j in range(len(letter)): + if plaintext[i] == letter[j]: + numP.append(number[j]) + h = (len(str(n))//2)-1 + q = len(numP)%h + for i in range(h-q): + numP.append(number[random.randint(0,25)]) + j = len(numP) / h + #print(numP) + X = [] + z = 0 + for m in range(h-1): + z+=2 + group(j,h,z) + k = len(X) + C = [] + for i in range(k): + b = X[i] + r = cipher(b,e) + C.append(r) + print("Ciphertext:",C) + print("Number of Ciphertext blocks:",len(C)) + +def setup(): + global n,e,d + while True: + try: + n = int(input(" Enter a value for n :")) + if n > 2: + break + except ValueError: + print('please enter a number') + while 1!=2 : + try: + e = int(input(" Enter a value for e :")) + if e >= 2: + break + except ValueError: + print('please enter a number') + while True: + try: + d = int(input(" Enter a value for d. If d unknown, enter 0 :")) + if d >= 0: + break + except ValueError: + print('please enter a number') + +#setup() +n = 2537 +e = 13 +d = 937 + +print("To redefine n,e, or d, type 'n','e',... etc.") +print("To encrypt a message with the current key, type 'Encrypt'") +print("To decrypt a message with the current key, type 'Decrypt'") +print("Type quit to exit") +print( '\n' ) +print( '\n' ) + +mm = str() +while mm != 'quit': + mm = input("Enter Command...") + if mm.lower() == 'encrypt': + Encrypt() + elif mm.lower() == 'decrypt': + Decrypt() + elif mm.lower() == 'n': + try: + print('current n = ',n) + n = int(input(" Enter a value for n :")) + except ValueError: + print('That is not a valid entry') + elif mm.lower() == 'help': + print("To redefine n,e, or d, type 'n','e',... etc.") + print("To encrypt a message with the current key, type 'Encrypt'") + print("To decrypt a message with the current key, type 'Decrypt'") + print("Type quit to exit") + print( '\n' ) + print( '\n' ) + elif mm.lower() == 'e': + try: + print('current e = ',e) + e = int(input(" Enter a value for e :")) + except ValueError: + print('That is not a valid entry') + elif mm.lower() == 'd': + try: + print('current d = ',d) + d = int(input(" Enter a value for d :")) + except ValueError: + print('That is not a valid entry') + else: + if mm != 'quit': + ii= random.randint(0,6) + statements = ["I sorry, Dave. I'm afraid i can't do that","I'm begging you....read the directions","Nah ahh ahh, didnt say the magic word","This input is....UNACCEPTABLE!!","Seriously....was that even a word???","Please follow the directions","Just type 'help' if you are really that lost"] + print(statements[ii]) diff --git a/Task/RSA-code/Python/rsa-code-3.py b/Task/RSA-code/Python/rsa-code-3.py new file mode 100644 index 0000000000..d35a894f90 --- /dev/null +++ b/Task/RSA-code/Python/rsa-code-3.py @@ -0,0 +1,18 @@ +>>> +To redefine n,e, or d, type 'n','e',... etc. +To encrypt a message with the current key, type 'Encrypt' +To decrypt a message with the current key, type 'Decrypt' +Type quit to exit + + + + +Enter Command...ENCRYPT +Enter Plaintext :drink MORE Ovaltine +Ciphertext: [140, 2222, 1864, 1616, 821, 384, 2038, 2116, 2222, 205, 384, 2116, 45, 1, 2497, 793, 1864, 1616, 205, 41] +Number of Ciphertext blocks: 20 +Enter Command...decrypt +Enter ciphertext blocks:[140, 2222, 1864, 1616, 821, 384, 2038, 2116, 2222, 205, 384, 2116, 45, 1, 2497, 793, 1864, 1616, 205, 41] +Plaintext is: drink more ovaltineu +Enter Command...quit +>>> diff --git a/Task/RSA-code/README b/Task/RSA-code/README new file mode 100644 index 0000000000..d82c741b07 --- /dev/null +++ b/Task/RSA-code/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/RSA_code diff --git a/Task/RSA-code/Racket/rsa-code.rkt b/Task/RSA-code/Racket/rsa-code.rkt new file mode 100644 index 0000000000..e40d962a11 --- /dev/null +++ b/Task/RSA-code/Racket/rsa-code.rkt @@ -0,0 +1,172 @@ +#lang racket +(require math/number-theory) +(define-logger rsa) +(current-logger rsa-logger) + +;; -| STRING TO NUMBER MAPPING |---------------------------------------------------------------------- +(define (bytes->number B) ; We'll need our data in numerical form .. + (for/fold ((rv 0)) ((b B)) (+ b (* rv 256)))) + +(define (number->bytes N) ; .. and back again + (define (inr n b) (if (zero? n) b (inr (quotient n 256) (bytes-append (bytes (modulo n 256)) b)))) + (inr N (bytes))) + +;; -| RSA PUBLIC / PRIVATE FUNCTIONS |---------------------------------------------------------------- +;; The basic definitions... pretty well lifted from the text book! +(define ((C e n) p) + ;; Just do the arithmetic to demonstrate RSA... + ;; breaking large messages into blocks is something for another day. + (unless (< p n) (raise-argument-error 'C (format "(and/c integer? (symbol (format "~a-~a" function-base-name s)))) + (define-values (n e d) (RSA-keyset function-base-name)) + (define my-C (rnm-fn (C e n) "C")) + (define my-P (rnm-fn (P d n) "P")) + (define my-encrypt (rnm-fn (compose number->bytes my-C bytes->number) "encrypt")) + (define my-decrypt (rnm-fn (compose number->bytes my-P bytes->number) "decrypt")) + (values my-C my-P my-encrypt my-decrypt (list n e d) (list n e))) + +;; -| HEREON IS JUST A LOAD OF CHATTY DEMOS |--------------------------------------------------------- +(define (narrated-encrypt-bytes C who plain-text) + (define plain-n (bytes->number plain-text)) + (define cypher-n (C plain-n)) + (define cypher-text (number->bytes cypher-n)) + (printf #<number cypher-text)) + (define plain-n (P cypher-n)) + (define plain-text (number->bytes plain-n)) + (printf #< ~s +Only she could have done this (only she has the her private key data) -- so this is a signature on the +message. Anyone can verify the signature by "decrypting" the message with the public "encryption" key. +(A-pub (A-prv msg)) -> ~s +But anyone is able to do this, so there is no privacy here. +Everyone knows that it can only be Alice at Lymm at noon, but this message is for Bob's eyes only. +We need to encrypt this with his public key: +(B-pub (A-prv msg)) -> ~s +Which is what gets posted to alt.chat.secret-rendezvous +Bob decrypts this to get the signed message from Alice: +(B-prv (B-pub (A-prv msg))) -> ~s +And verifies Alice's signature: +(A-pub (B-prv (B-pub (A-prv msg)))) -> ~s +Alice genuinely sent the message. +And nobody else (on a.c.s-r, at least) has read it. + +KEYS: + Alice's full set: ~s + Bob's full set: ~s +EOS + plain-A-to-B signed-A-to-B unsigned-A-to-B crypt-signed-A-to-B decrypt-signed-A-to-B + decrypt-verified-B A-pvt-keys B-pvt-keys)) diff --git a/Task/RSA-code/Seed7/rsa-code.seed7 b/Task/RSA-code/Seed7/rsa-code.seed7 new file mode 100644 index 0000000000..fb88fc9478 --- /dev/null +++ b/Task/RSA-code/Seed7/rsa-code.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + include "bytedata.s7i"; + +const proc: main is func + local + const string: plainText is "Rosetta Code"; + # Use a key big enough to hold 16 bytes of plain text in a single block. + const bigInteger: modulus is 9516311845790656153499716760847001433441357_; + const bigInteger: encode is 65537_; + const bigInteger: decode is 5617843187844953170308463622230283376298685_; + var bigInteger: plainTextNumber is 0_; + var bigInteger: encodedNumber is 0_; + var bigInteger: decodedNumber is 0_; + var string: decodedText is ""; + begin + writeln("Plain text: " <& plainText); + plainTextNumber := bytes2BigInt(plainText, UNSIGNED, BE); + if plainTextNumber >= modulus then + writeln("Plain text message too long"); + else + writeln("Plain text as a number: " <& plainTextNumber); + encodedNumber := modPow(plainTextNumber, encode, modulus); + writeln("Encoded: " <& encodedNumber); + decodedNumber := modPow(encodedNumber, decode, modulus); + writeln("Decoded: " <& decodedNumber); + decodedText := bytes(decodedNumber, UNSIGNED, BE); + writeln("Decoded number as text: " <& decodedText); + end if; + end func; diff --git a/Task/RSA-code/Tcl/rsa-code.tcl b/Task/RSA-code/Tcl/rsa-code.tcl new file mode 100644 index 0000000000..6d3948462c --- /dev/null +++ b/Task/RSA-code/Tcl/rsa-code.tcl @@ -0,0 +1,48 @@ +package require Tcl 8.5 + +# This is a straight-forward square-and-multiply implementation that relies on +# Tcl 8.5's bignum support (based on LibTomMath) for speed. +proc modexp {b expAndMod} { + lassign $expAndMod -> e n + if {$b >= $n} {puts stderr "WARNING: modulus too small"} + for {set r 1} {$e != 0} {set e [expr {$e >> 1}]} { + if {$e & 1} { + set r [expr {($r * $b) % $n}] + } + set b [expr {($b ** 2) % $n}] + } + return $r +} + +# Assumes that messages are shorter than the modulus +proc rsa_encrypt {message publicKey} { + if {[lindex $publicKey 0] ne "publicKey"} {error "key handling"} + set toEnc 0 + foreach char [split [encoding convertto utf-8 $message] ""] { + set toEnc [expr {$toEnc * 256 + [scan $char "%c"]}] + } + return [modexp $toEnc $publicKey] +} + +proc rsa_decrypt {encrypted privateKey} { + if {[lindex $privateKey 0] ne "privateKey"} {error "key handling"} + set toDec [modexp $encrypted $privateKey] + for {set message ""} {$toDec > 0} {set toDec [expr {$toDec >> 8}]} { + append message [format "%c" [expr {$toDec & 255}]] + } + return [encoding convertfrom utf-8 [string reverse $message]] +} + +# Assemble packaged public and private keys +set e 65537 +set n 9516311845790656153499716760847001433441357 +set d 5617843187844953170308463622230283376298685 +set publicKey [list "publicKey" $e $n] +set privateKey [list "privateKey" $d $n] + +# Test on some input strings +foreach input {"Rosetta Code" "UTF-8 \u263a test"} { + set enc [rsa_encrypt $input $publicKey] + set dec [rsa_decrypt $enc $privateKey] + puts "$input -> $enc -> $dec" +} diff --git a/Task/Ranking-methods/00DESCRIPTION b/Task/Ranking-methods/00DESCRIPTION new file mode 100644 index 0000000000..64f3cd95e6 --- /dev/null +++ b/Task/Ranking-methods/00DESCRIPTION @@ -0,0 +1,23 @@ +The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. + +The numerical rank of a competitor can be assigned in several [[wp:Ranking|different ways]]. + +;Task: +The following scores are accrued for all competitors of a competition (in best-first order): +
44 Solomon
+42 Jason
+42 Errol
+41 Garry
+41 Bernard
+41 Barry
+39 Stephen
+ +For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: +# Standard. (Ties share what would have been their first ordinal number). +# Modified. (Ties share what would have been their last ordinal number). +# Dense. (Ties share the next available integer). +# Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise). +# Fractional. (Ties share the mean of what would have been their ordinal numbers). +See the [[wp:Ranking|wikipedia article]] for a fuller description. + +Show here, on this page, the ranking of the test scores under each of the numbered ranking methods. diff --git a/Task/Ranking-methods/AWK/ranking-methods.awk b/Task/Ranking-methods/AWK/ranking-methods.awk new file mode 100644 index 0000000000..979e26e400 --- /dev/null +++ b/Task/Ranking-methods/AWK/ranking-methods.awk @@ -0,0 +1,100 @@ +## +## Dense ranking in file: ranking_d.awk +## + +BEGIN{ lastresult = "!"; lastrank = 0 } + +function d_rank(){ + if($1==lastresult){ + print lastrank, $0 + }else{ + lastresult = $1 + print ++lastrank, $0 } +} +//{d_rank() } + +## +## Fractional ranking in file: ranking_f.awk +## + +BEGIN{ + last = "!" + flen = 0 } + +function f_rank(){ + item = $0 + if($1!=last){ + if(flen){ + sum = 0 + for(fl=0; fl < flen;){ + $0 = fifo[fl++] + sum += $1 } + mean = sum / flen + for(fl=0; fl < flen;){ + $0 = fifo[fl++] + $1 = "" + printf("%3g %s\n", mean, $0) } + flen = 0 + }} + $0 = item + last = $1 + fifo[flen++] = sprintf("%i %s", FNR, item) +} +//{f_rank()} + +END{ if(flen){ + sum = 0 + for(fl=0; fl < flen;){ + $0 = fifo[fl++] + sum += $1 } + mean = sum / flen + for(fl=0; fl < flen;){ + $0 = fifo[fl++] + $1 = "" + printf("%3g %s\n", mean, $0) }}} + +## +## Modified competition ranking in file: ranking_mc.awk +## + +BEGIN{ + lastresult = "!" + flen = 0 } + +function mc_rank(){ + if($1==lastresult){ + fifo[flen++] = $0 + }else{ + for(fl=0; fl < flen;){ + print FNR-1, fifo[fl++]} + flen = 0 + fifo[flen++] = $0 + lastresult = $1} +} +//{mc_rank()} + +END{ for(fl=0; fl < flen;){ + print FNR, fifo[fl++]} } + +## +## Ordinal ranking in file: ranking_o.awk +## + +function o_rank(){ print FNR, $0 } +//{o_rank() } + +## +## Standard competition ranking in file: ranking_sc.awk +## + +BEGIN{ lastresult = lastrank = "!" } + +function sc_rank(){ + if($1==lastresult){ + print lastrank, $0 + }else{ + print FNR, $0 + lastresult = $1 + lastrank = FNR} +} +//{sc_rank()} diff --git a/Task/Ranking-methods/Go/ranking-methods.go b/Task/Ranking-methods/Go/ranking-methods.go new file mode 100644 index 0000000000..0c7f1a6542 --- /dev/null +++ b/Task/Ranking-methods/Go/ranking-methods.go @@ -0,0 +1,113 @@ +package main + +import ( + "fmt" + "sort" +) + +type rankable interface { + Len() int + RankEqual(int, int) bool +} + +func StandardRank(d rankable) []float64 { + r := make([]float64, d.Len()) + var k int + for i := range r { + if i == 0 || !d.RankEqual(i, i-1) { + k = i + 1 + } + r[i] = float64(k) + } + return r +} + +func ModifiedRank(d rankable) []float64 { + r := make([]float64, d.Len()) + for i := range r { + k := i + 1 + for j := i + 1; j < len(r) && d.RankEqual(i, j); j++ { + k = j + 1 + } + r[i] = float64(k) + } + return r +} + +func DenseRank(d rankable) []float64 { + r := make([]float64, d.Len()) + var k int + for i := range r { + if i == 0 || !d.RankEqual(i, i-1) { + k++ + } + r[i] = float64(k) + } + return r +} + +func OrdinalRank(d rankable) []float64 { + r := make([]float64, d.Len()) + for i := range r { + r[i] = float64(i + 1) + } + return r +} + +func FractionalRank(d rankable) []float64 { + r := make([]float64, d.Len()) + for i := 0; i < len(r); { + var j int + f := float64(i + 1) + for j = i + 1; j < len(r) && d.RankEqual(i, j); j++ { + f += float64(j + 1) + } + f /= float64(j - i) + for ; i < j; i++ { + r[i] = f + } + } + return r +} + +type scores []struct { + score int + name string +} + +func (s scores) Len() int { return len(s) } +func (s scores) RankEqual(i, j int) bool { return s[i].score == s[j].score } +func (s scores) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s scores) Less(i, j int) bool { + if s[i].score != s[j].score { + return s[i].score > s[j].score + } + return s[i].name < s[j].name +} + +var data = scores{ + {44, "Solomon"}, + {42, "Jason"}, + {42, "Errol"}, + {41, "Garry"}, + {41, "Bernard"}, + {41, "Barry"}, + {39, "Stephen"}, +} + +func main() { + show := func(name string, fn func(rankable) []float64) { + fmt.Println(name, "Ranking:") + r := fn(data) + for i, d := range data { + fmt.Printf("%4v - %2d %s\n", r[i], d.score, d.name) + } + } + + sort.Sort(data) + show("Standard", StandardRank) + show("\nModified", ModifiedRank) + show("\nDense", DenseRank) + show("\nOrdinal", OrdinalRank) + show("\nFractional", FractionalRank) +} diff --git a/Task/Ranking-methods/Haskell/ranking-methods.hs b/Task/Ranking-methods/Haskell/ranking-methods.hs new file mode 100644 index 0000000000..a45ccd4887 --- /dev/null +++ b/Task/Ranking-methods/Haskell/ranking-methods.hs @@ -0,0 +1,72 @@ +import Data.List (groupBy, sort, intercalate) + +type Item = (Int, String) +type ItemList = [Item] +type ItemGroups = [ItemList] +type RankItem a = (a, Int, String) +type RankItemList a = [RankItem a] + +-- make sure the input is ordered and grouped by score +prepare :: ItemList -> ItemGroups +prepare = groupBy gf . reverse . sort + where gf (a, _) (b, _) = a == b + +-- give an item a rank +rank :: Num a => a -> Item -> RankItem a +rank n (a, b) = (n, a, b) + +-- ranking methods +standard, modified, dense, ordinal :: ItemGroups -> RankItemList Int + +standard = ms 1 where + ms _ [] = [] + ms n (x:xs) = map (rank n) x ++ ms (n + length x) xs + +modified = md 1 where + md _ [] = [] + md n (x:xs) = let l = length x + nl = n + l + nl1 = nl - 1 + in map (rank nl1) x ++ md (n + l) xs + +dense = md 1 where + md _ [] = [] + md n (x:xs) = map (rank n) x ++ md (n + 1) xs + +ordinal = zipWith rank [1..] . concat + +fractional :: ItemGroups -> RankItemList Double +fractional = mf 1.0 where + mf _ [] = [] + mf n (x:xs) = let l = length x + o = take l [n ..] + ld = fromIntegral l + a = sum o / ld + in map (rank a) x ++ mf (n + ld) xs + +-- sample data +test :: ItemGroups +test = prepare + [ (44, "Solomon") + , (42, "Jason") + , (42, "Errol") + , (41, "Garry") + , (41, "Bernard") + , (41, "Barry") + , (39, "Stephen") ] + +-- print rank items nicely +nicePrint :: Show a => String -> RankItemList a -> IO () +nicePrint xs items = do + putStrLn xs + mapM_ np items + putStr "\n" + where np (a, b, c) = putStrLn $ intercalate "\t" [show a, show b, c] + +main :: IO () +main = do + nicePrint "Standard:" $ standard test + nicePrint "Modified:" $ modified test + nicePrint "Dense:" $ dense test + nicePrint "Ordinal:" $ ordinal test + nicePrint "Fractional:" $ fractional test diff --git a/Task/Ranking-methods/J/ranking-methods-1.j b/Task/Ranking-methods/J/ranking-methods-1.j new file mode 100644 index 0000000000..3a4f2f0ca4 --- /dev/null +++ b/Task/Ranking-methods/J/ranking-methods-1.j @@ -0,0 +1,19 @@ +competitors=:<;._1;._2]0 :0 + 44 Solomon + 42 Jason + 42 Errol + 41 Garry + 41 Bernard + 41 Barry + 39 Stephen +) + +scores=: {."1 + +standard=: 1+i.~ +modified=: 1+i:~ +dense=: #/.~ # #\@~. +ordinal=: #\ +fractional=: #/.~ # ] (+/%#)/. #\ + +rank=:1 :'<"0@u@:scores,.]' diff --git a/Task/Ranking-methods/J/ranking-methods-2.j b/Task/Ranking-methods/J/ranking-methods-2.j new file mode 100644 index 0000000000..1242ac6ea2 --- /dev/null +++ b/Task/Ranking-methods/J/ranking-methods-2.j @@ -0,0 +1,80 @@ + standard rank competitors +┌─┬──┬───────┐ +│1│44│Solomon│ +├─┼──┼───────┤ +│2│42│Jason │ +├─┼──┼───────┤ +│2│42│Errol │ +├─┼──┼───────┤ +│4│41│Garry │ +├─┼──┼───────┤ +│4│41│Bernard│ +├─┼──┼───────┤ +│4│41│Barry │ +├─┼──┼───────┤ +│7│39│Stephen│ +└─┴──┴───────┘ + modified rank competitors +┌─┬──┬───────┐ +│1│44│Solomon│ +├─┼──┼───────┤ +│3│42│Jason │ +├─┼──┼───────┤ +│3│42│Errol │ +├─┼──┼───────┤ +│6│41│Garry │ +├─┼──┼───────┤ +│6│41│Bernard│ +├─┼──┼───────┤ +│6│41│Barry │ +├─┼──┼───────┤ +│7│39│Stephen│ +└─┴──┴───────┘ + dense rank competitors +┌─┬──┬───────┐ +│1│44│Solomon│ +├─┼──┼───────┤ +│2│42│Jason │ +├─┼──┼───────┤ +│2│42│Errol │ +├─┼──┼───────┤ +│3│41│Garry │ +├─┼──┼───────┤ +│3│41│Bernard│ +├─┼──┼───────┤ +│3│41│Barry │ +├─┼──┼───────┤ +│4│39│Stephen│ +└─┴──┴───────┘ + ordinal rank competitors +┌─┬──┬───────┐ +│1│44│Solomon│ +├─┼──┼───────┤ +│2│42│Jason │ +├─┼──┼───────┤ +│3│42│Errol │ +├─┼──┼───────┤ +│4│41│Garry │ +├─┼──┼───────┤ +│5│41│Bernard│ +├─┼──┼───────┤ +│6│41│Barry │ +├─┼──┼───────┤ +│7│39│Stephen│ +└─┴──┴───────┘ + fractional rank competitors +┌───┬──┬───────┐ +│1 │44│Solomon│ +├───┼──┼───────┤ +│2.5│42│Jason │ +├───┼──┼───────┤ +│2.5│42│Errol │ +├───┼──┼───────┤ +│5 │41│Garry │ +├───┼──┼───────┤ +│5 │41│Bernard│ +├───┼──┼───────┤ +│5 │41│Barry │ +├───┼──┼───────┤ +│7 │39│Stephen│ +└───┴──┴───────┘ diff --git a/Task/Ranking-methods/Java/ranking-methods.java b/Task/Ranking-methods/Java/ranking-methods.java new file mode 100644 index 0000000000..97ac421fcf --- /dev/null +++ b/Task/Ranking-methods/Java/ranking-methods.java @@ -0,0 +1,75 @@ +import java.util.*; + +public class RankingMethods { + + final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", + "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"}; + + public static void main(String[] args) { + int len = input.length; + + Map map = new TreeMap<>((a, b) -> b.compareTo(a)); + for (int i = 0; i < len; i++) { + String key = input[i].split("\\s+")[0]; + int[] arr; + if ((arr = map.get(key)) == null) + arr = new int[]{i, 0}; + arr[1]++; + map.put(key, arr); + } + int[][] groups = map.values().toArray(new int[map.size()][]); + + standardRanking(len, groups); + modifiedRanking(len, groups); + denseRanking(len, groups); + ordinalRanking(len); + fractionalRanking(len, groups); + } + + private static void standardRanking(int len, int[][] groups) { + System.out.println("\nStandard ranking"); + for (int i = 0, rank = 0, group = 0; i < len; i++) { + if (group < groups.length && i == groups[group][0]) { + rank = i + 1; + group++; + } + System.out.printf("%d %s%n", rank, input[i]); + } + } + + private static void modifiedRanking(int len, int[][] groups) { + System.out.println("\nModified ranking"); + for (int i = 0, rank = 0, group = 0; i < len; i++) { + if (group < groups.length && i == groups[group][0]) + rank += groups[group++][1]; + System.out.printf("%d %s%n", rank, input[i]); + } + } + + private static void denseRanking(int len, int[][] groups) { + System.out.println("\nDense ranking"); + for (int i = 0, rank = 0; i < len; i++) { + if (rank < groups.length && i == groups[rank][0]) + rank++; + System.out.printf("%d %s%n", rank, input[i]); + } + } + + private static void ordinalRanking(int len) { + System.out.println("\nOrdinal ranking"); + for (int i = 0; i < len; i++) + System.out.printf("%d %s%n", i + 1, input[i]); + } + + private static void fractionalRanking(int len, int[][] groups) { + System.out.println("\nFractional ranking"); + float rank = 0; + for (int i = 0, tmp = 0, group = 0; i < len; i++) { + if (group < groups.length && i == groups[group][0]) { + tmp += groups[group++][1]; + rank = (i + 1 + tmp) / 2.0F; + } + System.out.printf("%2.1f %s%n", rank, input[i]); + } + } +} diff --git a/Task/Ranking-methods/Perl-6/ranking-methods.pl6 b/Task/Ranking-methods/Perl-6/ranking-methods.pl6 new file mode 100644 index 0000000000..e812b38022 --- /dev/null +++ b/Task/Ranking-methods/Perl-6/ranking-methods.pl6 @@ -0,0 +1,45 @@ +my @scores = + Solomon => 44, + Jason => 42, + Errol => 42, + Garry => 41, + Bernard => 41, + Barry => 41, + Stephen => 39; + +sub tiers (@s) { @s.classify(*.value).pairs.sort.reverse.map: { [.value».key] } } + +sub standard (@s) { + my $rank = 1; + gather for tiers @s -> @players { + take $rank => @players; + $rank += @players; + } +} + +sub modified (@s) { + my $rank = 0; + gather for tiers @s -> @players { + $rank += @players; + take $rank => @players; + } +} + +sub dense (@s) { tiers(@s).map: { ++$_ => @^players } } + +sub ordinal (@s) { @s.map: ++$_ => *.key } + +sub fractional (@s) { + my $rank = 1; + gather for tiers @s -> @players { + my $beg = $rank; + my $end = $rank += @players; + take [+]($beg ..^ $end) / @players => @players; + } +} + +say "Standard:"; .say for standard @scores; +say "\nModified:"; .say for modified @scores; +say "\nDense:"; .say for dense @scores; +say "\nOrdinal:"; .say for ordinal @scores; +say "\nFractional:"; .say for fractional @scores; diff --git a/Task/Ranking-methods/Python/ranking-methods.py b/Task/Ranking-methods/Python/ranking-methods.py new file mode 100644 index 0000000000..3e980aaf00 --- /dev/null +++ b/Task/Ranking-methods/Python/ranking-methods.py @@ -0,0 +1,74 @@ +def mc_rank(iterable, start=1): + """Modified competition ranking""" + lastresult, fifo = None, [] + for n, item in enumerate(iterable, start-1): + if item[0] == lastresult: + fifo += [item] + else: + while fifo: + yield n, fifo.pop(0) + lastresult, fifo = item[0], fifo + [item] + while fifo: + yield n+1, fifo.pop(0) + + +def sc_rank(iterable, start=1): + """Standard competition ranking""" + lastresult, lastrank = None, None + for n, item in enumerate(iterable, start): + if item[0] == lastresult: + yield lastrank, item + else: + yield n, item + lastresult, lastrank = item[0], n + + +def d_rank(iterable, start=1): + """Dense ranking""" + lastresult, lastrank = None, start - 1, + for item in iterable: + if item[0] == lastresult: + yield lastrank, item + else: + lastresult, lastrank = item[0], lastrank + 1 + yield lastrank, item + + +def o_rank(iterable, start=1): + """Ordinal ranking""" + yield from enumerate(iterable, start) + + +def f_rank(iterable, start=1): + """Fractional ranking""" + last, fifo = None, [] + for n, item in enumerate(iterable, start): + if item[0] != last: + if fifo: + mean = sum(f[0] for f in fifo) / len(fifo) + while fifo: + yield mean, fifo.pop(0)[1] + last = item[0] + fifo.append((n, item)) + if fifo: + mean = sum(f[0] for f in fifo) / len(fifo) + while fifo: + yield mean, fifo.pop(0)[1] + + +if __name__ == '__main__': + scores = [(44, 'Solomon'), + (42, 'Jason'), + (42, 'Errol'), + (41, 'Garry'), + (41, 'Bernard'), + (41, 'Barry'), + (39, 'Stephen')] + + print('\nScores to be ranked (best first):') + for s in scores: + print(' %2i %s' % (s )) + for ranker in [sc_rank, mc_rank, d_rank, o_rank, f_rank]: + print('\n%s:' % ranker.__doc__) + for rank, score in ranker(scores): + print(' %3g, %r' % (rank, score)) diff --git a/Task/Ranking-methods/README b/Task/Ranking-methods/README new file mode 100644 index 0000000000..7b1ed44ebb --- /dev/null +++ b/Task/Ranking-methods/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Ranking_methods diff --git a/Task/Ranking-methods/Racket/ranking-methods.rkt b/Task/Ranking-methods/Racket/ranking-methods.rkt new file mode 100644 index 0000000000..6afae2d685 --- /dev/null +++ b/Task/Ranking-methods/Racket/ranking-methods.rkt @@ -0,0 +1,77 @@ +#lang racket +;; Tim-brown 2014-09-11 + +;; produces a ranking according to ranking function: rfn +;; INPUT: +;; lst : (list (score . details)) +;; rfn : (length-scores) +;; -> (values +;; ranks-added ; how many ranks to add for the next iteration +;; (idx . rest -> rank-offset)) ; function that produces the rank for the idx^th element +;; ; in the scoring (arity must be >= 1) +(define (rank-list all-scores rfn) + (let loop ((rank-0 0) (lst (sort all-scores > #:key car)) (acc empty)) + (cond + [(null? lst) acc] + [else + (define 1st-score (caar lst)) + (define (ties-with-1st? cand) (= (car cand) 1st-score)) + (define-values (tied unranked) (splitf-at lst ties-with-1st?)) + ;; all ranking functions should properly handle a singleton tied list + (define tied-len (length tied)) + (define tied? (> tied-len 1)) + (define-values (ranks-added rank-offset-fn) (rfn tied-len)) + (define ranked-tied (for/list ((t (in-list tied)) (i (in-naturals 1))) + (list* tied? (+ rank-0 (rank-offset-fn i)) t))) + (loop (+ ranks-added rank-0) unranked (append acc ranked-tied))]))) + +;; Ties share what would have been their first ordinal number +(define (rank-function:Standard l) + (values l (thunk* 1))) + +;; Ties share what would have been their last ordinal number +(define (rank-function:Modified l) + (values l (thunk* l))) + +;; Ties share the next available integer +(define (rank-function:Dense l) + (values 1 (thunk* 1))) + +;; Competitors take the next available integer. Ties are not treated otherwise +(define (rank-function:Ordinal l) + (values l (λ (n . _) n))) + +;; Ties share the mean of what would have been their ordinal numbers +(define (rank-function:Fractional l) + (values l (thunk* (/ (+ l 1) 2)))) + +(define score-board + '((44 . Solomon) + (42 . Jason) + (42 . Errol) + (41 . Garry) + (41 . Bernard) + (41 . Barry) + (39 . Stephen))) + +(define format-number + (match-lambda + [(? integer? i) i] + [(and f (app numerator n) (app denominator d)) + (define-values (q r) (quotient/remainder n d)) + (format "~a ~a/~a" q r d)])) + +(for ((fn (list + rank-function:Standard + rank-function:Modified + rank-function:Dense + rank-function:Ordinal + rank-function:Fractional))) + (printf "Function: ~s~%" fn) + (for ((r (in-list (rank-list score-board fn)))) + (printf "~a ~a\t~a\t~a~%" + (if (car r) "=" " ") + (format-number (cadr r)) + (caddr r) + (cdddr r))) + (newline)) diff --git a/Task/Ranking-methods/Ruby/ranking-methods.rb b/Task/Ranking-methods/Ruby/ranking-methods.rb new file mode 100644 index 0000000000..94d6fdcdc0 --- /dev/null +++ b/Task/Ranking-methods/Ruby/ranking-methods.rb @@ -0,0 +1,23 @@ +ar = "44 Solomon +42 Jason +42 Errol +41 Garry +41 Bernard +41 Barry +39 Stephen".lines.map{|line| line.split} + +grouped = ar.group_by{|pair| pair.delete_at(0).to_i} +s_rnk = 1 +m_rnk = o_rnk = f_rnk = 0 +puts "stand.\tmod.\tdense\tord.\tfract." + +grouped.each.with_index do |(score, names), i| + d_rnk = i + 1 + m_rnk += names.flatten!.size + f_rnk = (s_rnk + m_rnk)/2.0 + names.each do |name| + o_rnk += 1 + puts "#{s_rnk}\t#{m_rnk}\t#{d_rnk}\t#{o_rnk}\t#{f_rnk.to_s.gsub(".0","")}\t#{score} #{name}" + end + s_rnk += names.size +end diff --git a/Task/Ranking-methods/Scala/ranking-methods.scala b/Task/Ranking-methods/Scala/ranking-methods.scala new file mode 100644 index 0000000000..0e8ae7acf2 --- /dev/null +++ b/Task/Ranking-methods/Scala/ranking-methods.scala @@ -0,0 +1,44 @@ +object RankingMethods extends App { + case class Score(score: Int, name: String) // incoming data + case class Rank[Precision](rank: Precision, names: List[String]) // outgoing results (can be int or double) + case class State[Precision](n: Int, done: List[Rank[Precision]]) { // internal state, no mutable variables + def next(n: Int, next: Rank[Precision]) = State(n, next :: done) + } + def grouped[Precision](list: List[Score]) = // group names together by score, with highest first + (scala.collection.immutable.TreeMap[Int, List[Score]]() ++ list.groupBy(-_.score)) + .values.map(_.map(_.name)).foldLeft(State[Precision](1, Nil)) _ + + // Ranking methods: + + def rankStandard(list: List[Score]) = + grouped[Int](list){case (state, names) => state.next(state.n+names.length, Rank(state.n, names))}.done.reverse + + def rankModified(list: List[Score]) = + rankStandard(list).map(r => Rank(r.rank+r.names.length-1, r.names)) + + def rankDense(list: List[Score]) = + grouped[Int](list){case (state, names) => state.next(state.n+1, Rank(state.n, names))}.done.reverse + + def rankOrdinal(list: List[Score]) = + list.zipWithIndex.map{case (score, n) => Rank(n+1, List(score.name))} + + def rankFractional(list: List[Score]) = + rankStandard(list).map(r => Rank((2*r.rank+r.names.length-1.0)/2, r.names)) + + // Tests: + + def parseScores(s: String) = s split "\\s+" match {case Array(s,n) => Score(s.toInt, n)} + val test = List("44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen").map(parseScores) + + println("Standard:") + println(rankStandard(test) mkString "\n") + println("\nModified:") + println(rankModified(test) mkString "\n") + println("\nDense:") + println(rankDense(test) mkString "\n") + println("\nOrdinal:") + println(rankOrdinal(test) mkString "\n") + println("\nFractional:") + println(rankFractional(test) mkString "\n") + +} diff --git a/Task/Ranking-methods/Tcl/ranking-methods.tcl b/Task/Ranking-methods/Tcl/ranking-methods.tcl new file mode 100644 index 0000000000..c380a5caca --- /dev/null +++ b/Task/Ranking-methods/Tcl/ranking-methods.tcl @@ -0,0 +1,56 @@ +proc rank {rankingMethod sortedList} { + # Extract the groups in the data (this is pointless for ordinal...) + set s [set group [set groups {}]] + foreach {score who} $sortedList { + if {$score != $s} { + lappend groups [llength $group] + set s $score + set group {} + } + lappend group $who + } + lappend groups [llength $group] + # Construct the rankings; note that we have a zero-sized leading group + set n 1; set m 0 + foreach g $groups { + switch $rankingMethod { + standard { + lappend result {*}[lrepeat $g $n] + incr n $g + } + modified { + lappend result {*}[lrepeat $g [incr m $g]] + } + dense { + lappend result {*}[lrepeat $g $m] + incr m + } + ordinal { + for {set i 0} {$i < $g} {incr i} { + lappend result [incr m] + } + } + fractional { + set val [expr {($n + [incr n $g] - 1) / 2.0}] + lappend result {*}[lrepeat $g [format %g $val]] + } + } + } + return $result +} + +set data { + 44 Solomon + 42 Jason + 42 Errol + 41 Garry + 41 Bernard + 41 Barry + 39 Stephen +} +foreach method {standard modified dense ordinal fractional} { + puts "Using method '$method'...\n Rank\tScore\tWho" + foreach rank [rank $method $data] {score who} $data { + puts " $rank\t$score\t$who" + } +} diff --git a/Task/Rep-string/00DESCRIPTION b/Task/Rep-string/00DESCRIPTION new file mode 100644 index 0000000000..0c24faa753 --- /dev/null +++ b/Task/Rep-string/00DESCRIPTION @@ -0,0 +1,22 @@ +Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''. + +For example, the string '10011001100' is a rep-string as the leftmost four characters of '1001' are repeated three times and truncated on the right to give the original string. + +Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string. + +The task is to: +* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). +* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. +* Use the function to indicate the repeating substring if any, in the following: +
'1001110011'
+'1110111011'
+'0010010010'
+'1010101010'
+'1111111111'
+'0100101101'
+'0100100'
+'101'
+'11'
+'00'
+'1'
+* Show your output on this page. diff --git a/Task/Rep-string/ALGOL-68/rep-string.alg b/Task/Rep-string/ALGOL-68/rep-string.alg new file mode 100644 index 0000000000..89215df160 --- /dev/null +++ b/Task/Rep-string/ALGOL-68/rep-string.alg @@ -0,0 +1,68 @@ +# procedure to find the longest rep-string in a given string # +# the input string is not validated to contain only "0" and "1" characters # +PROC longest rep string = ( STRING input )STRING: +BEGIN + + STRING result := ""; + + # ensure the string we are working on has a lower-bound of 1 # + STRING str = input[ AT 1 ]; + + # work backwards from half the input string looking for a rep-string # + FOR string length FROM UPB str OVER 2 BY -1 TO 1 + WHILE + STRING left substring = str[ 1 : string length ]; + # if the left substgring repeated a sufficient number of times # + # (truncated on the right) is equal to the original string, then # + # we have found the longest rep-string # + STRING repeated string = ( left substring + * ( ( UPB str OVER string length ) + 1 ) + )[ 1 : UPB str ]; + IF str = repeated string + THEN + # found a rep-string # + result := left substring; + FALSE + ELSE + # not a rep-string, keep looking # + TRUE + FI + DO + SKIP + OD; + + result +END; # longest rep string # + + +# test the longest rep string procedure # +main: +( + + []STRING tests = ( "1001110011" + , "1110111011" + , "0010010010" + , "1010101010" + , "1111111111" + , "0100101101" + , "0100100" + , "101" + , "11" + , "00" + , "1" + ); + + FOR test number FROM LWB tests TO UPB tests + DO + STRING rep string = longest rep string( tests[ test number ] ); + print( ( tests[ test number ] + , ": " + , IF rep string = "" + THEN "no rep string" + ELSE "longest rep string: """ + rep string + """" + FI + , newline + ) + ) + OD +) diff --git a/Task/Rep-string/Ada/rep-string.ada b/Task/Rep-string/Ada/rep-string.ada new file mode 100644 index 0000000000..43e9b39bf4 --- /dev/null +++ b/Task/Rep-string/Ada/rep-string.ada @@ -0,0 +1,31 @@ +with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed; + +procedure Rep_String is + + function Find_Largest_Rep_String(S:String) return String is + L: Natural := S'Length; + begin + for I in reverse 1 .. L/2 loop + declare + use Ada.Strings.Fixed; + T: String := S(S'First .. S'First + I-1); -- the first I characters of S + U: String := (1+(L/I)) * T; -- repeat T so often that U'Length >= L + begin -- compare first L characers of U with S + if U(U'First .. U'First + S'Length -1) = S then + return T; -- T is a rep-string + end if; + end; + end loop; + return ""; -- no rep string; + end Find_Largest_Rep_String; + + X: String := Ada.Command_Line.Argument(1); + Y: String := Find_Largest_Rep_String(X); + +begin + if Y="" then + Ada.Text_IO.Put_Line("No rep-string for """ & X & """"); + else + Ada.Text_IO.Put_Line("Longest rep-string for """& X &""": """& Y &""""); + end if; +end Rep_String; diff --git a/Task/Rep-string/AutoHotkey/rep-string.ahk b/Task/Rep-string/AutoHotkey/rep-string.ahk new file mode 100644 index 0000000000..aad80a04e2 --- /dev/null +++ b/Task/Rep-string/AutoHotkey/rep-string.ahk @@ -0,0 +1,19 @@ +In := ["1001110011", "1110111011", "0010010010", "1010101010" + , "1111111111", "0100101101", "0100100", "101", "11", "00", "1"] +for k, v in In + Out .= RepString(v) "`t" v "`n" +MsgBox, % Out + +RepString(s) { + Loop, % StrLen(s) // 2 { + i := A_Index + Loop, Parse, s + { + pos := Mod(A_Index, i) + if (A_LoopField != SubStr(s, !pos ? i : pos, 1)) + continue, 2 + } + return SubStr(s, 1, i) + } + return "N/A" +} diff --git a/Task/Rep-string/Bracmat/rep-string.bracmat b/Task/Rep-string/Bracmat/rep-string.bracmat new file mode 100644 index 0000000000..ea31957418 --- /dev/null +++ b/Task/Rep-string/Bracmat/rep-string.bracmat @@ -0,0 +1,36 @@ +( ( rep-string + = reps L x y + . ( reps + = x y z + . !arg:(?x.?y) + & ( @(!y:!x ?z)&reps$(!x.!z) + | @(!x:!y ?) + ) + ) + & ( :?L + & @( !arg + : %?x + !x + ( ?y + & reps$(!x.!y) + & !x !L:?L + & ~ + ) + ) + | !L: + & out$(str$(!arg " is not a rep-string")) + | out$(!arg ":" !L) + ) + ) +& rep-string$1001110011 +& rep-string$1110111011 +& rep-string$0010010010 +& rep-string$1010101010 +& rep-string$1111111111 +& rep-string$0100101101 +& rep-string$0100100 +& rep-string$101 +& rep-string$11 +& rep-string$00 +& rep-string$1 +); diff --git a/Task/Rep-string/C++/rep-string.cpp b/Task/Rep-string/C++/rep-string.cpp new file mode 100644 index 0000000000..fb278effc8 --- /dev/null +++ b/Task/Rep-string/C++/rep-string.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +bool is_repstring( const std::string & teststring , std::string & repunit ) { + std::string regex( "^(.+)\\1+(.*)$" ) ; + boost::regex e ( regex ) ; + boost::smatch what ; + if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { + std::string firstbracket( what[1 ] ) ; + std::string secondbracket( what[ 2 ] ) ; + if ( firstbracket.length( ) >= secondbracket.length( ) && + firstbracket.find( secondbracket ) != std::string::npos ) { + repunit = firstbracket ; + } + } + return !repunit.empty( ) ; +} + +int main( ) { + std::vector teststrings { "1001110011" , "1110111011" , "0010010010" , + "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; + std::string theRep ; + for ( std::string myString : teststrings ) { + if ( is_repstring( myString , theRep ) ) { + std::cout << myString << " is a rep string! Here is a repeating string:\n" ; + std::cout << theRep << " " ; + } + else { + std::cout << myString << " is no rep string!" ; + } + theRep.clear( ) ; + std::cout << std::endl ; + } + return 0 ; +} diff --git a/Task/Rep-string/C/rep-string.c b/Task/Rep-string/C/rep-string.c new file mode 100644 index 0000000000..7093551ca6 --- /dev/null +++ b/Task/Rep-string/C/rep-string.c @@ -0,0 +1,34 @@ +#include +#include + +int repstr(char *str) +{ + if (!str) return 0; + + size_t sl = strlen(str) / 2; + while (sl > 0) { + if (strstr(str, str + sl) == str) + return sl; + --sl; + } + + return 0; +} + +int main(void) +{ + char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111", + "0100101101", "0100100", "101", "11", "00", "1" }; + + size_t strslen = sizeof(strs) / sizeof(strs[0]); + size_t i; + for (i = 0; i < strslen; ++i) { + int n = repstr(strs[i]); + if (n) + printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]); + else + printf("\"%s\" = not a rep-string\n", strs[i]); + } + + return 0; +} diff --git a/Task/Rep-string/D/rep-string.d b/Task/Rep-string/D/rep-string.d new file mode 100644 index 0000000000..da05f1449a --- /dev/null +++ b/Task/Rep-string/D/rep-string.d @@ -0,0 +1,44 @@ +import std.stdio, std.string, std.conv, std.range, std.algorithm, + std.ascii, std.typecons; + +Nullable!(size_t, 0) repString1(in string s) pure nothrow @safe @nogc +in { + //assert(s.all!isASCII); + assert(s.representation.all!isASCII); +} body { + immutable sr = s.representation; + foreach_reverse (immutable n; 1 .. sr.length / 2 + 1) + if (sr.take(n).cycle.take(sr.length).equal(sr)) + return typeof(return)(n); + return typeof(return)(); +} + +Nullable!(size_t, 0) repString2(in string s) pure @safe /*@nogc*/ +in { + assert(s.countchars("01") == s.length); +} body { + immutable bits = s.to!ulong(2); + + foreach_reverse (immutable left; 1 .. s.length / 2 + 1) { + immutable right = s.length - left; + if ((bits ^ (bits >> left)) == ((bits >> right) << right)) + return typeof(return)(left); + } + return typeof(return)(); +} + +void main() { + immutable words = "1001110011 1110111011 0010010010 1010101010 + 1111111111 0100101101 0100100 101 11 00 1".split; + + foreach (immutable w; words) { + immutable r1 = w.repString1; + //assert(r1 == w.repString2); + immutable r2 = w.repString2; + assert((r1.isNull && r2.isNull) || r1 == r2); + if (r1.isNull) + writeln(w, " (no repeat)"); + else + writefln("%(%s %)", w.chunks(r1)); + } +} diff --git a/Task/Rep-string/Go/rep-string.go b/Task/Rep-string/Go/rep-string.go new file mode 100644 index 0000000000..f1727da9fb --- /dev/null +++ b/Task/Rep-string/Go/rep-string.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "strings" +) + +func rep(s string) int { + for x := len(s) / 2; x > 0; x-- { + if strings.HasPrefix(s, s[x:]) { + return x + } + } + return 0 +} + +const m = ` +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1` + +func main() { + for _, s := range strings.Fields(m) { + if n := rep(s); n > 0 { + fmt.Printf("%q %d rep-string %q\n", s, n, s[:n]) + } else { + fmt.Printf("%q not a rep-string\n", s) + } + } +} diff --git a/Task/Rep-string/Haskell/rep-string.hs b/Task/Rep-string/Haskell/rep-string.hs new file mode 100644 index 0000000000..37a81f9701 --- /dev/null +++ b/Task/Rep-string/Haskell/rep-string.hs @@ -0,0 +1,45 @@ +import Data.List (maximumBy, inits) + +repstring :: String -> Maybe String +-- empty strings are not rep strings +repstring [] = Nothing +-- strings with only one character are not rep strings +repstring (_:[]) = Nothing +repstring xs + | any (`notElem` "01") xs = Nothing + | otherwise = longest xs + where + -- length of the original string + lxs = length xs + -- half that length + lq2 = lxs `quot` 2 + -- make a string of same length using repetitions of a part + -- of the original string, and also return the substring used + subrepeat x = (x, take lxs $ concat $ repeat x) + -- check if a repeated string matches the original string + sndValid (_, ys) = ys == xs + -- make all possible strings out of repetitions of parts of + -- the original string, which have max. length lq2 + possible = map subrepeat . take lq2 . tail . inits + -- filter only valid possibilities, and return the substrings + -- used for building them + valid = map fst . filter sndValid . possible + -- see which string is longer + compLength a b = compare (length a) (length b) + -- get the longest substring that, repeated, builds a string + -- that matches the original string + longest ys = case valid ys of + [] -> Nothing + zs -> Just $ maximumBy compLength zs + +main :: IO () +main = do + mapM_ processIO examples + where + examples = ["1001110011", "1110111011", "0010010010", + "1010101010", "1111111111", "0100101101", "0100100", + "101", "11", "00", "1"] + process = maybe "Not a rep string" id . repstring + processIO xs = do + putStr (xs ++ ": ") + putStrLn $ process xs diff --git a/Task/Rep-string/Icon/rep-string.icon b/Task/Rep-string/Icon/rep-string.icon new file mode 100644 index 0000000000..2397077df1 --- /dev/null +++ b/Task/Rep-string/Icon/rep-string.icon @@ -0,0 +1,14 @@ +procedure main(A) + every write(s := !A,": ",(repString(s) | "Not a rep string!")\1) +end + +procedure repString(s) + rs := s[1+:*s/2] + while (*rs > 0) & (s ~== lrepl(rs,*s,rs)) do rs := rs[1:-1] + return (*rs > 0, rs) +end + +procedure lrepl(s1,n,s2) # The standard left() procedure won't work. + while *s1 < n do s1 ||:= s2 + return s1[1+:n] +end diff --git a/Task/Rep-string/J/rep-string-1.j b/Task/Rep-string/J/rep-string-1.j new file mode 100644 index 0000000000..9a318aa21f --- /dev/null +++ b/Task/Rep-string/J/rep-string-1.j @@ -0,0 +1,4 @@ +replengths=: >:@i.@<.@-:@# +rep=: $@] $ $ + +isRepStr=: +./@((] -: rep)"0 1~ replengths) diff --git a/Task/Rep-string/J/rep-string-2.j b/Task/Rep-string/J/rep-string-2.j new file mode 100644 index 0000000000..d3ad3d95a8 --- /dev/null +++ b/Task/Rep-string/J/rep-string-2.j @@ -0,0 +1,17 @@ + isRepStr '1001110011' +1 + Tests=: noun define +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1 +) + isRepStr;._2 Tests NB. run all tests +1 1 1 1 1 0 1 0 1 1 0 diff --git a/Task/Rep-string/J/rep-string-3.j b/Task/Rep-string/J/rep-string-3.j new file mode 100644 index 0000000000..d94fcc2593 --- /dev/null +++ b/Task/Rep-string/J/rep-string-3.j @@ -0,0 +1 @@ +nRepStr=: 0 -.~ (([ * ] -: rep)"0 1~ replengths) diff --git a/Task/Rep-string/J/rep-string-4.j b/Task/Rep-string/J/rep-string-4.j new file mode 100644 index 0000000000..786f74a0d3 --- /dev/null +++ b/Task/Rep-string/J/rep-string-4.j @@ -0,0 +1,11 @@ + ":@nRepStr;._2 Tests +5 +4 +3 +2 4 +1 2 3 4 5 + +3 + +1 +1 diff --git a/Task/Rep-string/Java/rep-string.java b/Task/Rep-string/Java/rep-string.java new file mode 100644 index 0000000000..b5d7f04d2c --- /dev/null +++ b/Task/Rep-string/Java/rep-string.java @@ -0,0 +1,30 @@ +public class RepString { + + static final String[] input = {"1001110011", "1110111011", "0010010010", + "1010101010", "1111111111", "0100101101", "0100100", "101", "11", + "00", "1", "0100101"}; + + public static void main(String[] args) { + for (String s : input) + System.out.printf("%s : %s%n", s, repString(s)); + } + + static String repString(String s) { + int len = s.length(); + outer: + for (int part = len / 2; part > 0; part--) { + int tail = len % part; + if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) + continue; + for (int j = 0; j < len / part - 1; j++) { + int a = j * part; + int b = (j + 1) * part; + int c = (j + 2) * part; + if (!s.substring(a, b).equals(s.substring(b, c))) + continue outer; + } + return s.substring(0, part); + } + return "none"; + } +} diff --git a/Task/Rep-string/Maple/rep-string-1.maple b/Task/Rep-string/Maple/rep-string-1.maple new file mode 100644 index 0000000000..8cb1af466a --- /dev/null +++ b/Task/Rep-string/Maple/rep-string-1.maple @@ -0,0 +1,8 @@ +repstr? := proc( s :: string ) + local per := StringTools:-Period( s ); + if 2 * per <= length( s ) then + true, s[ 1 .. per ] + else + false, "" + end if +end proc: diff --git a/Task/Rep-string/Maple/rep-string-2.maple b/Task/Rep-string/Maple/rep-string-2.maple new file mode 100644 index 0000000000..014209b47d --- /dev/null +++ b/Task/Rep-string/Maple/rep-string-2.maple @@ -0,0 +1,16 @@ +> Test := ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111", \ + "0100101101", "0100100", "101", "11", "00", "1"]: +> for s in Test do +> printf( "%*s\t%5s %s\n", 3 + max(map(length,Test)), s, repstr?( s ) ) +> end do: + 1001110011 true 10011 + 1110111011 true 1110 + 0010010010 true 001 + 1010101010 true 10 + 1111111111 true 1 + 0100101101 false + 0100100 true 010 + 101 false + 11 true 1 + 00 true 0 + 1 false diff --git a/Task/Rep-string/Mathematica/rep-string-1.math b/Task/Rep-string/Mathematica/rep-string-1.math new file mode 100644 index 0000000000..d5edd18ac6 --- /dev/null +++ b/Task/Rep-string/Mathematica/rep-string-1.math @@ -0,0 +1 @@ +RepStringQ[strin_String]:=StringCases[strin,StartOfString~~Repeated[x__,{2,\[Infinity]}]~~y___~~EndOfString/;StringMatchQ[x,StartOfString~~y~~___]:>x, Overlaps -> All] diff --git a/Task/Rep-string/Mathematica/rep-string-2.math b/Task/Rep-string/Mathematica/rep-string-2.math new file mode 100644 index 0000000000..ef9e7fe6ec --- /dev/null +++ b/Task/Rep-string/Mathematica/rep-string-2.math @@ -0,0 +1,2 @@ +str={"1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"}; +{#,RepStringQ[#]}&/@str//Grid diff --git a/Task/Rep-string/NetRexx/rep-string.netrexx b/Task/Rep-string/NetRexx/rep-string.netrexx new file mode 100644 index 0000000000..7e1a9c7fcb --- /dev/null +++ b/Task/Rep-string/NetRexx/rep-string.netrexx @@ -0,0 +1,61 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +/* REXX *************************************************************** +* 11.05.2013 Walter Pachl +**********************************************************************/ +runSample(arg) +return + +/** + * Test for rep-strings + * @param s_str a string to check for rep-strings + * @return Rexx string: boolean indication of reps, length, repeated value + */ +method repstring(s_str) public static + s_str_n = s_str.length() + rep_str = '' + Loop lx = s_str.length() % 2 to 1 By -1 + If s_str.substr(lx + 1, lx) = s_str.left(lx) Then Leave lx + End lx + If lx > 0 Then Do label reps + rep_str = s_str.left(lx) + Loop ix = 1 By 1 + If s_str.substr(ix * lx + 1, lx) <> rep_str Then + Leave ix + End ix + If rep_str.copies(s_str_n).left(s_str.length()) <> s_str Then + rep_str = '' + End reps + Return (rep_str.length() > 0) rep_str.length() rep_str + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + parse arg samples + if samples = '' then - + samples = - + '1001110011' - + '1110111011' - + '0010010010' - + '1010101010' - + '1111111111' - + '0100101101' - + '0100100' - + '101' - + '11' - + '00' - + '1' + + loop w_ = 1 to samples.words() + in_str = samples.word(w_) + parse repstring(in_str) is_rep_str rep_str_len rep_str + + sq = ''''in_str'''' + tstrlen = sq.length().max(20) + sq=sq.right(tstrlen) + if is_rep_str then + Say sq 'has a repetition length of' rep_str_len "i.e. '"rep_str"'" + else + Say sq 'is not a repeated string' + end w_ + return diff --git a/Task/Rep-string/PARI-GP/rep-string.pari b/Task/Rep-string/PARI-GP/rep-string.pari new file mode 100644 index 0000000000..d5d8696572 --- /dev/null +++ b/Task/Rep-string/PARI-GP/rep-string.pari @@ -0,0 +1,3 @@ +rep(v)=for(i=1,#v\2,for(j=i+1,#v,if(v[j]!=v[j-i],next(2)));return(i));0; +v=["1001110011","1110111011","0010010010","1010101010","1111111111","0100101101","0100100","101","11","00","1"]; +for(i=1,#v,print(v[i]" "rep(Vec(v[i])))) diff --git a/Task/Rep-string/PL-I/rep-string.pli b/Task/Rep-string/PL-I/rep-string.pli new file mode 100644 index 0000000000..5137f41e65 --- /dev/null +++ b/Task/Rep-string/PL-I/rep-string.pli @@ -0,0 +1,19 @@ +rep: procedure options (main); /* 5 May 2015 */ + declare s bit (10) varying; + declare (i, k) fixed binary; + +main_loop: + do s = '1001110011'b, '1110111011'b, '0010010010'b, '1010101010'b, + '1111111111'b, '0100101101'b, '0100100'b, '101'b, '11'b, '00'b, '1'b; + k = length(s); + do i = k/2 to 1 by -1; + if substr(s, 1, i) = substr(s, i+1, i) then + do; + put skip edit (s, ' is a rep-string containing ', substr(s, 1, i) ) (a); + iterate main_loop; + end; + end; + put skip edit (s, ' is not a rep-string') (a); + end; + +end rep; diff --git a/Task/Rep-string/Perl-6/rep-string-1.pl6 b/Task/Rep-string/Perl-6/rep-string-1.pl6 new file mode 100644 index 0000000000..b6cc7b16ab --- /dev/null +++ b/Task/Rep-string/Perl-6/rep-string-1.pl6 @@ -0,0 +1,9 @@ +for <1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1> { + if /^ (.+) $0+: (.*$) / { + my $rep = $0.chars; + say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2); + } + else { + say "$_ (no repeat)"; + } +} diff --git a/Task/Rep-string/Perl-6/rep-string-2.pl6 b/Task/Rep-string/Perl-6/rep-string-2.pl6 new file mode 100644 index 0000000000..2acf3cce1e --- /dev/null +++ b/Task/Rep-string/Perl-6/rep-string-2.pl6 @@ -0,0 +1,17 @@ +sub repstr(Str $s) { + my $bits = :2($s); + for reverse 1 .. $s.chars div 2 -> $left { + my $right = $s.chars - $left; + return $left if $bits +^ ($bits +> $left) == $bits +> $right +< $right; + } +} + + +for '1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1'.words { + if repstr $_ -> $rep { + say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2); + } + else { + say "$_ (no repeat)"; + } +} diff --git a/Task/Rep-string/Perl/rep-string.pl b/Task/Rep-string/Perl/rep-string.pl new file mode 100644 index 0000000000..e48b666019 --- /dev/null +++ b/Task/Rep-string/Perl/rep-string.pl @@ -0,0 +1,8 @@ +foreach (qw(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1)) { + print "$_\n"; + if (/^(.+)\1+(.*$)(?(?{ substr($1, 0, length $2) eq $2 })|(?!))/) { + print ' ' x length $1, "$1\n\n"; + } else { + print " (no repeat)\n\n"; + } +} diff --git a/Task/Rep-string/Prolog/rep-string.pro b/Task/Rep-string/Prolog/rep-string.pro new file mode 100644 index 0000000000..db77f675cb --- /dev/null +++ b/Task/Rep-string/Prolog/rep-string.pro @@ -0,0 +1,32 @@ +:- use_module(library(func)). + +%% Implementation logic: + +test_for_repstring(String, (String, Result, Reps)) :- + ( setof(Rep, repstring(String, Rep), Reps) + -> Result = 'no repstring' + ; Result = 'repstrings', Reps = [] + ). + +repstring(Codes, R) :- + RepLength = between(1) of (_//2) of length $ Codes, + length(R, RepLength), + phrase( (rep(R), prefix(~,R)), + Codes). + +rep(X) --> X, X. +rep(X) --> X, rep(X). + + +%% Demonstration output: + +test_strings([`1001110011`, `1110111011`, `0010010010`, `1010101010`, + `1111111111`, `0100101101`, `0100100`, `101`, `11`, `00`, `1`]). + +report_repstring((S,Result,Reps)):- + format('~s -- ~w: ', [S, Result]), + foreach(member(R, Reps), format('~s, ', [R])), nl. + +report_repstrings :- + Results = maplist(test_for_repstring) $ test_strings(~), + maplist(report_repstring, Results). diff --git a/Task/Rep-string/Python/rep-string-1.py b/Task/Rep-string/Python/rep-string-1.py new file mode 100644 index 0000000000..65a37f811a --- /dev/null +++ b/Task/Rep-string/Python/rep-string-1.py @@ -0,0 +1,23 @@ +def is_repeated(text): + 'check if the first part of the string is repeated throughout the string' + for x in range(len(text)//2, 0, -1): + if text.startswith(text[x:]): return x + return 0 + +matchstr = """\ +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1 +""" +for line in matchstr.split(): + ln = is_repeated(line) + print('%r has a repetition length of %i i.e. %s' + % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string')) diff --git a/Task/Rep-string/Python/rep-string-2.py b/Task/Rep-string/Python/rep-string-2.py new file mode 100644 index 0000000000..fa8371fae8 --- /dev/null +++ b/Task/Rep-string/Python/rep-string-2.py @@ -0,0 +1,30 @@ +>>> def reps(text): + return [text[:x] for x in range(1, 1 + len(text) // 2) + if text.startswith(text[x:])] + +>>> matchstr = """\ +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1 +""" +>>> print('\n'.join('%r has reps %r' % (line, reps(line)) for line in matchstr.split())) +'1001110011' has reps ['10011'] +'1110111011' has reps ['1110'] +'0010010010' has reps ['001'] +'1010101010' has reps ['10', '1010'] +'1111111111' has reps ['1', '11', '111', '1111', '11111'] +'0100101101' has reps [] +'0100100' has reps ['010'] +'101' has reps [] +'11' has reps ['1'] +'00' has reps ['0'] +'1' has reps [] +>>> diff --git a/Task/Rep-string/Python/rep-string-3.py b/Task/Rep-string/Python/rep-string-3.py new file mode 100644 index 0000000000..1a8837852b --- /dev/null +++ b/Task/Rep-string/Python/rep-string-3.py @@ -0,0 +1,25 @@ +import re + +matchstr = """\ +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1""" + +def _checker(matchobj): + g0, (g1, g2, g3, g4) = matchobj.group(0), matchobj.groups() + if not g4 and g1 and g1.startswith(g3): + return '%r repeats %r' % (g0, g1) + return '%r is not a rep-string' % (g0,) + +def checkit(txt): + print(re.sub(r'(.+)(\1+)(.*)|(.*)', _checker, txt)) + +checkit(matchstr) diff --git a/Task/Rep-string/README b/Task/Rep-string/README new file mode 100644 index 0000000000..494f10caef --- /dev/null +++ b/Task/Rep-string/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Rep-string diff --git a/Task/Rep-string/REXX/rep-string-1.rexx b/Task/Rep-string/REXX/rep-string-1.rexx new file mode 100644 index 0000000000..018de13705 --- /dev/null +++ b/Task/Rep-string/REXX/rep-string-1.rexx @@ -0,0 +1,52 @@ +/* REXX *************************************************************** +* 11.05.2013 Walter Pachl +* 14.05.2013 Walter Pachl extend to show additional rep-strings +**********************************************************************/ +Call repstring '1001110011' +Call repstring '1110111011' +Call repstring '0010010010' +Call repstring '1010101010' +Call repstring '1111111111' +Call repstring '0100101101' +Call repstring '0100100' +Call repstring '101' +Call repstring '11' +Call repstring '00' +Call repstring '1' +Exit + +repstring: +Parse Arg s +sq=''''s'''' +n=length(s) +Do l=length(s)%2 to 1 By -1 + If substr(s,l+1,l)=left(s,l) Then Leave + End +If l>0 Then Do + rep_str=left(s,l) + Do i=1 By 1 + If substr(s,i*l+1,l)<>rep_str Then + Leave + End + If left(copies(rep_str,n),length(s))=s Then Do + Call show_rep rep_str /* show result */ + Do i=length(rep_str)-1 To 1 By -1 /* look for shorter rep_str-s */ + rep_str=left(s,i) + If left(copies(rep_str,n),length(s))=s Then + Call show_rep rep_str + End + End + Else + Call show_norep + End +Else + Call show_norep +Return + +show_rep: + Parse Arg rs + Say right(sq,12) 'has a repetition length of' length(rs) 'i.e.' ''''rs'''' + Return +show_norep: + Say right(sq,12) 'is not a repeated string' + Return diff --git a/Task/Rep-string/REXX/rep-string-2.rexx b/Task/Rep-string/REXX/rep-string-2.rexx new file mode 100644 index 0000000000..391980301f --- /dev/null +++ b/Task/Rep-string/REXX/rep-string-2.rexx @@ -0,0 +1,13 @@ +/*REXX pgm determines if a str is a repStr, returns minimum len. repStr.*/ +s=1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 + /* [↑] a list of binary strings.*/ + do k=1 for words(s); _=word(s,k) /*process all the binary strings.*/ + say right(_,25) repString(_) /*show the original & the result.*/ + end /*k*/ /* [↑] "result" may be negatory.*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────REPSTRING subroutine───────────────*/ +repString: procedure; parse arg x; L=length(x); r@= ' rep string=' + do j=1 for L-1 while j<=L%2; p=left(x,j) /*WHILE tests max*/ + if left(copies(p,L),L)==x then return r@ left(p,15) '[length' j"]" + end /*j*/ /* [↑] we have found a repString*/ +return ' (no repetitions)' /*(sigh)∙∙∙ a failure to find rep*/ diff --git a/Task/Rep-string/Racket/rep-string.rkt b/Task/Rep-string/Racket/rep-string.rkt new file mode 100644 index 0000000000..1412fdfd67 --- /dev/null +++ b/Task/Rep-string/Racket/rep-string.rkt @@ -0,0 +1,26 @@ +#lang racket + +(define (rep-string str) + (define len (string-length str)) + (for/or ([n (in-range 1 len)]) + (and (let loop ([from n]) + (or (>= from len) + (let ([m (min (- len from) n)]) + (and (equal? (substring str from (+ from m)) + (substring str 0 m)) + (loop (+ n from)))))) + (<= n (quotient len 2)) + (substring str 0 n)))) + +(for ([str '("1001110011" + "1110111011" + "0010010010" + "1010101010" + "1111111111" + "0100101101" + "0100100" + "101" + "11" + "00" + "1")]) + (printf "~a => ~a\n" str (or (rep-string str) "not a rep-string"))) diff --git a/Task/Rep-string/Ruby/rep-string.rb b/Task/Rep-string/Ruby/rep-string.rb new file mode 100644 index 0000000000..09ba8b5379 --- /dev/null +++ b/Task/Rep-string/Ruby/rep-string.rb @@ -0,0 +1,16 @@ +ar = %w(1001110011 + 1110111011 + 0010010010 + 1010101010 + 1111111111 + 0100101101 + 0100100 + 101 + 11 + 00 + 1) + +ar.each do |str| + rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]} + puts str, rep_pos ? " "*rep_pos + str[0, rep_pos] : "(no repetition)", "" +end diff --git a/Task/Rep-string/Scala/rep-string.scala b/Task/Rep-string/Scala/rep-string.scala new file mode 100644 index 0000000000..e977e829fc --- /dev/null +++ b/Task/Rep-string/Scala/rep-string.scala @@ -0,0 +1,27 @@ +object RepString extends App { + def repsOf(s: String) = s.trim match { + case s if s.length < 2 => Nil + case s => (1 to (s.length/2)).map(s take _) + .filter(_ * s.length take s.length equals s) + } + + val tests = Array( + "1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1" + ) + def printReps(s: String) = repsOf(s) match { + case Nil => s+": NO" + case r => s+": YES ("+r.mkString(", ")+")" + } + val todo = if (args.length > 0) args else tests + todo.map(printReps).foreach(println) +} diff --git a/Task/Rep-string/Seed7/rep-string.seed7 b/Task/Rep-string/Seed7/rep-string.seed7 new file mode 100644 index 0000000000..9f82af9310 --- /dev/null +++ b/Task/Rep-string/Seed7/rep-string.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + +const func integer: repeatLength (in string: text) is func + result + var integer: length is 0; + local + var integer: pos is 0; + begin + for pos range succ(length(text) div 2) downto 1 until length <> 0 do + if startsWith(text, text[pos ..]) then + length := pred(pos); + end if; + end for; + end func; + +const proc: main is func + local + var string: line is ""; + var integer: length is 0; + begin + for line range [] ("1001110011", "1110111011", "0010010010", "1010101010", + "1111111111", "0100101101", "0100100", "101", "11", "00", "1") do + length := repeatLength(line); + if length = 0 then + writeln("No rep-string for " <& literal(line)); + else + writeln("Longest rep-string for " <& literal(line) <& ": " <& literal(line[.. length])); + end if; + end for; + end func; diff --git a/Task/Rep-string/Tcl/rep-string-1.tcl b/Task/Rep-string/Tcl/rep-string-1.tcl new file mode 100644 index 0000000000..150aaad0bf --- /dev/null +++ b/Task/Rep-string/Tcl/rep-string-1.tcl @@ -0,0 +1,11 @@ +proc repstring {text} { + set len [string length $text] + for {set i [expr {$len/2}]} {$i > 0} {incr i -1} { + set sub [string range $text 0 [expr {$i-1}]] + set eq [string repeat $sub [expr {int(ceil($len/double($i)))}]] + if {[string equal -length $len $text $eq]} { + return $sub + } + } + error "no repetition" +} diff --git a/Task/Rep-string/Tcl/rep-string-2.tcl b/Task/Rep-string/Tcl/rep-string-2.tcl new file mode 100644 index 0000000000..19cf2fc4e5 --- /dev/null +++ b/Task/Rep-string/Tcl/rep-string-2.tcl @@ -0,0 +1,12 @@ +foreach sample { + "1001110011" "1110111011" "0010010010" "1010101010" "1111111111" + "0100101101" "0100100" "101" "11" "00" "1" +} { + if {[catch { + set rep [repstring $sample] + puts [format "\"%s\" has repetition (length: %d) of \"%s\"" \ + $sample [string length $rep] $rep] + }]} { + puts [format "\"%s\" is not a repeated string" $sample] + } +} diff --git a/Task/Rep-string/UNIX-Shell/rep-string.sh b/Task/Rep-string/UNIX-Shell/rep-string.sh new file mode 100644 index 0000000000..c02c639c12 --- /dev/null +++ b/Task/Rep-string/UNIX-Shell/rep-string.sh @@ -0,0 +1,35 @@ +is_repeated() { + local str=$1 len rep part + for (( len = ${#str} / 2; len > 0; len-- )); do + part=${str:0:len} + rep="" + while (( ${#rep} < ${#str} )); do + rep+=$part + done + if [[ ${rep:0:${#str}} == $str ]] && (( $len < ${#str} )); then + echo "$part" + return 0 + fi + done + return 1 +} + +while read test; do + if part=$( is_repeated "$test" ); then + echo "$test is composed of $part repeated" + else + echo "$test is not a repeated string" + fi +done <Hey you, Bub!” would be shown reversed as: “Bub! you, Hey” +Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation forms part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. +'''Display''' the strings in order (1st, 2nd, 3rd, ···), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) + +;Input data +
+             (ten lines within the box)
+ line
+     ╔════════════════════════════════════════╗
+   1 ║  ---------- Ice and Fire ------------  ║
+   2 ║                                        ║  ◄─── a blank line here.
+   3 ║  fire, in end will world the say Some  ║
+   4 ║  ice. in say Some                      ║
+   5 ║  desire of tasted I've what From       ║
+   6 ║  fire. favor who those with hold I     ║
+   7 ║                                        ║  ◄─── a blank line here.
+   8 ║  ... elided paragraph last ...         ║
+   9 ║                                        ║  ◄─── a blank line here.
+  10 ║  Frost Robert -----------------------  ║
+     ╚════════════════════════════════════════╝
+
diff --git a/Task/Reverse-words-in-a-string/AWK/reverse-words-in-a-string.awk b/Task/Reverse-words-in-a-string/AWK/reverse-words-in-a-string.awk new file mode 100644 index 0000000000..a4b3794216 --- /dev/null +++ b/Task/Reverse-words-in-a-string/AWK/reverse-words-in-a-string.awk @@ -0,0 +1,22 @@ +# syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK +BEGIN { + text[++i] = "---------- Ice and Fire ------------" + text[++i] = "" + text[++i] = "fire, in end will world the say Some" + text[++i] = "ice. in say Some" + text[++i] = "desire of tasted I've what From" + text[++i] = "fire. favor who those with hold I" + text[++i] = "" + text[++i] = "... elided paragraph last ..." + text[++i] = "" + text[++i] = "Frost Robert -----------------------" + leng = i + for (i=1; i<=leng; i++) { + n = split(text[i],arr," ") + for (j=n; j>0; j--) { + printf("%s ",arr[j]) + } + printf("\n") + } + exit(0) +} diff --git a/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-1.ada b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-1.ada new file mode 100644 index 0000000000..912ff82d76 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-1.ada @@ -0,0 +1,11 @@ +package Simple_Parse is + -- a very simplistic parser, useful to split a string into words + + function Next_Word(S: String; Point: in out Positive) + return String; + -- a "word" is a sequence of non-space characters + -- if S(Point .. S'Last) holds at least one word W + -- then Next_Word increments Point by len(W) and returns W. + -- else Next_Word sets Point to S'Last+1 and returns "" + +end Simple_Parse; diff --git a/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-2.ada b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-2.ada new file mode 100644 index 0000000000..ba17de0924 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-2.ada @@ -0,0 +1,20 @@ +package body Simple_Parse is + + function Next_Word(S: String; Point: in out Positive) return String is + Start: Positive := Point; + Stop: Natural; + begin + while Start <= S'Last and then S(Start) = ' ' loop + Start := Start + 1; + end loop; -- now S(Start) is the first non-space, + -- or Start = S'Last+1 if S is empty or space-only + Stop := Start-1; -- now S(Start .. Stop) = "" + while Stop < S'Last and then S(Stop+1) /= ' ' loop + Stop := Stop + 1; + end loop; -- now S(Stop+1) is the first sopace after Start + -- or Stop = S'Last if there is no such space + Point := Stop+1; + return S(Start .. Stop); + end Next_Word; + +end Simple_Parse; diff --git a/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-3.ada b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-3.ada new file mode 100644 index 0000000000..905d1bbf78 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-3.ada @@ -0,0 +1,21 @@ +with Ada.Text_IO, Simple_Parse; + +procedure Reverse_Words is + + function Reverse_Words(S: String) return String is + Cursor: Positive := S'First; + Word: String := Simple_Parse.Next_Word(S, Cursor); + begin + if Word = "" then + return ""; + else + return Reverse_Words(S(Cursor .. S'Last)) & " " & Word; + end if; + end Reverse_Words; + + use Ada.Text_IO; +begin + while not End_Of_File loop + Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input + end loop; +end Reverse_Words; diff --git a/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime b/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime new file mode 100644 index 0000000000..5ed7842e08 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime @@ -0,0 +1,32 @@ +integer i, j, s; +list l, x; +data b; +file f; + +l_bill(l, 0, + "---------- Ice and Fire ------------", + "", + "fire, in end will world the say Some", + "ice. in say Some", + "desire of tasted I've what From", + "fire. favor who those with hold I", + "", + "... elided paragraph last ...", + "", + "Frost Robert -----------------------"); + +i = -l_length(l); +while (i) { + b_cast(b, l[i]); + f_b_affix(f, b); + f_list(f, x, 0); + j = l_length(x); + s = 0; + while (j) { + o_space(s); + s = 1; + o_text(x[j -= 1]); + } + o_newline(); + i += 1; +} diff --git a/Task/Reverse-words-in-a-string/Applesoft-BASIC/reverse-words-in-a-string.applesoft b/Task/Reverse-words-in-a-string/Applesoft-BASIC/reverse-words-in-a-string.applesoft new file mode 100644 index 0000000000..e8381c496d --- /dev/null +++ b/Task/Reverse-words-in-a-string/Applesoft-BASIC/reverse-words-in-a-string.applesoft @@ -0,0 +1,26 @@ +100 DATA"---------- ICE AND FIRE ------------" +110 DATA" " +120 DATA"FIRE, IN END WILL WORLD THE SAY SOME" +130 DATA"ICE. IN SAY SOME " +140 DATA"DESIRE OF TASTED I'VE WHAT FROM " +150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I " +160 DATA" " +170 DATA"... ELIDED PARAGRAPH LAST ... " +180 DATA" " +190 DATA"FROST ROBERT -----------------------" + +200 FOR L = 1 TO 10 +210 READ T$ +220 I = LEN(T$) +240 IF I THEN GOSUB 300 : PRINT W$; : IF I THEN PRINT " "; : GOTO 240 +250 PRINT +260 NEXT L +270 END + +300 W$ = "" +310 FOR I = I TO 1 STEP -1 +320 IF MID$(T$, I, 1) = " " THEN NEXT I : RETURN +330 FOR I = I TO 1 STEP -1 +340 C$ = MID$(T$, I, 1) +350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I +360 RETURN diff --git a/Task/Reverse-words-in-a-string/AutoHotkey/reverse-words-in-a-string.ahk b/Task/Reverse-words-in-a-string/AutoHotkey/reverse-words-in-a-string.ahk new file mode 100644 index 0000000000..bc4ad1033b --- /dev/null +++ b/Task/Reverse-words-in-a-string/AutoHotkey/reverse-words-in-a-string.ahk @@ -0,0 +1,21 @@ +Data := " +(Join`r`n +---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert ----------------------- +)" + +Loop, Parse, Data, `n, `r +{ + Loop, Parse, A_LoopField, % A_Space + Line := A_LoopField " " Line + Output .= Line "`n", Line := "" +} +MsgBox, % RTrim(Output, "`n") diff --git a/Task/Reverse-words-in-a-string/BBC-BASIC/reverse-words-in-a-string.bbc b/Task/Reverse-words-in-a-string/BBC-BASIC/reverse-words-in-a-string.bbc new file mode 100644 index 0000000000..ca49410d32 --- /dev/null +++ b/Task/Reverse-words-in-a-string/BBC-BASIC/reverse-words-in-a-string.bbc @@ -0,0 +1,16 @@ + PRINT FNreverse("---------- Ice and Fire ------------")\ + \ 'FNreverse("")\ + \ 'FNreverse("fire, in end will world the say Some")\ + \ 'FNreverse("ice. in say Some")\ + \ 'FNreverse("desire of tasted I've what From")\ + \ 'FNreverse("fire. favor who those with hold I")\ + \ 'FNreverse("")\ + \ 'FNreverse("... elided paragraph last ...")\ + \ 'FNreverse("")\ + \ 'FNreverse("Frost Robert -----------------------") + END + + DEF FNreverse(s$) + LOCAL sp% + sp%=INSTR(s$," ") + IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$ diff --git a/Task/Reverse-words-in-a-string/Bracmat/reverse-words-in-a-string.bracmat b/Task/Reverse-words-in-a-string/Bracmat/reverse-words-in-a-string.bracmat new file mode 100644 index 0000000000..aca410a6f9 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Bracmat/reverse-words-in-a-string.bracmat @@ -0,0 +1,37 @@ +("---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------" + : ?text +& ( reverse + = token tokens reversed + . :?tokens + & whl + ' ( @( !arg + : ?token (" "|\t|\r) ?arg + ) + & !tokens !token:?tokens + ) + & !tokens !arg:?tokens + & :?reversed + & whl + ' ( !tokens:%?token %?tokens + & " " !token !reversed:?reversed + ) + & !tokens !reversed:?reversed + & str$!reversed + ) +& :?output +& whl + ' ( @(!text:?line \n ?text) + & !output reverse$!line \n:?output + ) +& !output reverse$!text:?output +& out$str$!output +); diff --git a/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-1.cpp b/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-1.cpp new file mode 100644 index 0000000000..45920001c9 --- /dev/null +++ b/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-1.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include + +//code for a C++11 compliant compiler +template +void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) { + std::reverse(first, last); + auto block_last = first; + do { + using std::placeholders::_1; + auto block_first = std::find_if_not(block_last, last, + std::bind(std::equal_to(),_1, separator)); + block_last = std::find(block_first, last, separator); + std::reverse(block_first, block_last); + } while(block_last != last); +} + +//code for a C++03 compliant compiler +template +void block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) { + std::reverse(first, last); + BidirectionalIterator block_last = first; + do { + BidirectionalIterator block_first = std::find_if(block_last, last, + std::bind2nd(std::not_equal_to(), separator)); + block_last = std::find(block_first, last, separator); + std::reverse(block_first, block_last); + } while(block_last != last); +} + +int main() { + std::string str1[] = + { + "---------- Ice and Fire ------------", + "", + "fire, in end will world the say Some", + "ice. in say Some", + "desire of tasted I've what From", + "fire. favor who those with hold I", + "", + "... elided paragraph last ...", + "", + "Frost Robert -----------------------" + }; + + std::for_each(begin(str1), end(str1), [](std::string& s){ + block_reverse_cpp11(begin(s), end(s), ' '); + std::cout << s << std::endl; + }); + + std::for_each(begin(str1), end(str1), [](std::string& s){ + block_reverse_cpp03(begin(s), end(s), ' '); + std::cout << s << std::endl; + }); + + return 0; +} diff --git a/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-2.cpp b/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-2.cpp new file mode 100644 index 0000000000..8d3a631510 --- /dev/null +++ b/Task/Reverse-words-in-a-string/C++/reverse-words-in-a-string-2.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +string invertString( string s ) +{ + string st, tmp; + for( string::iterator it = s.begin(); it != s.end(); it++ ) + { + if( *it != 32 ) tmp += *it; + else + { + st = " " + tmp + st; + tmp.clear(); + } + } + return tmp + st; +} + +int main( int argc, char* argv[] ) +{ + string str[] = + { + "---------- Ice and Fire ------------", + "", + "fire, in end will world the say Some", + "ice. in say Some", + "desire of tasted I've what From", + "fire. favor who those with hold I", + "", + "... elided paragraph last ...", + "", + "Frost Robert -----------------------" + }; + for( int i = 0; i < 10; i++ ) + cout << invertString( str[i] ) << "\n"; + + cout << "\n"; + return system( "pause" ); +} diff --git a/Task/Reverse-words-in-a-string/C/reverse-words-in-a-string.c b/Task/Reverse-words-in-a-string/C/reverse-words-in-a-string.c new file mode 100644 index 0000000000..2057d69236 --- /dev/null +++ b/Task/Reverse-words-in-a-string/C/reverse-words-in-a-string.c @@ -0,0 +1,35 @@ +#include +#include + +void rev_print(char *s, int n) +{ + for (; *s && isspace(*s); s++); + if (*s) { + char *e; + for (e = s; *e && !isspace(*e); e++); + rev_print(e, 0); + printf("%.*s%s", (int)(e - s), s, " " + n); + } + if (n) putchar('\n'); +} + +int main(void) +{ + char *s[] = { + "---------- Ice and Fire ------------", + " ", + "fire, in end will world the say Some", + "ice. in say Some ", + "desire of tasted I've what From ", + "fire. favor who those with hold I ", + " ", + "... elided paragraph last ... ", + " ", + "Frost Robert -----------------------", + 0 + }; + int i; + for (i = 0; s[i]; i++) rev_print(s[i], 1); + + return 0; +} diff --git a/Task/Reverse-words-in-a-string/Clojure/reverse-words-in-a-string.clj b/Task/Reverse-words-in-a-string/Clojure/reverse-words-in-a-string.clj new file mode 100644 index 0000000000..441eb89ea2 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Clojure/reverse-words-in-a-string.clj @@ -0,0 +1,14 @@ +(def poem + "---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert -----------------------") + +(doall + (map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n")))) diff --git a/Task/Reverse-words-in-a-string/Common-Lisp/reverse-words-in-a-string.lisp b/Task/Reverse-words-in-a-string/Common-Lisp/reverse-words-in-a-string.lisp new file mode 100644 index 0000000000..b3bc83c84b --- /dev/null +++ b/Task/Reverse-words-in-a-string/Common-Lisp/reverse-words-in-a-string.lisp @@ -0,0 +1,29 @@ +(defun split-and-reverse (str) + (labels + ((iter (s lst) + (let ((s2 (string-trim '(#\space) s))) + (if s2 + (let ((word-end (position #\space s2))) + (if (and word-end (< (1+ word-end) (length s2))) + (iter (subseq s2 (1+ word-end)) + (cons (subseq s2 0 word-end) lst)) + (cons s2 lst))) + lst)))) + (iter str NIL))) + +(defparameter *poem* + "---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert -----------------------") + +(with-input-from-string (s *poem*) + (loop for line = (read-line s NIL) + while line + do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line)))) diff --git a/Task/Reverse-words-in-a-string/D/reverse-words-in-a-string.d b/Task/Reverse-words-in-a-string/D/reverse-words-in-a-string.d new file mode 100644 index 0000000000..040db02296 --- /dev/null +++ b/Task/Reverse-words-in-a-string/D/reverse-words-in-a-string.d @@ -0,0 +1,18 @@ +void main() { + import std.stdio, std.string, std.range, std.algorithm; + + immutable text = +"---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------"; + + writefln("%(%-(%s %)\n%)", + text.splitLines.map!(r => r.split.retro)); +} diff --git a/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-1.elixir b/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-1.elixir new file mode 100644 index 0000000000..2bb6b53f4d --- /dev/null +++ b/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-1.elixir @@ -0,0 +1,10 @@ +defmodule RC do + def reverse_words(txt) do + txt |> String.split("\n") # split lines + |> Enum.map(&( # in each line + &1 |> String.split # split words + |> Enum.reverse # reverse words + |> Enum.join(" "))) # rejoin words + |> Enum.join("\n") # rejoin lines + end +end diff --git a/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-2.elixir b/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-2.elixir new file mode 100644 index 0000000000..f1d7824738 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Elixir/reverse-words-in-a-string-2.elixir @@ -0,0 +1,13 @@ +txt = + "---------- Ice and Fire ------------\n" <> + " \n" <> + "fire, in end will world the say Some\n" <> + "ice. in say Some \n" <> + "desire of tasted I've what From \n" <> + "fire. favor who those with hold I \n" <> + " \n" <> + "... elided paragraph last ... \n" <> + " \n" <> + "Frost Robert -----------------------" + +IO.puts RC.reverse_words(txt) diff --git a/Task/Reverse-words-in-a-string/Go/reverse-words-in-a-string.go b/Task/Reverse-words-in-a-string/Go/reverse-words-in-a-string.go new file mode 100644 index 0000000000..396781c4ba --- /dev/null +++ b/Task/Reverse-words-in-a-string/Go/reverse-words-in-a-string.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "strings" +) + +// a number of strings +var n = []string{ + "---------- Ice and Fire ------------", + " ", + "fire, in end will world the say Some", + "ice. in say Some ", + "desire of tasted I've what From ", + "fire. favor who those with hold I ", + " ", + "... elided paragraph last ... ", + " ", + "Frost Robert -----------------------", +} + +func main() { + for i, s := range n { + t := strings.Fields(s) // tokenize + // reverse + last := len(t) - 1 + for j, k := range t[:len(t)/2] { + t[j], t[last-j] = t[last-j], k + } + n[i] = strings.Join(t, " ") + } + // display result + for _, t := range n { + fmt.Println(t) + } +} diff --git a/Task/Reverse-words-in-a-string/Groovy/reverse-words-in-a-string.groovy b/Task/Reverse-words-in-a-string/Groovy/reverse-words-in-a-string.groovy new file mode 100644 index 0000000000..f960d2f5c1 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Groovy/reverse-words-in-a-string.groovy @@ -0,0 +1,15 @@ +def text = new StringBuilder() + .append('---------- Ice and Fire ------------\n') + .append(' \n') + .append('fire, in end will world the say Some\n') + .append('ice. in say Some \n') + .append('desire of tasted I\'ve what From \n') + .append('fire. favor who those with hold I \n') + .append(' \n') + .append('... elided paragraph last ... \n') + .append(' \n') + .append('Frost Robert -----------------------\n').toString() + +text.eachLine { line -> + println "$line --> ${line.split(' ').reverse().join(' ')}" +} diff --git a/Task/Reverse-words-in-a-string/Haskell/reverse-words-in-a-string.hs b/Task/Reverse-words-in-a-string/Haskell/reverse-words-in-a-string.hs new file mode 100644 index 0000000000..95d62eb16e --- /dev/null +++ b/Task/Reverse-words-in-a-string/Haskell/reverse-words-in-a-string.hs @@ -0,0 +1,18 @@ +revstr :: String -> String +revstr = unwords . reverse . words -- point-free style +--equivalent: +--revstr s = unwords (reverse (words s)) + +revtext :: String -> String +revtext = unlines . map revstr . lines -- applies revstr to each line independently + +test = revtext "---------- Ice and Fire ------------\n\ + \\n\ + \fire, in end will world the say Some\n\ + \ice. in say Some\n\ + \desire of tasted I've what From\n\ + \fire. favor who those with hold I\n\ + \\n\ + \... elided paragraph last ...\n\ + \\n\ + \Frost Robert -----------------------\n" --multiline string notation requires \ at end and start of lines, and \n to be manually input diff --git a/Task/Reverse-words-in-a-string/Icon/reverse-words-in-a-string.icon b/Task/Reverse-words-in-a-string/Icon/reverse-words-in-a-string.icon new file mode 100644 index 0000000000..873e355af2 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Icon/reverse-words-in-a-string.icon @@ -0,0 +1,14 @@ +procedure main() + every write(rWords(&input)) +end + +procedure rWords(f) + every !f ? { + every (s := "") := genWords() || s + suspend s + } +end + +procedure genWords() + while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w +end diff --git a/Task/Reverse-words-in-a-string/J/reverse-words-in-a-string.j b/Task/Reverse-words-in-a-string/J/reverse-words-in-a-string.j new file mode 100644 index 0000000000..47418f89ce --- /dev/null +++ b/Task/Reverse-words-in-a-string/J/reverse-words-in-a-string.j @@ -0,0 +1,22 @@ + ([:;@|.[:<;.1 ' ',]);._2]0 :0 +---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert ----------------------- +) + ------------ Fire and Ice ---------- + + Some say the world will end in fire, + Some say in ice. + From what I've tasted of desire + I hold with those who favor fire. + + ... last paragraph elided ... + + ----------------------- Robert Frost diff --git a/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-1.java b/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-1.java new file mode 100644 index 0000000000..c55e196eb3 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-1.java @@ -0,0 +1,22 @@ +public class ReverseWords { + + static final String[] lines = { + " ----------- Ice and Fire ----------- ", + " ", + " fire, in end will world the say Some ", + " ice. in say Some ", + " desire of tasted I've what From ", + " fire. favor who those with hold I ", + " ", + " ... elided paragraph last ... ", + " Frost Robert ----------------------- "}; + + public static void main(String[] args) { + for (String line : lines) { + String[] words = line.split("\\s"); + for (int i = words.length - 1; i >= 0; i--) + System.out.printf("%s ", words[i]); + System.out.println(); + } + } +} diff --git a/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-2.java b/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-2.java new file mode 100644 index 0000000000..ee853d635a --- /dev/null +++ b/Task/Reverse-words-in-a-string/Java/reverse-words-in-a-string-2.java @@ -0,0 +1,39 @@ +package string; + +import static java.util.Arrays.stream; + +public interface ReverseWords { + public static final String[] LINES = { + " ----------- Ice and Fire ----------- ", + " ", + " fire, in end will world the say Some ", + " ice. in say Some ", + " desire of tasted I've what From ", + " fire. favor who those with hold I ", + " ", + " ... elided paragraph last ... ", + " Frost Robert ----------------------- " + }; + + public static String[] reverseWords(String[] lines) { + return stream(lines) + .parallel() + .map(l -> l.split("\\s")) + .map(ws -> stream(ws) + .parallel() + .map(w -> " " + w) + .reduce( + "", + (w1, w2) -> w2 + w1 + ) + ) + .toArray(String[]::new) + ; + } + + public static void main(String... arguments) { + stream(reverseWords(LINES)) + .forEach(System.out::println) + ; + } +} diff --git a/Task/Reverse-words-in-a-string/Julia/reverse-words-in-a-string.julia b/Task/Reverse-words-in-a-string/Julia/reverse-words-in-a-string.julia new file mode 100644 index 0000000000..eead9ff1cd --- /dev/null +++ b/Task/Reverse-words-in-a-string/Julia/reverse-words-in-a-string.julia @@ -0,0 +1 @@ +revstring (str) = join(reverse(split(str, " ")), " ") diff --git a/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua b/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua new file mode 100644 index 0000000000..e18b5368c8 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua @@ -0,0 +1,19 @@ +function table.reverse(a) + local res = {} + for i = #a, 1, -1 do + res[#res+1] = a[i] + end + return res +end + +function splittokens(s) + local res = {} + for w in s:gmatch("%S+") do + res[#res+1] = w + end + return res +end + +for line, nl in s:gmatch("([^\n]-)(\n)") do + print(table.concat(table.reverse(splittokens(line)), ' ')) +end diff --git a/Task/Reverse-words-in-a-string/MATLAB/reverse-words-in-a-string.m b/Task/Reverse-words-in-a-string/MATLAB/reverse-words-in-a-string.m new file mode 100644 index 0000000000..2cea7ae9aa --- /dev/null +++ b/Task/Reverse-words-in-a-string/MATLAB/reverse-words-in-a-string.m @@ -0,0 +1,25 @@ +function testReverseWords + testStr = {'---------- Ice and Fire ------------' ; ... + '' ; ... + 'fire, in end will world the say Some' ; ... + 'ice. in say Some' ; ... + 'desire of tasted I''ve what From' ; ... + 'fire. favor who those with hold I' ; ... + '' ; ... + '... elided paragraph last ...' ; ... + '' ; ... + 'Frost Robert -----------------------' }; + for k = 1:length(testStr) + fprintf('%s\n', reverseWords(testStr{k})) + end +end + +function strOut = reverseWords(strIn) + strOut = strtrim(strIn); + if ~isempty(strOut) + % Could use strsplit() instead of textscan() in R2013a or later + words = textscan(strOut, '%s'); + words = words{1}; + strOut = strtrim(sprintf('%s ', words{end:-1:1})); + end +end diff --git a/Task/Reverse-words-in-a-string/Mathematica/reverse-words-in-a-string.math b/Task/Reverse-words-in-a-string/Mathematica/reverse-words-in-a-string.math new file mode 100644 index 0000000000..af193f50b4 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Mathematica/reverse-words-in-a-string.math @@ -0,0 +1,16 @@ +poem = "---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert -----------------------"; +lines = StringSplit[poem, "\n"]; +wordArray = StringSplit[#] & @ lines ; +reversedWordArray = Reverse[#] & /@ wordArray ; +linesWithReversedWords = + StringJoin[Riffle[#, " "]] & /@ reversedWordArray; +finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords diff --git a/Task/Reverse-words-in-a-string/OCaml/reverse-words-in-a-string.ocaml b/Task/Reverse-words-in-a-string/OCaml/reverse-words-in-a-string.ocaml new file mode 100644 index 0000000000..dd7175a6fa --- /dev/null +++ b/Task/Reverse-words-in-a-string/OCaml/reverse-words-in-a-string.ocaml @@ -0,0 +1,16 @@ +#load "str.cma" +let input = ["---------- Ice and Fire ------------"; + ""; + "fire, in end will world the say Some"; + "ice. in say Some"; + "desire of tasted I've what From"; + "fire. favor who those with hold I"; + ""; + "... elided paragraph last ..."; + ""; + "Frost Robert -----------------------"];; + +let splitted = List.map (Str.split (Str.regexp " ")) input in +let reversed = List.map List.rev splitted in +let final = List.map (String.concat " ") reversed in +List.iter print_endline final;; diff --git a/Task/Reverse-words-in-a-string/Objeck/reverse-words-in-a-string.objeck b/Task/Reverse-words-in-a-string/Objeck/reverse-words-in-a-string.objeck new file mode 100644 index 0000000000..e6ed418d30 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Objeck/reverse-words-in-a-string.objeck @@ -0,0 +1,29 @@ +use Collection; + +class Reverselines { + function : Main(args : String[]) ~ Nil { + lines := List->New(); + lines->AddBack("---------- Ice and Fire ------------"); + lines->AddBack(""); + lines->AddBack("fire, in end will world the say Some"); + lines->AddBack("ice. in say Some"); + lines->AddBack("desire of tasted I've what From"); + lines->AddBack("fire. favor who those with hold I"); + lines->AddBack(""); + lines->AddBack("... elided paragraph last ..."); + lines->AddBack(""); + lines->AddBack("Frost Robert -----------------------"); + + lines->Rewind(); + each(i : lines) { + words := lines->Get()->As(String)->Split(" "); + if(words <> Nil) { + for(j := words->Size() - 1; j > -1; j-=1;) { + IO.Console->Print(words[j])->Print(" "); + }; + }; + IO.Console->PrintLine(); + lines->Next(); + }; + } +} diff --git a/Task/Reverse-words-in-a-string/PL-I/reverse-words-in-a-string.pli b/Task/Reverse-words-in-a-string/PL-I/reverse-words-in-a-string.pli new file mode 100644 index 0000000000..1c077532a5 --- /dev/null +++ b/Task/Reverse-words-in-a-string/PL-I/reverse-words-in-a-string.pli @@ -0,0 +1,24 @@ +rev: procedure options (main); /* 5 May 2014 */ + declare (s, reverse) character (50) varying; + declare (i, j) fixed binary; + declare in file; + + open file (in) title ('/REV-WRD.DAT,type(text),recsize(50)'); + + do j = 1 to 10; + get file (in) edit (s) (L); + put skip list (trim(s)); + + reverse = ''; + + do while (length(s) > 0); + s = trim(s); + i = index(s, ' '); + if i = 0 then + if s ^= '' then i = length(s)+1; + if i > 0 then reverse = substr(s, 1, i-1) || ' ' || reverse; + if length(s) = i then s = ''; else s = substr(s, i); + end; + put edit ('---> ', reverse) (col(40), 2 A); + end; +end rev; diff --git a/Task/Reverse-words-in-a-string/Perl-6/reverse-words-in-a-string.pl6 b/Task/Reverse-words-in-a-string/Perl-6/reverse-words-in-a-string.pl6 new file mode 100644 index 0000000000..6111d45ed4 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Perl-6/reverse-words-in-a-string.pl6 @@ -0,0 +1 @@ +say .words.reverse for lines diff --git a/Task/Reverse-words-in-a-string/Perl/reverse-words-in-a-string.pl b/Task/Reverse-words-in-a-string/Perl/reverse-words-in-a-string.pl new file mode 100644 index 0000000000..9d1f0c449f --- /dev/null +++ b/Task/Reverse-words-in-a-string/Perl/reverse-words-in-a-string.pl @@ -0,0 +1,12 @@ +print join(" ", reverse split), "\n" for ; +__DATA__ +---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert ----------------------- diff --git a/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-1.py b/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-1.py new file mode 100644 index 0000000000..f2bc6d959f --- /dev/null +++ b/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-1.py @@ -0,0 +1,13 @@ + text = '''\ +---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------''' + +for line in text.split('\n'): print(' '.join(line.split()[::-1])) diff --git a/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-2.py b/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-2.py new file mode 100644 index 0000000000..de243a8823 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Python/reverse-words-in-a-string-2.py @@ -0,0 +1,10 @@ +------------ Fire and Ice ---------- + +Some say the world will end in fire, +Some say in ice. +From what I've tasted of desire +I hold with those who favor fire. + +... last paragraph elided ... + +----------------------- Robert Frost diff --git a/Task/Reverse-words-in-a-string/README b/Task/Reverse-words-in-a-string/README new file mode 100644 index 0000000000..a9da3e9d02 --- /dev/null +++ b/Task/Reverse-words-in-a-string/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Reverse_words_in_a_string diff --git a/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string.rexx b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string.rexx new file mode 100644 index 0000000000..cbc564aba3 --- /dev/null +++ b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string.rexx @@ -0,0 +1,19 @@ +/*REXX pgm reverses the order of tokens in a string, but not the letters*/ +@. = +@.1 = "---------- Ice and Fire ------------" +@.2 = ' ' +@.3 = "fire, in end will world the say Some" +@.4 = "ice. in say Some" +@.5 = "desire of tasted I've what From" +@.6 = "fire. favor who those with hold I" +@.7 = ' ' +@.8 = "... elided paragraph last ..." +@.9 = ' ' +@.10 = "Frost Robert -----------------------" + + do j=1 while @.j\==''; $= /*process each "line"; nullify $.*/ + do k=1 for words(@.j) /*process each word in the string*/ + $=word(@.j,k) $ /*prepend the word to a new line.*/ + end /*k*/ /* [↑] could do this another way*/ + say $ /*display newly constructed line.*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Reverse-words-in-a-string/Racket/reverse-words-in-a-string.rkt b/Task/Reverse-words-in-a-string/Racket/reverse-words-in-a-string.rkt new file mode 100644 index 0000000000..91f01400ec --- /dev/null +++ b/Task/Reverse-words-in-a-string/Racket/reverse-words-in-a-string.rkt @@ -0,0 +1,27 @@ +#lang racket/base + +(require racket/string) + +(define (split-reverse str) + (string-join + (reverse + (string-split str)))) + +(define poem + "---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------") + + +(let ([poem-port (open-input-string poem)]) + (let loop ([l (read-line poem-port)]) + (unless (eof-object? l) + (begin (displayln (split-reverse l)) + (loop (read-line poem-port)))))) diff --git a/Task/Reverse-words-in-a-string/Ruby/reverse-words-in-a-string.rb b/Task/Reverse-words-in-a-string/Ruby/reverse-words-in-a-string.rb new file mode 100644 index 0000000000..2d5d763712 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Ruby/reverse-words-in-a-string.rb @@ -0,0 +1,18 @@ +def reverse_words(string) + string.each_line.map {|line| line.split.reverse.join(" ")} +end + +str = <<'EOS' +---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert ----------------------- +EOS + +puts reverse_words(str) diff --git a/Task/Reverse-words-in-a-string/Scala/reverse-words-in-a-string.scala b/Task/Reverse-words-in-a-string/Scala/reverse-words-in-a-string.scala new file mode 100644 index 0000000000..dde4c14f46 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Scala/reverse-words-in-a-string.scala @@ -0,0 +1,17 @@ +object ReverseWords extends App { + + """| ---------- Ice and Fire ------------ + | + | fire, in end will world the say Some + | ice. in say Some + | desire of tasted I've what From + | fire. favor who those with hold I + | + | ... elided paragraph last ... + | + | Frost Robert ----------------------- """ + .stripMargin.lines.toList.map{_.split(" ")}.map{_.reverse} + .map(_.mkString(" ")) + .foreach{println} + +} diff --git a/Task/Reverse-words-in-a-string/Scheme/reverse-words-in-a-string.ss b/Task/Reverse-words-in-a-string/Scheme/reverse-words-in-a-string.ss new file mode 100644 index 0000000000..22eb8caa18 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Scheme/reverse-words-in-a-string.ss @@ -0,0 +1,14 @@ +(for-each + (lambda (s) (print (string-join (reverse (string-split s #/ +/))))) + (string-split + "---------- Ice and Fire ------------ + + fire, in end will world the say Some + ice. in say Some + desire of tasted I've what From + fire. favor who those with hold I + + ... elided paragraph last ... + + Frost Robert -----------------------" + #/[ \r]*\n[ \r]*/)) diff --git a/Task/Reverse-words-in-a-string/Seed7/reverse-words-in-a-string.seed7 b/Task/Reverse-words-in-a-string/Seed7/reverse-words-in-a-string.seed7 new file mode 100644 index 0000000000..6bbfd7206d --- /dev/null +++ b/Task/Reverse-words-in-a-string/Seed7/reverse-words-in-a-string.seed7 @@ -0,0 +1,28 @@ +$ include "seed7_05.s7i"; + +const array string: lines is [] ( + "---------- Ice and Fire ------------", + "", + "fire, in end will world the say Some", + "ice. in say Some", + "desire of tasted I've what From", + "fire. favor who those with hold I", + "", + "... elided paragraph last ...", + "", + "Frost Robert -----------------------"); + +const proc: main is func + local + var string: line is ""; + var array string: words is 0 times ""; + var integer: index is 0; + begin + for line range lines do + words := split(line, ' '); + for index range length(words) downto 1 do + write(words[index] <& " "); + end for; + writeln; + end for; + end func; diff --git a/Task/Reverse-words-in-a-string/Smalltalk/reverse-words-in-a-string.st b/Task/Reverse-words-in-a-string/Smalltalk/reverse-words-in-a-string.st new file mode 100644 index 0000000000..2373d744f6 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Smalltalk/reverse-words-in-a-string.st @@ -0,0 +1,12 @@ +poem := '---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I''ve what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------'. + +(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr). diff --git a/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-1.tcl b/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-1.tcl new file mode 100644 index 0000000000..fa213767e9 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-1.tcl @@ -0,0 +1,17 @@ +set lines { + "---------- Ice and Fire ------------" + "" + "fire, in end will world the say Some" + "ice. in say Some" + "desire of tasted I've what From" + "fire. favor who those with hold I" + "" + "... elided paragraph last ..." + "" + "Frost Robert -----------------------" +} +foreach line $lines { + puts [join [lreverse [regexp -all -inline {\S+} $line]]] + # This would also work for data this simple: + ### puts [lreverse $line] +} diff --git a/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-2.tcl b/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-2.tcl new file mode 100644 index 0000000000..e3266d75c6 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Tcl/reverse-words-in-a-string-2.tcl @@ -0,0 +1 @@ +puts [join [lmap line $lines {lreverse $line}] "\n"] diff --git a/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-1.sh b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-1.sh new file mode 100644 index 0000000000..ca3c709e08 --- /dev/null +++ b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-1.sh @@ -0,0 +1,17 @@ +while read -a words; do + for ((i=${#words[@]}-1; i>=0; i--)); do + printf "%s " "${words[i]}" + done + echo +done << END +---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert ----------------------- +END diff --git a/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-2.sh b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-2.sh new file mode 100644 index 0000000000..d7f742777f --- /dev/null +++ b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-2.sh @@ -0,0 +1 @@ +read -a diff --git a/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-3.sh b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-3.sh new file mode 100644 index 0000000000..f487e1b7ef --- /dev/null +++ b/Task/Reverse-words-in-a-string/UNIX-Shell/reverse-words-in-a-string-3.sh @@ -0,0 +1 @@ +read -A diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk b/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk new file mode 100644 index 0000000000..1757b12e05 --- /dev/null +++ b/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk @@ -0,0 +1 @@ +Pseudocode diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c b/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c new file mode 100644 index 0000000000..e84c223938 --- /dev/null +++ b/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c @@ -0,0 +1 @@ +printf("Hello world!\n"); diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl b/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl new file mode 100644 index 0000000000..053662f327 --- /dev/null +++ b/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl @@ -0,0 +1 @@ +print "Hello world!\n" diff --git a/Task/Runge-Kutta-method/00DESCRIPTION b/Task/Runge-Kutta-method/00DESCRIPTION new file mode 100644 index 0000000000..54f2f3273d --- /dev/null +++ b/Task/Runge-Kutta-method/00DESCRIPTION @@ -0,0 +1,19 @@ +Given the example Differential equation: +:y'(t) = t \times \sqrt {y(t)} +With initial condition: +:t_0 = 0 and y_0 = y(t_0) = y(0) = 1 +This equation has an exact solution: +:y(t) = \tfrac{1}{16}(t^2 +4)^2 +;Task +Demonstrate the commonly used explicit [[wp:Runge–Kutta_methods#Common_fourth-order_Runge.E2.80.93Kutta_method|fourth-order Runge–Kutta method]] to solve the above differential equation. +* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given) +* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution. +;Method summary +Starting with a given y_n and t_n calculate: +:\delta y_1 = \delta t\times y'(t_n, y_n)\quad +:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) +:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) +:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad +then: +:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4) +:t_{n+1} = t_n + \delta t\quad diff --git a/Task/Runge-Kutta-method/00META.yaml b/Task/Runge-Kutta-method/00META.yaml new file mode 100644 index 0000000000..94b4ccfa51 --- /dev/null +++ b/Task/Runge-Kutta-method/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Runge-Kutta method diff --git a/Task/Runge-Kutta-method/AWK/runge-kutta-method.awk b/Task/Runge-Kutta-method/AWK/runge-kutta-method.awk new file mode 100644 index 0000000000..a2ec5f3889 --- /dev/null +++ b/Task/Runge-Kutta-method/AWK/runge-kutta-method.awk @@ -0,0 +1,19 @@ +# syntax: GAWK -f RUNGE-KUTTA_METHOD.AWK +# converted from BBC BASIC +BEGIN { + print(" t y error") + y = 1 + for (i=0; i<=100; i++) { + t = i / 10 + if (t == int(t)) { + actual = ((t^2+4)^2) / 16 + printf("%2d %12.7f %g\n",t,y,actual-y) + } + k1 = t * sqrt(y) + k2 = (t + 0.05) * sqrt(y + 0.05 * k1) + k3 = (t + 0.05) * sqrt(y + 0.05 * k2) + k4 = (t + 0.10) * sqrt(y + 0.10 * k3) + y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6 + } + exit(0) +} diff --git a/Task/Runge-Kutta-method/Ada/runge-kutta-method.ada b/Task/Runge-Kutta-method/Ada/runge-kutta-method.ada new file mode 100644 index 0000000000..2b46c53f62 --- /dev/null +++ b/Task/Runge-Kutta-method/Ada/runge-kutta-method.ada @@ -0,0 +1,52 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Generic_Elementary_Functions; +procedure RungeKutta is + type Floaty is digits 15; + type Floaty_Array is array (Natural range <>) of Floaty; + package FIO is new Ada.Text_IO.Float_IO(Floaty); use FIO; + type Derivative is access function(t, y : Floaty) return Floaty; + package Math is new Ada.Numerics.Generic_Elementary_Functions (Floaty); + function calc_err (t, calc : Floaty) return Floaty; + + procedure Runge (yp_func : Derivative; t, y : in out Floaty_Array; + dt : Floaty) is + dy1, dy2, dy3, dy4 : Floaty; + begin + for n in t'First .. t'Last-1 loop + dy1 := dt * yp_func(t(n), y(n)); + dy2 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy1 / 2.0); + dy3 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy2 / 2.0); + dy4 := dt * yp_func(t(n) + dt, y(n) + dy3); + t(n+1) := t(n) + dt; + y(n+1) := y(n) + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; + end loop; + end Runge; + + procedure Print (t, y : Floaty_Array; modnum : Positive) is begin + for i in t'Range loop + if i mod modnum = 0 then + Put("y("); Put (t(i), Exp=>0, Fore=>0, Aft=>1); + Put(") = "); Put (y(i), Exp=>0, Fore=>0, Aft=>8); + Put(" Error:"); Put (calc_err(t(i),y(i)), Aft=>5); + New_Line; + end if; + end loop; + end Print; + + function yprime (t, y : Floaty) return Floaty is begin + return t * Math.Sqrt (y); + end yprime; + function calc_err (t, calc : Floaty) return Floaty is + actual : constant Floaty := (t**2 + 4.0)**2 / 16.0; + begin return abs(actual-calc); + end calc_err; + + dt : constant Floaty := 0.10; + N : constant Positive := 100; + t_arr, y_arr : Floaty_Array(0 .. N); +begin + t_arr(0) := 0.0; + y_arr(0) := 1.0; + Runge (yprime'Access, t_arr, y_arr, dt); + Print (t_arr, y_arr, 10); +end RungeKutta; diff --git a/Task/Runge-Kutta-method/BASIC/runge-kutta-method.basic b/Task/Runge-Kutta-method/BASIC/runge-kutta-method.basic new file mode 100644 index 0000000000..74074b92d5 --- /dev/null +++ b/Task/Runge-Kutta-method/BASIC/runge-kutta-method.basic @@ -0,0 +1,15 @@ + y = 1.0 + FOR i% = 0 TO 100 + t = i% / 10 + + IF t = INT(t) THEN + actual = ((t^2 + 4)^2) / 16 + PRINT "y("; t ") = "; y TAB(20) "Error = "; actual - y + ENDIF + + k1 = t * SQR(y) + k2 = (t + 0.05) * SQR(y + 0.05 * k1) + k3 = (t + 0.05) * SQR(y + 0.05 * k2) + k4 = (t + 0.10) * SQR(y + 0.10 * k3) + y += 0.1 * (k1 + 2 * (k2 + k3) + k4) / 6 + NEXT i% diff --git a/Task/Runge-Kutta-method/C/runge-kutta-method.c b/Task/Runge-Kutta-method/C/runge-kutta-method.c new file mode 100644 index 0000000000..0961d3a74e --- /dev/null +++ b/Task/Runge-Kutta-method/C/runge-kutta-method.c @@ -0,0 +1,37 @@ +#include +#include +#include + +double rk4(double(*f)(double, double), double dx, double x, double y) +{ + double k1 = dx * f(x, y), + k2 = dx * f(x + dx / 2, y + k1 / 2), + k3 = dx * f(x + dx / 2, y + k2 / 2), + k4 = dx * f(x + dx, y + k3); + return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6; +} + +double rate(double x, double y) +{ + return x * sqrt(y); +} + +int main(void) +{ + double *y, x, y2; + double x0 = 0, x1 = 10, dx = .1; + int i, n = 1 + (x1 - x0)/dx; + y = malloc(sizeof(double) * n); + + for (y[0] = 1, i = 1; i < n; i++) + y[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]); + + printf("x\ty\trel. err.\n------------\n"); + for (i = 0; i < n; i += 10) { + x = x0 + dx * i; + y2 = pow(x * x / 4 + 1, 2); + printf("%g\t%g\t%g\n", x, y[i], y[i]/y2 - 1); + } + + return 0; +} diff --git a/Task/Runge-Kutta-method/D/runge-kutta-method.d b/Task/Runge-Kutta-method/D/runge-kutta-method.d new file mode 100644 index 0000000000..e79181f571 --- /dev/null +++ b/Task/Runge-Kutta-method/D/runge-kutta-method.d @@ -0,0 +1,38 @@ +import std.stdio, std.math, std.typecons; + +alias FP = real; +alias FPs = Typedef!(FP[101]); + +void runge(in FP function(in FP, in FP) + pure nothrow @safe @nogc yp_func, + ref FPs t, ref FPs y, in FP dt) pure nothrow @safe @nogc { + foreach (immutable n; 0 .. t.length - 1) { + immutable FP + dy1 = dt * yp_func(t[n], y[n]), + dy2 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy1 / 2.0), + dy3 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy2 / 2.0), + dy4 = dt * yp_func(t[n] + dt, y[n] + dy3); + t[n + 1] = t[n] + dt; + y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; + } +} + +FP calc_err(in FP t, in FP calc) pure nothrow @safe @nogc { + immutable FP actual = (t ^^ 2 + 4.0) ^^ 2 / 16.0; + return abs(actual - calc); +} + +void main() { + enum FP dt = 0.10; + FPs t_arr, y_arr; + + t_arr[0] = 0.0; + y_arr[0] = 1.0; + runge((t, y) => t * y.sqrt, t_arr, y_arr, dt); + + foreach (immutable i; 0 .. t_arr.length) + if (i % 10 == 0) + writefln("y(%.1f) = %.8f Error: %.6g", + t_arr[i], y_arr[i], + calc_err(t_arr[i], y_arr[i])); +} diff --git a/Task/Runge-Kutta-method/Dart/runge-kutta-method.dart b/Task/Runge-Kutta-method/Dart/runge-kutta-method.dart new file mode 100644 index 0000000000..6bf169b4f9 --- /dev/null +++ b/Task/Runge-Kutta-method/Dart/runge-kutta-method.dart @@ -0,0 +1,27 @@ +import 'dart:math' as Math; + +num RungeKutta4(Function f, num t, num y, num dt){ + num k1 = dt * f(t,y); + num k2 = dt * f(t+0.5*dt, y + 0.5*k1); + num k3 = dt * f(t+0.5*dt, y + 0.5*k2); + num k4 = dt * f(t + dt, y + k3); + return y + (1/6) * (k1 + 2*k2 + 2*k3 + k4); +} + +void main(){ + num t = 0; + num dt = 0.1; + num tf = 10; + num totalPoints = ((tf-t)/dt).floor()+1; + num y = 1; + Function f = (num t, num y) => t * Math.sqrt(y); + Function actual = (num t) => (1/16) * (t*t+4)*(t*t+4); + for (num i = 0; i <= totalPoints; i++){ + num relativeError = (actual(t) - y)/actual(t); + if (i%10 == 0){ + print('y(${t.round().toStringAsPrecision(3)}) = ${y.toStringAsPrecision(11)} Error = ${relativeError.toStringAsPrecision(11)}'); + } + y = RungeKutta4(f, t, y, dt); + t += dt; + } +} diff --git a/Task/Runge-Kutta-method/F-Sharp/runge-kutta-method.fs b/Task/Runge-Kutta-method/F-Sharp/runge-kutta-method.fs new file mode 100644 index 0000000000..87d9873002 --- /dev/null +++ b/Task/Runge-Kutta-method/F-Sharp/runge-kutta-method.fs @@ -0,0 +1,21 @@ +open System + +let y'(t,y) = t * sqrt(y) + +let RungeKutta4 t0 y0 t_max dt = + + let dy1(t,y) = dt * y'(t,y) + let dy2(t,y) = dt * y'(t+dt/2.0, y+dy1(t,y)/2.0) + let dy3(t,y) = dt * y'(t+dt/2.0, y+dy2(t,y)/2.0) + let dy4(t,y) = dt * y'(t+dt, y+dy3(t,y)) + + (t0,y0) |> Seq.unfold (fun (t,y) -> + if ( t <= t_max) then Some((t,y), (Math.Round(t+dt, 6), y + ( dy1(t,y) + 2.0*dy2(t,y) + 2.0*dy3(t,y) + dy4(t,y))/6.0)) + else None + ) + +let y_exact t = (pown (pown t 2 + 4.0) 2)/16.0 + +RungeKutta4 0.0 1.0 10.0 0.1 + |> Seq.filter (fun (t,y) -> t % 1.0 = 0.0 ) + |> Seq.iter (fun (t,y) -> Console.WriteLine("y({0})={1}\t(relative error:{2})", t, y, (y / y_exact(t))-1.0) ) diff --git a/Task/Runge-Kutta-method/Fortran/runge-kutta-method.f b/Task/Runge-Kutta-method/Fortran/runge-kutta-method.f new file mode 100644 index 0000000000..b8fcbea1f9 --- /dev/null +++ b/Task/Runge-Kutta-method/Fortran/runge-kutta-method.f @@ -0,0 +1,29 @@ +program rungekutta +implicit none +real(kind=kind(1.0D0)) :: t,dt,tstart,tstop +real(kind=kind(1.0D0)) :: y,k1,k2,k3,k4 +tstart =0.0D0 ; tstop =10.0D0 ; dt = 0.1D0 +y = 1.0D0 +t = tstart +write(6,'(A,f4.1,A,f12.8,A,es13.6)') 'y(',t,') = ',y,' Error = '& + &,abs(y-(t**2+4.0d0)**2/16.0d0) +do; if ( t .ge. tstop ) exit + k1 = f (t , y ) + k2 = f (t+0.5D0 * dt, y +0.5D0 * dt * k1) + k3 = f (t+0.5D0 * dt, y +0.5D0 * dt * k2) + k4 = f (t+ dt, y + dt * k3) + y = y + dt *( k1 + 2.0D0 *( k2 + k3 ) + k4 )/6.0D0 + t = t + dt + if(abs(real(nint(t))-t) .le. 1.0D-12) then + write(6,'(A,f4.1,A,f12.8,A,es13.6)') 'y(',t,') = ',y,' Error = '& + &,abs(y-(t**2+4.0d0)**2/16.0d0) + end if +end do +contains + function f (t,y) + implicit none + real(kind=kind(1.0D0)),intent(in) :: y,t + real(kind=kind(1.0D0)) :: f + f = t*sqrt(y) + end function f +end program rungekutta diff --git a/Task/Runge-Kutta-method/Go/runge-kutta-method.go b/Task/Runge-Kutta-method/Go/runge-kutta-method.go new file mode 100644 index 0000000000..03e0e10766 --- /dev/null +++ b/Task/Runge-Kutta-method/Go/runge-kutta-method.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "math" +) + +type ypFunc func(t, y float64) float64 +type ypStepFunc func(t, y, dt float64) float64 + +// newRKStep takes a function representing a differential equation +// and returns a function that performs a single step of the forth-order +// Runge-Kutta method. +func newRK4Step(yp ypFunc) ypStepFunc { + return func(t, y, dt float64) float64 { + dy1 := dt * yp(t, y) + dy2 := dt * yp(t+dt/2, y+dy1/2) + dy3 := dt * yp(t+dt/2, y+dy2/2) + dy4 := dt * yp(t+dt, y+dy3) + return y + (dy1+2*(dy2+dy3)+dy4)/6 + } +} + +// example differential equation +func yprime(t, y float64) float64 { + return t * math.Sqrt(y) +} + +// exact solution of example +func actual(t float64) float64 { + t = t*t + 4 + return t * t / 16 +} + +func main() { + t0, tFinal := 0, 10 // task specifies times as integers, + dtPrint := 1 // and to print at whole numbers. + y0 := 1. // initial y. + dtStep := .1 // step value. + + t, y := float64(t0), y0 + ypStep := newRK4Step(yprime) + for t1 := t0 + dtPrint; t1 <= tFinal; t1 += dtPrint { + printErr(t, y) // print intermediate result + for steps := int(float64(dtPrint)/dtStep + .5); steps > 1; steps-- { + y = ypStep(t, y, dtStep) + t += dtStep + } + y = ypStep(t, y, float64(t1)-t) // adjust step to integer time + t = float64(t1) + } + printErr(t, y) // print final result +} + +func printErr(t, y float64) { + fmt.Printf("y(%.1f) = %f Error: %e\n", t, y, math.Abs(actual(t)-y)) +} diff --git a/Task/Runge-Kutta-method/Haskell/runge-kutta-method-1.hs b/Task/Runge-Kutta-method/Haskell/runge-kutta-method-1.hs new file mode 100644 index 0000000000..1452154e41 --- /dev/null +++ b/Task/Runge-Kutta-method/Haskell/runge-kutta-method-1.hs @@ -0,0 +1,17 @@ +import Data.List + +dv :: Floating a => a -> a -> a +dv = (. sqrt). (*) + +fy t = 1/16 * (4+t^2)^2 + +rk4 :: (Enum a, Fractional a)=> (a -> a -> a) -> a -> a -> a -> [(a,a)] +rk4 fd y0 a h = zip ts $ scanl (flip fc) y0 ts where + ts = [a,h ..] + fc t y = sum. (y:). zipWith (*) [1/6,1/3,1/3,1/6] + $ scanl (\k f -> h * fd (t+f*h) (y+f*k)) (h * fd t y) [1/2,1/2,1] + +task = mapM_ print + $ map (\(x,y)-> (truncate x,y,fy x - y)) + $ filter (\(x,_) -> 0== mod (truncate $ 10*x) 10) + $ take 101 $ rk4 dv 1.0 0 0.1 diff --git a/Task/Runge-Kutta-method/Haskell/runge-kutta-method-2.hs b/Task/Runge-Kutta-method/Haskell/runge-kutta-method-2.hs new file mode 100644 index 0000000000..8e8967d5cd --- /dev/null +++ b/Task/Runge-Kutta-method/Haskell/runge-kutta-method-2.hs @@ -0,0 +1,12 @@ +*Main> task +(0,1.0,0.0) +(1,1.5624998542781088,1.4572189122041834e-7) +(2,3.9999990805208006,9.194792029987298e-7) +(3,10.562497090437557,2.909562461184123e-6) +(4,24.999993765090654,6.234909399438493e-6) +(5,52.56248918030265,1.0819697635611192e-5) +(6,99.99998340540378,1.6594596999652822e-5) +(7,175.56247648227165,2.3517730085131916e-5) +(8,288.99996843479926,3.1565204153594095e-5) +(9,451.562459276841,4.0723166534917254e-5) +(10,675.9999490167125,5.098330132113915e-5) diff --git a/Task/Runge-Kutta-method/J/runge-kutta-method-1.j b/Task/Runge-Kutta-method/J/runge-kutta-method-1.j new file mode 100644 index 0000000000..86ea9351cd --- /dev/null +++ b/Task/Runge-Kutta-method/J/runge-kutta-method-1.j @@ -0,0 +1,18 @@ +NB.*rk4 a Solve function using Runge-Kutta method +NB. y is: y(ta) , ta , tb , tstep +NB. u is: function to solve +NB. eg: fyp rk4 1 0 10 0.1 +rk4=: adverb define + 'Y0 a b h'=. 4{. y + T=. a + i.@>:&.(%&h) b - a + Y=. Yt=. Y0 + for_t. }: T do. + ty=. t,Yt + k1=. h * u ty + k2=. h * u ty + -: h,k1 + k3=. h * u ty + -: h,k2 + k4=. h * u ty + h,k3 + Y=. Y, Yt=. Yt + (%6) * 1 2 2 1 +/@:* k1, k2, k3, k4 + end. +T ,. Y +) diff --git a/Task/Runge-Kutta-method/J/runge-kutta-method-2.j b/Task/Runge-Kutta-method/J/runge-kutta-method-2.j new file mode 100644 index 0000000000..c5a545faaf --- /dev/null +++ b/Task/Runge-Kutta-method/J/runge-kutta-method-2.j @@ -0,0 +1,17 @@ + fy=: (%16) * [: *: 4 + *: NB. f(t,y) + fyp=: (* %:)/ NB. f'(t,y) + report_whole=: (10 * i. >:10)&{ NB. report at whole-numbered t values + report_err=: (, {: - [: fy {.)"1 NB. report errors + + report_err report_whole fyp rk4 1 0 10 0.1 + 0 1 0 + 1 1.5625 _1.45722e_7 + 2 4 _9.19479e_7 + 3 10.5625 _2.90956e_6 + 4 25 _6.23491e_6 + 5 52.5625 _1.08197e_5 + 6 100 _1.65946e_5 + 7 175.562 _2.35177e_5 + 8 289 _3.15652e_5 + 9 451.562 _4.07232e_5 +10 676 _5.09833e_5 diff --git a/Task/Runge-Kutta-method/J/runge-kutta-method-3.j b/Task/Runge-Kutta-method/J/runge-kutta-method-3.j new file mode 100644 index 0000000000..e6a9943f09 --- /dev/null +++ b/Task/Runge-Kutta-method/J/runge-kutta-method-3.j @@ -0,0 +1,17 @@ +rk4=: adverb define + 'Y0 a b h'=. 4{. y + T=. a + i.@>:&.(%&h) b-a + (,. [: h&(u nextY)@,/\. Y0 ,~ }.)&.|. T +) + +NB. nextY a Calculate Yn+1 of a function using Runge-Kutta method +NB. y is: 2-item numeric list of time t and y(t) +NB. u is: function to use +NB. x is: step size +NB. eg: 0.001 fyp nextY 0 1 +nextY=: adverb define +: + tableau=. 1 0.5 0.5, x * u y + ks=. (x * [: u y + (* x&,))/\. tableau + ({:y) + 6 %~ +/ 1 2 2 1 * ks +) diff --git a/Task/Runge-Kutta-method/JavaScript/runge-kutta-method.js b/Task/Runge-Kutta-method/JavaScript/runge-kutta-method.js new file mode 100644 index 0000000000..da63d15546 --- /dev/null +++ b/Task/Runge-Kutta-method/JavaScript/runge-kutta-method.js @@ -0,0 +1,36 @@ +function rk4(y, x, dx, f) { + var k1 = dx * f(x, y), + k2 = dx * f(x + dx / 2.0, +y + k1 / 2.0), + k3 = dx * f(x + dx / 2.0, +y + k2 / 2.0), + k4 = dx * f(x + dx, +y + k3); + + return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0; +} + +function f(x, y) { + return x * Math.sqrt(y); +} + +function actual(x) { + return (1/16) * (x*x+4)*(x*x+4); +} + +var y = 1.0, + x = 0.0, + step = 0.1, + steps = 0, + maxSteps = 101, + sampleEveryN = 10; + +while (steps < maxSteps) { + if (steps%sampleEveryN === 0) { + console.log("y(" + x + ") = \t" + y + "\t ± " + (actual(x) - y).toExponential()); + } + + y = rk4(y, x, step, f); + + // using integer math for the step addition + // to prevent floating point errors as 0.2 + 0.1 != 0.3 + x = ((x * 10) + (step * 10)) / 10; + steps += 1; +} diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia new file mode 100644 index 0000000000..026d7a4efd --- /dev/null +++ b/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia @@ -0,0 +1,33 @@ +function rk4(f) + return (t,y,dt)-> + ( (dy1 )-> + ( (dy2 )-> + ( (dy3 )-> + ( (dy4 )->( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 + )( dt * f( t +dt , y + dy3 ) ) + )( dt * f( t +dt/2, y + dy2/2 ) ) + )( dt * f( t +dt/2, y + dy1/2 ) ) + )( dt * f( t , y ) ) +end + +theory(t) = (t^2 + 4.0)^2 / 16.0 + +tmax = 10.0 +ttol = 1.e-5 + +t0 = 0.0 +y0 = 1.0 +dt = 0.1 + +dy = rk4( (t,y) -> t*sqrt(y) ) + +t = t0 +y = y0 + +while t <= tmax + if abs(round(t) - t) < ttol + @printf( STDOUT,"y(%4.1f)\t= %12.6f \t error: %12.6e\n",t,y,abs(y-theory(t)) ) + end + y = y + dy(t,y,dt) + t = t + dt +end diff --git a/Task/Runge-Kutta-method/MATLAB/runge-kutta-method.m b/Task/Runge-Kutta-method/MATLAB/runge-kutta-method.m new file mode 100644 index 0000000000..7502bfa711 --- /dev/null +++ b/Task/Runge-Kutta-method/MATLAB/runge-kutta-method.m @@ -0,0 +1,37 @@ +function testRK4Programs + figure + hold on + t = 0:0.1:10; + y = 0.0625.*(t.^2+4).^2; + plot(t, y, '-k') + [tode4, yode4] = testODE4(t); + plot(tode4, yode4, '--b') + [trk4, yrk4] = testRK4(t); + plot(trk4, yrk4, ':r') + legend('Exact', 'ODE4', 'RK4') + hold off + fprintf('Time\tExactVal\tODE4Val\tODE4Error\tRK4Val\tRK4Error\n') + for k = 1:10:length(t) + fprintf('%.f\t\t%7.3f\t\t%7.3f\t%7.3g\t%7.3f\t%7.3g\n', t(k), y(k), ... + yode4(k), abs(y(k)-yode4(k)), yrk4(k), abs(y(k)-yrk4(k))) + end +end + +function [t, y] = testODE4(t) + y0 = 1; + y = ode4(@(tVal,yVal)tVal*sqrt(yVal), t, y0); +end + +function [t, y] = testRK4(t) + dydt = @(tVal,yVal)tVal*sqrt(yVal); + y = zeros(size(t)); + y(1) = 1; + for k = 1:length(t)-1 + dt = t(k+1)-t(k); + dy1 = dt*dydt(t(k), y(k)); + dy2 = dt*dydt(t(k)+0.5*dt, y(k)+0.5*dy1); + dy3 = dt*dydt(t(k)+0.5*dt, y(k)+0.5*dy2); + dy4 = dt*dydt(t(k)+dt, y(k)+dy3); + y(k+1) = y(k)+(dy1+2*dy2+2*dy3+dy4)/6; + end +end diff --git a/Task/Runge-Kutta-method/Mathematica/runge-kutta-method.math b/Task/Runge-Kutta-method/Mathematica/runge-kutta-method.math new file mode 100644 index 0000000000..a00a6d55d2 --- /dev/null +++ b/Task/Runge-Kutta-method/Mathematica/runge-kutta-method.math @@ -0,0 +1,20 @@ +(* Symbolic solution *) +DSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, t] +Table[{t, 1/16 (4 + t^2)^2}, {t, 0, 10}] + +(* Numerical solution I (not RK4) *) +Table[{t, y[t], Abs[y[t] - 1/16*(4 + t^2)^2]}, {t, 0, 10}] /. + First@NDSolve[{y'[t] == t*Sqrt[y[t]], y[0] == 1}, y, {t, 0, 10}] + +(* Numerical solution II (RK4) *) +f[{t_, y_}] := {1, t Sqrt[y]} +h = 0.1; +phi[y_] := Module[{k1, k2, k3, k4}, + k1 = h*f[y]; + k2 = h*f[y + 1/2 k1]; + k3 = h*f[y + 1/2 k2]; + k4 = h*f[y + k3]; + y + k1/6 + k2/3 + k3/3 + k4/6] +solution = NestList[phi, {0, 1}, 101]; +Table[{y[[1]], y[[2]], Abs[y[[2]] - 1/16 (y[[1]]^2 + 4)^2]}, + {y, solution[[1 ;; 101 ;; 10]]}] diff --git a/Task/Runge-Kutta-method/Maxima/runge-kutta-method.maxima b/Task/Runge-Kutta-method/Maxima/runge-kutta-method.maxima new file mode 100644 index 0000000000..83a312ae90 --- /dev/null +++ b/Task/Runge-Kutta-method/Maxima/runge-kutta-method.maxima @@ -0,0 +1,40 @@ +/* Here is how to solve a differential equation */ +'diff(y, x) = x * sqrt(y); +ode2(%, y, x); +ic1(%, x = 0, y = 1); +factor(solve(%, y)); /* [y = (x^2 + 4)^2 / 16] */ + +/* The Runge-Kutta solver is builtin */ + +load(dynamics)$ +sol: rk(t * sqrt(y), y, 1, [t, 0, 10, 1.0])$ +plot2d([discrete, sol])$ + +/* An implementation of RK4 for one equation */ + +rk4(f, x0, y0, x1, n) := block([h, x, y, vx, vy, k1, k2, k3, k4], + h: bfloat((x1 - x0) / (n - 1)), + x: x0, + y: y0, + vx: makelist(0, n + 1), + vy: makelist(0, n + 1), + vx[1]: x0, + vy[1]: y0, + for i from 1 thru n do ( + k1: bfloat(h * f(x, y)), + k2: bfloat(h * f(x + h / 2, y + k1 / 2)), + k3: bfloat(h * f(x + h / 2, y + k2 / 2)), + k4: bfloat(h * f(x + h, y + k3)), + vy[i + 1]: y: y + (k1 + 2 * k2 + 2 * k3 + k4) / 6, + vx[i + 1]: x: x + h + ), + [vx, vy] +)$ + +[x, y]: rk4(lambda([x, y], x * sqrt(y)), 0, 1, 10, 101)$ + +plot2d([discrete, x, y])$ + +s: map(lambda([x], (x^2 + 4)^2 / 16), x)$ + +for i from 1 step 10 thru 101 do print(x[i], " ", y[i], " ", y[i] - s[i]); diff --git a/Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml b/Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml new file mode 100644 index 0000000000..061c2f69ff --- /dev/null +++ b/Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml @@ -0,0 +1,16 @@ +let y' t y = t *. sqrt y +let exact t = let u = 0.25*.t*.t +. 1.0 in u*.u + +let rk4_step (y,t) h = + let k1 = h *. y' t y in + let k2 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k1) in + let k3 = h *. y' (t +. 0.5*.h) (y +. 0.5*.k2) in + let k4 = h *. y' (t +. h) (y +. k3) in + (y +. (k1+.k4)/.6.0 +. (k2+.k3)/.3.0, t +. h) + +let rec loop h n (y,t) = + if n mod 10 = 1 then + Printf.printf "t = %f,\ty = %f,\terr = %g\n" t y (abs_float (y -. exact t)); + if n < 102 then loop h (n+1) (rk4_step (y,t) h) + +let _ = loop 0.1 1 (1.0, 0.0) diff --git a/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave b/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave new file mode 100644 index 0000000000..f0a34fd1f8 --- /dev/null +++ b/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave @@ -0,0 +1,8 @@ +function ydot = f(y, t) + ydot = t * sqrt( y ); +endfunction + +t = [0:10]'; +y = lsode("f", 1, t); + +[ t, y, y - 1/16 * (t.**2 + 4).**2 ] diff --git a/Task/Runge-Kutta-method/PARI-GP/runge-kutta-method.pari b/Task/Runge-Kutta-method/PARI-GP/runge-kutta-method.pari new file mode 100644 index 0000000000..fa93fb0cbc --- /dev/null +++ b/Task/Runge-Kutta-method/PARI-GP/runge-kutta-method.pari @@ -0,0 +1,16 @@ +rk4(f,dx,x,y)={ + my(k1=dx*f(x,y), k2=dx*f(x+dx/2,y+k1/2), k3=dx*f(x+dx/2,y+k2/2), k4=dx*f(x+dx,y+k3)); + y + (k1 + 2*k2 + 2*k3 + k4) / 6 +}; +rate(x,y)=x*sqrt(y); +go()={ + my(x0=0,x1=10,dx=.1,n=1+(x1-x0)\dx,y=vector(n)); + y[1]=1; + for(i=2,n,y[i]=rk4(rate, dx, x0 + dx * (i - 1), y[i-1])); + print("x\ty\trel. err.\n------------"); + forstep(i=1,n,10, + my(x=x0+dx*i,y2=(x^2/4+1)^2); + print(x "\t" y[i] "\t" y[i]/y2 - 1) + ) +}; +go() diff --git a/Task/Runge-Kutta-method/PL-I/runge-kutta-method.pli b/Task/Runge-Kutta-method/PL-I/runge-kutta-method.pli new file mode 100644 index 0000000000..eda7f2c7b8 --- /dev/null +++ b/Task/Runge-Kutta-method/PL-I/runge-kutta-method.pli @@ -0,0 +1,25 @@ +Runge_Kutta: procedure options (main); /* 10 March 2014 */ + declare (y, dy1, dy2, dy3, dy4) float (18); + declare t fixed decimal (10,1); + declare dt float (18) static initial (0.1); + + y = 1; + do t = 0 to 10 by 0.1; + dy1 = dt * ydash(t, y); + dy2 = dt * ydash(t + dt/2, y + dy1/2); + dy3 = dt * ydash(t + dt/2, y + dy2/2); + dy4 = dt * ydash(t + dt, y + dy3); + + if mod(t, 1.0) = 0 then + put skip edit('y(', trim(t), ')=', y, ', error = ', abs(y - (t**2 + 4)**2 / 16 )) + (3 a, column(9), f(16,10), a, f(13,10)); + y = y + (dy1 + 2*dy2 + 2*dy3 + dy4)/6; + end; + + +ydash: procedure (t, y) returns (float(18)); + declare (t, y) float (18) nonassignable; + return ( t*sqrt(y) ); +end ydash; + +end Runge_kutta; diff --git a/Task/Runge-Kutta-method/Pascal/runge-kutta-method.pascal b/Task/Runge-Kutta-method/Pascal/runge-kutta-method.pascal new file mode 100644 index 0000000000..154a6ac9fe --- /dev/null +++ b/Task/Runge-Kutta-method/Pascal/runge-kutta-method.pascal @@ -0,0 +1,71 @@ +program RungeKuttaExample; + +uses sysutils; + +type + TDerivative = function (t, y : Real) : Real; + +procedure RungeKutta(yDer : TDerivative; + var t, y : array of Real; + dt : Real); +var + dy1, dy2, dy3, dy4 : Real; + idx : Cardinal; + +begin + for idx := Low(t) to High(t) - 1 do + begin + dy1 := dt * yDer(t[idx], y[idx]); + dy2 := dt * yDer(t[idx] + dt / 2.0, y[idx] + dy1 / 2.0); + dy3 := dt * yDer(t[idx] + dt / 2.0, y[idx] + dy2 / 2.0); + dy4 := dt * yDer(t[idx] + dt, y[idx] + dy3); + + t[idx + 1] := t[idx] + dt; + y[idx + 1] := y[idx] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; + end; +end; + +function CalcError(t, y : Real) : Real; +var + trueVal : Real; + +begin + trueVal := sqr(sqr(t) + 4.0) / 16.0; + CalcError := abs(trueVal - y); +end; + +procedure Print(t, y : array of Real; + modnum : Integer); +var + idx : Cardinal; + +begin + for idx := Low(t) to High(t) do + begin + if idx mod modnum = 0 then + begin + WriteLn(Format('y(%4.1f) = %12.8f Error: %12.6e', + [t[idx], y[idx], CalcError(t[idx], y[idx])])); + end; + end; +end; + +function YPrime(t, y : Real) : Real; +begin + YPrime := t * sqrt(y); +end; + +const + dt = 0.10; + N = 100; + +var + tArr, yArr : array [0..N] of Real; + +begin + tArr[0] := 0.0; + yArr[0] := 1.0; + + RungeKutta(@YPrime, tArr, yArr, dt); + Print(tArr, yArr, 10); +end. diff --git a/Task/Runge-Kutta-method/Perl-6/runge-kutta-method.pl6 b/Task/Runge-Kutta-method/Perl-6/runge-kutta-method.pl6 new file mode 100644 index 0000000000..179c90eab8 --- /dev/null +++ b/Task/Runge-Kutta-method/Perl-6/runge-kutta-method.pl6 @@ -0,0 +1,21 @@ +sub runge-kutta(&yp) { + return -> \t, \y, \δt { + my $a = δt * yp( t, y ); + my $b = δt * yp( t + δt/2, y + $a/2 ); + my $c = δt * yp( t + δt/2, y + $b/2 ); + my $d = δt * yp( t + δt, y + $c ); + ($a + 2*($b + $c) + $d) / 6; + } +} + +constant δt = .1; +my &δy = runge-kutta { $^t * sqrt($^y) }; + +loop ( + my ($t, $y) = (0, 1); + $t <= 10; + ($t, $y) = ($t + δt, $y + δy($t, $y, δt)) +) { + printf "y(%2d) = %12f ± %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16) + if $t.narrow ~~ Int; +} diff --git a/Task/Runge-Kutta-method/Perl/runge-kutta-method.pl b/Task/Runge-Kutta-method/Perl/runge-kutta-method.pl new file mode 100644 index 0000000000..38242f0927 --- /dev/null +++ b/Task/Runge-Kutta-method/Perl/runge-kutta-method.pl @@ -0,0 +1,22 @@ +sub runge_kutta { + my ($yp, $dt) = @_; + sub { + my ($t, $y) = @_; + my @dy = $dt * $yp->( $t , $y ); + push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[0]/2 ); + push @dy, $dt * $yp->( $t + $dt/2, $y + $dy[1]/2 ); + push @dy, $dt * $yp->( $t + $dt , $y + $dy[2] ); + return $t + $dt, $y + ($dy[0] + 2*$dy[1] + 2*$dy[2] + $dy[3]) / 6; + } +} + +my $RK = runge_kutta sub { $_[0] * sqrt $_[1] }, .1; + +for( + my ($t, $y) = (0, 1); + sprintf("%.0f", $t) <= 10; + ($t, $y) = $RK->($t, $y) +) { + printf "y(%2.0f) = %12f ± %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16) + if sprintf("%.4f", $t) =~ /0000$/; +} diff --git a/Task/Runge-Kutta-method/Python/runge-kutta-method.py b/Task/Runge-Kutta-method/Python/runge-kutta-method.py new file mode 100644 index 0000000000..901334c397 --- /dev/null +++ b/Task/Runge-Kutta-method/Python/runge-kutta-method.py @@ -0,0 +1,21 @@ +def RK4(f): + return lambda t, y, dt: ( + lambda dy1: ( + lambda dy2: ( + lambda dy3: ( + lambda dy4: (dy1 + 2*dy2 + 2*dy3 + dy4)/6 + )( dt * f( t + dt , y + dy3 ) ) + )( dt * f( t + dt/2, y + dy2/2 ) ) + )( dt * f( t + dt/2, y + dy1/2 ) ) + )( dt * f( t , y ) ) + +def theory(t): return (t**2 + 4)**2 /16 + +from math import sqrt +dy = RK4(lambda t, y: t*sqrt(y)) + +t, y, dt = 0., 1., .1 +while t <= 10: + if abs(round(t) - t) < 1e-5: + print("y(%2.1f)\t= %4.6f \t error: %4.6g" % ( t, y, abs(y - theory(t)))) + t, y = t + dt, y + dy( t, y, dt ) diff --git a/Task/Runge-Kutta-method/README b/Task/Runge-Kutta-method/README new file mode 100644 index 0000000000..408d958ee4 --- /dev/null +++ b/Task/Runge-Kutta-method/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Runge-Kutta_method diff --git a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx new file mode 100644 index 0000000000..aa63e8aa3a --- /dev/null +++ b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx @@ -0,0 +1,35 @@ +/*REXX program uses the Runge-Kutta method to solve the differential */ +/* ____ */ +/*equation: y'(t)=t²√y(t) which has the exact solution: y(t)=(t²+4)²/16*/ + +numeric digits 40; d=digits()%2 /*use forty digits, show ½ that. */ +x0=0; x1=10; dx=.1; n=1 + (x1-x0) / dx; y.=1 + + do m=1 for n-1; mm=m-1 + y.m=Runge_Kutta(dx, x0+dx*mm, y.mm) + end /*m*/ + +say center(x,13,'─') center(y,d,'─') ' ' center('relative error',d,'─') + + do i=0 to n-1 by 10; x=(x0+dx*i)/1; y2=(x*x/4+1)**2 + relE=format(y.i/y2-1,,13)/1; if relE=0 then relE=' 0' + say center(x,13) right(format(y.i,,12),d) ' ' left(relE,d) + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────RATE subroutine─────────────────────*/ +rate: return arg(1)*sqrt(arg(2)) +/*──────────────────────────────────Runge_Kutta subroutine──────────────*/ +Runge_Kutta: procedure; parse arg dx,x,y + k1 = dx * rate(x , y ) + k2 = dx * rate(x+dx/2 , y+k1/2 ) + k3 = dx * rate(x+dx/2 , y+k2/2 ) + k4 = dx * rate(x+dx , y+k3 ) +return y + (k1 + 2*k2 + 2*k3 + k4) / 6 +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits() + numeric digits 11; g=.sqrtG() + do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1 + if m.k>11 then numeric digits m.k + g=.5*(g+x/g); end; numeric digits d; return g/1 +.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 diff --git a/Task/Runge-Kutta-method/Racket/runge-kutta-method-1.rkt b/Task/Runge-Kutta-method/Racket/runge-kutta-method-1.rkt new file mode 100644 index 0000000000..be91889998 --- /dev/null +++ b/Task/Runge-Kutta-method/Racket/runge-kutta-method-1.rkt @@ -0,0 +1,8 @@ +(define (RK4 F δt) + (λ (t y) + (define δy1 (* δt (F t y))) + (define δy2 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy1))))) + (define δy3 (* δt (F (+ t (* 1/2 δt)) (+ y (* 1/2 δy2))))) + (define δy4 (* δt (F (+ t δt) (+ y δy1)))) + (list (+ t δt) + (+ y (* 1/6 (+ δy1 (* 2 δy2) (* 2 δy3) δy4)))))) diff --git a/Task/Runge-Kutta-method/Racket/runge-kutta-method-2.rkt b/Task/Runge-Kutta-method/Racket/runge-kutta-method-2.rkt new file mode 100644 index 0000000000..15f626d8b5 --- /dev/null +++ b/Task/Runge-Kutta-method/Racket/runge-kutta-method-2.rkt @@ -0,0 +1,5 @@ +(define ((step-subdivision n method) F h) + (λ (x . y) (last (ODE-solve F (cons x y) + #:x-max (+ x h) + #:step (/ h n) + #:method method)))) diff --git a/Task/Runge-Kutta-method/Racket/runge-kutta-method-3.rkt b/Task/Runge-Kutta-method/Racket/runge-kutta-method-3.rkt new file mode 100644 index 0000000000..e4046c8820 --- /dev/null +++ b/Task/Runge-Kutta-method/Racket/runge-kutta-method-3.rkt @@ -0,0 +1,10 @@ +(define (F t y) (* t (sqrt y))) + +(define (exact-solution t) (* 1/16 (sqr (+ 4 (sqr t))))) + +(define numeric-solution + (ODE-solve F '(0 1) #:x-max 10 #:step 1 #:method (step-subdivision 10 RK4))) + +(for ([s numeric-solution]) + (match-define (list t y) s) + (printf "t=~a\ty=~a\terror=~a\n" t y (- y (exact-solution t)))) diff --git a/Task/Runge-Kutta-method/Racket/runge-kutta-method-4.rkt b/Task/Runge-Kutta-method/Racket/runge-kutta-method-4.rkt new file mode 100644 index 0000000000..eabf7e6b33 --- /dev/null +++ b/Task/Runge-Kutta-method/Racket/runge-kutta-method-4.rkt @@ -0,0 +1,4 @@ +> (require plot) +> (plot (list (function exact-solution 0 10 #:label "Exact solution") + (points numeric-solution #:label "Runge-Kutta method")) + #:x-label "t" #:y-label "y(t)") diff --git a/Task/Runge-Kutta-method/Ruby/runge-kutta-method.rb b/Task/Runge-Kutta-method/Ruby/runge-kutta-method.rb new file mode 100644 index 0000000000..8c42326161 --- /dev/null +++ b/Task/Runge-Kutta-method/Ruby/runge-kutta-method.rb @@ -0,0 +1,27 @@ +def calc_rk4(f) + return ->(t,y,dt){ + ->(dy1 ){ + ->(dy2 ){ + ->(dy3 ){ + ->(dy4 ){ ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 }.call( + dt * f.call( t + dt , y + dy3 ))}.call( + dt * f.call( t + dt/2, y + dy2/2 ))}.call( + dt * f.call( t + dt/2, y + dy1/2 ))}.call( + dt * f.call( t , y ))} +end + +TIME_MAXIMUM, WHOLE_TOLERANCE = 10.0, 1.0e-5 +T_START, Y_START, DT = 0.0, 1.0, 0.10 + +def my_diff_eqn(t,y) ; t * Math.sqrt(y) ; end +def my_solution(t ) ; (t**2 + 4)**2 / 16 ; end +def find_error(t,y) ; (y - my_solution(t)).abs ; end +def is_whole?(t ) ; (t.round - t).abs < WHOLE_TOLERANCE ; end + +dy = calc_rk4( ->(t,y){my_diff_eqn(t,y)} ) + +t, y = T_START, Y_START +while t <= TIME_MAXIMUM + printf("y(%4.1f)\t= %12.6f \t error: %12.6e\n",t,y,find_error(t,y)) if is_whole?(t) + t, y = t + DT, y + dy.call(t,y,DT) +end diff --git a/Task/Runge-Kutta-method/Run-BASIC/runge-kutta-method.run b/Task/Runge-Kutta-method/Run-BASIC/runge-kutta-method.run new file mode 100644 index 0000000000..af78d3244f --- /dev/null +++ b/Task/Runge-Kutta-method/Run-BASIC/runge-kutta-method.run @@ -0,0 +1,12 @@ +y = 1 +while t <= 10 + k1 = t * sqr(y) + k2 = (t + .05) * sqr(y + .05 * k1) + k3 = (t + .05) * sqr(y + .05 * k2) + k4 = (t + .1) * sqr(y + .1 * k3) + +if right$(using("##.#",t),1) = "0" then print "y(";using("##",t);") ="; using("####.#######", y);chr$(9);"Error ="; (((t^2 + 4)^2) /16) -y + y = y + .1 *(k1 + 2 * (k2 + k3) + k4) / 6 + t = t + .1 +wend +end diff --git a/Task/Runge-Kutta-method/Standard-ML/runge-kutta-method.ml b/Task/Runge-Kutta-method/Standard-ML/runge-kutta-method.ml new file mode 100644 index 0000000000..c5cf2129cd --- /dev/null +++ b/Task/Runge-Kutta-method/Standard-ML/runge-kutta-method.ml @@ -0,0 +1,41 @@ +fun step y' (tn,yn) dt = + let + val dy1 = dt * y'(tn,yn) + val dy2 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy1) + val dy3 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy2) + val dy4 = dt * y'(tn + dt, yn + dy3) + in + (tn + dt, yn + (1.0 / 6.0) * (dy1 + 2.0*dy2 + 2.0*dy3 + dy4)) + end + +(* Suggested test case *) +fun testy' (t,y) = + t * Math.sqrt y + +fun testy t = + (1.0 / 16.0) * Math.pow(Math.pow(t,2.0) + 4.0, 2.0) + +(* Test-runner that iterates the step function and prints the results. *) +fun test t0 y0 dt steps print_freq y y' = + let + fun loop i (tn,yn) = + if i = steps then () + else + let + val (t1,y1) = step y' (tn,yn) dt + val y1' = y tn + val () = if i mod print_freq = 0 then + (print ("Time: " ^ Real.toString tn ^ "\n"); + print ("Exact: " ^ Real.toString y1' ^ "\n"); + print ("Approx: " ^ Real.toString yn ^ "\n"); + print ("Error: " ^ Real.toString (y1' - yn) ^ "\n\n")) + else () + in + loop (i+1) (t1,y1) + end + in + loop 0 (t0,y0) + end + +(* Run the suggested test case *) +val () = test 0.0 1.0 0.1 101 10 testy testy' diff --git a/Task/Runge-Kutta-method/Tcl/runge-kutta-method.tcl b/Task/Runge-Kutta-method/Tcl/runge-kutta-method.tcl new file mode 100644 index 0000000000..24d5b8666d --- /dev/null +++ b/Task/Runge-Kutta-method/Tcl/runge-kutta-method.tcl @@ -0,0 +1,33 @@ +package require Tcl 8.5 + +# Hack to bring argument function into expression +proc tcl::mathfunc::dy {t y} {upvar 1 dyFn dyFn; $dyFn $t $y} + +proc rk4step {dyFn y* t* dt} { + upvar 1 ${y*} y ${t*} t + set dy1 [expr {$dt * dy($t, $y)}] + set dy2 [expr {$dt * dy($t+$dt/2, $y+$dy1/2)}] + set dy3 [expr {$dt * dy($t+$dt/2, $y+$dy2/2)}] + set dy4 [expr {$dt * dy($t+$dt, $y+$dy3)}] + set y [expr {$y + ($dy1 + 2*$dy2 + 2*$dy3 + $dy4)/6.0}] + set t [expr {$t + $dt}] +} + +proc y {t} {expr {($t**2 + 4)**2 / 16}} +proc δy {t y} {expr {$t * sqrt($y)}} + +proc printvals {t y} { + set err [expr {abs($y - [y $t])}] + puts [format "y(%.1f) = %.8f\tError: %.8e" $t $y $err] +} + +set t 0.0 +set y 1.0 +set dt 0.1 +printvals $t $y +for {set i 1} {$i <= 101} {incr i} { + rk4step δy y t $dt + if {$i%10 == 0} { + printvals $t $y + } +} diff --git a/Task/Semiprime/00DESCRIPTION b/Task/Semiprime/00DESCRIPTION new file mode 100644 index 0000000000..d4d41a6253 --- /dev/null +++ b/Task/Semiprime/00DESCRIPTION @@ -0,0 +1,3 @@ + Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [[prime_number|prime numbers]]. Example: 1679 = 23 × 73 (This particular number was chosen as the length of the [http://en.wikipedia.org/wiki/Arecibo_message Arecibo message]). + +Write a function determining whether a given number is semiprime. diff --git a/Task/Semiprime/00META.yaml b/Task/Semiprime/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Semiprime/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Semiprime/Ada/semiprime.ada b/Task/Semiprime/Ada/semiprime.ada new file mode 100644 index 0000000000..60cd1a3cca --- /dev/null +++ b/Task/Semiprime/Ada/semiprime.ada @@ -0,0 +1,21 @@ +with Prime_Numbers, Ada.Text_IO; + +procedure Test_Semiprime is + + package Integer_Numbers is new + Prime_Numbers (Natural, 0, 1, 2); + use Integer_Numbers; + +begin + for N in 1 .. 100 loop + if Decompose(N)'Length = 2 then -- N is a semiprime; + Ada.Text_IO.Put(Integer'Image(Integer(N))); + end if; + end loop; + Ada.Text_IO.New_Line; + for N in 1675 .. 1680 loop + if Decompose(N)'Length = 2 then -- N is a semiprime; + Ada.Text_IO.Put(Integer'Image(Integer(N))); + end if; + end loop; +end Test_Semiprime; diff --git a/Task/Semiprime/AutoHotkey/semiprime.ahk b/Task/Semiprime/AutoHotkey/semiprime.ahk new file mode 100644 index 0000000000..dce3c9d762 --- /dev/null +++ b/Task/Semiprime/AutoHotkey/semiprime.ahk @@ -0,0 +1,55 @@ +SetBatchLines -1 +k := 1 +loop, 100 +{ + m := semiprime(k) + StringSplit, m_m, m, - + if ( m_m1 = "yes" ) + list .= k . " " + k++ +} +MsgBox % list +list := +;=================================================================================================================================== +k := 1675 +loop, 5 +{ + m := semiprime(k) + StringSplit, m_m, m, - + if ( m_m1 = "yes" ) + list1 .= semiprime(k) . "`n" + else + list1 .= semiprime(k) . "`n" + k++ +} +MsgBox % list1 +list1 := +;=================================================================================================================================== +; The function========================================================================================================================== +semiprime(k) +{ + start := floor(sqrt(k)) + loop, % floor(sqrt(k)) - 1 + { + if ( mod(k, start) = 0 ) + new .= floor(start) . "*" . floor(k//start) . "," + start-- + } + + StringSplit, index, new, `, + + if ( index0 = 2 ) + { + StringTrimRight, new, new, 1 + StringSplit, 2_ind, new, * + if (mod(2_ind2, 2_ind1) = 0) && ( 2_ind1 != 2_ind2 ) + new := "N0- " . k . " - " . new + else + new := "yes- " . k . " - " . new + } + else + new := "N0- " . k . " - " . new +return new +} +;================================================================================================================================================= +esc::Exitapp diff --git a/Task/Semiprime/C++/semiprime.cpp b/Task/Semiprime/C++/semiprime.cpp new file mode 100644 index 0000000000..11a8f55ddb --- /dev/null +++ b/Task/Semiprime/C++/semiprime.cpp @@ -0,0 +1,21 @@ +#include + +bool isSemiPrime( int c ) +{ + int a = 2, b = 0; + while( b < 3 && c != 1 ) + { + if( !( c % a ) ) + { c /= a; b++; } + else a++; + } + return b == 2; +} +int main( int argc, char* argv[] ) +{ + for( int x = 2; x < 100; x++ ) + if( isSemiPrime( x ) ) + std::cout << x << " "; + + return 0; +} diff --git a/Task/Semiprime/C/semiprime.c b/Task/Semiprime/C/semiprime.c new file mode 100644 index 0000000000..98bfa435e8 --- /dev/null +++ b/Task/Semiprime/C/semiprime.c @@ -0,0 +1,21 @@ +#include + +int semiprime(int n) +{ + int p, f = 0; + for (p = 2; f < 2 && p*p <= n; p++) + while (0 == n % p) + n /= p, f++; + + return f + (n > 1) == 2; +} + +int main(void) +{ + int i; + for (i = 2; i < 100; i++) + if (semiprime(i)) printf(" %d", i); + putchar('\n'); + + return 0; +} diff --git a/Task/Semiprime/Common-Lisp/semiprime.lisp b/Task/Semiprime/Common-Lisp/semiprime.lisp new file mode 100644 index 0000000000..d7388217fd --- /dev/null +++ b/Task/Semiprime/Common-Lisp/semiprime.lisp @@ -0,0 +1,9 @@ +(defun semiprimep (n &optional (a 2)) + (cond ((> a (isqrt n)) nil) + ((zerop (rem n a)) (and (primep a) (primep (/ n a)))) + (t (semiprimep n (+ a 1))))) + +(defun primep (n &optional (a 2)) + (cond ((> a (isqrt n)) t) + ((zerop (rem n a)) nil) + (t (primep n (+ a 1))))) diff --git a/Task/Semiprime/D/semiprime.d b/Task/Semiprime/D/semiprime.d new file mode 100644 index 0000000000..5d365c8bec --- /dev/null +++ b/Task/Semiprime/D/semiprime.d @@ -0,0 +1,19 @@ +bool semiprime(long n) pure nothrow @safe @nogc { + auto nf = 0; + foreach (immutable i; 2 .. n + 1) { + while (n % i == 0) { + if (nf == 2) + return false; + nf++; + n /= i; + } + } + return nf == 2; +} + +void main() { + import std.stdio; + + foreach (immutable n; 1675 .. 1681) + writeln(n, " -> ", n.semiprime); +} diff --git a/Task/Semiprime/Forth/semiprime.fth b/Task/Semiprime/Forth/semiprime.fth new file mode 100644 index 0000000000..984d4c8a89 --- /dev/null +++ b/Task/Semiprime/Forth/semiprime.fth @@ -0,0 +1,8 @@ +: semiprime? + 0 swap dup 2 do + begin dup i mod 0= while i / swap 1+ swap repeat + over 1 > over i dup * < or if leave then + loop 1 > abs + 2 = +; + +: test 100 2 do i semiprime? if i . then loop cr ; diff --git a/Task/Semiprime/Go/semiprime.go b/Task/Semiprime/Go/semiprime.go new file mode 100644 index 0000000000..dd90bdba11 --- /dev/null +++ b/Task/Semiprime/Go/semiprime.go @@ -0,0 +1,23 @@ +package main + +import "fmt" + +func semiprime(n int) bool { + nf := 0 + for i := 2; i <= n; i++ { + for n%i == 0 { + if nf == 2 { + return false + } + nf++ + n /= i + } + } + return nf == 2 +} + +func main() { + for v := 1675; v <= 1680; v++ { + fmt.Println(v, "->", semiprime(v)) + } +} diff --git a/Task/Semiprime/Haskell/semiprime-1.hs b/Task/Semiprime/Haskell/semiprime-1.hs new file mode 100644 index 0000000000..eb7e4c3597 --- /dev/null +++ b/Task/Semiprime/Haskell/semiprime-1.hs @@ -0,0 +1,4 @@ +isSemiprime :: Int -> Bool +isSemiprime n = (length factors) == 2 && (product factors) == n || + (length factors) == 1 && (head factors) ^ 2 == n + where factors = primeFactors n diff --git a/Task/Semiprime/Haskell/semiprime-2.hs b/Task/Semiprime/Haskell/semiprime-2.hs new file mode 100644 index 0000000000..15fa2a3a24 --- /dev/null +++ b/Task/Semiprime/Haskell/semiprime-2.hs @@ -0,0 +1,4 @@ +isSemiprime :: Int -> Bool +isSemiprime n = case (primeFactors n) of + [f1, f2] -> f1 * f2 == n + otherwise -> False diff --git a/Task/Semiprime/Icon/semiprime.icon b/Task/Semiprime/Icon/semiprime.icon new file mode 100644 index 0000000000..3d22badd96 --- /dev/null +++ b/Task/Semiprime/Icon/semiprime.icon @@ -0,0 +1,9 @@ +link "factors" + +procedure main(A) + every nf := semiprime(n := !A) do write(n," = ",nf[1]," * ",nf[2]) +end + +procedure semiprime(n) # Succeeds and produces the factors only if n is semiprime. + return (2 = *(nf := factors(n)), nf) +end diff --git a/Task/Semiprime/J/semiprime-1.j b/Task/Semiprime/J/semiprime-1.j new file mode 100644 index 0000000000..551f9e1892 --- /dev/null +++ b/Task/Semiprime/J/semiprime-1.j @@ -0,0 +1 @@ +isSemiPrime=: 2 = #@q: ::0:"0 diff --git a/Task/Semiprime/J/semiprime-2.j b/Task/Semiprime/J/semiprime-2.j new file mode 100644 index 0000000000..e89eb92ac2 --- /dev/null +++ b/Task/Semiprime/J/semiprime-2.j @@ -0,0 +1,2 @@ + I. isSemiPrime i.100 +4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95 diff --git a/Task/Semiprime/Java/semiprime.java b/Task/Semiprime/Java/semiprime.java new file mode 100644 index 0000000000..790c67cb27 --- /dev/null +++ b/Task/Semiprime/Java/semiprime.java @@ -0,0 +1,57 @@ +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +public class SemiPrime{ + private static final BigInteger TWO = BigInteger.valueOf(2); + + public static List primeDecomp(BigInteger a){ + // impossible for values lower than 2 + if(a.compareTo(TWO) < 0){ + return null; + } + + //quickly handle even values + List result = new ArrayList(); + while(a.and(BigInteger.ONE).equals(BigInteger.ZERO)){ + a = a.shiftRight(1); + result.add(TWO); + } + + //left with odd values + if(!a.equals(BigInteger.ONE)){ + BigInteger b = BigInteger.valueOf(3); + while(b.compareTo(a) < 0){ + if(b.isProbablePrime(10)){ + BigInteger[] dr = a.divideAndRemainder(b); + if(dr[1].equals(BigInteger.ZERO)){ + result.add(b); + a = dr[0]; + } + } + b = b.add(TWO); + } + result.add(b); //b will always be prime here... + } + return result; + } + + public static boolean isSemi(BigInteger x){ + List decomp = primeDecomp(x); + return decomp != null && decomp.size() == 2; + } + + public static void main(String[] args){ + for(int i = 2; i <= 100; i++){ + if(isSemi(BigInteger.valueOf(i))){ + System.out.print(i + " "); + } + } + System.out.println(); + for(int i = 1675; i <= 1680; i++){ + if(isSemi(BigInteger.valueOf(i))){ + System.out.print(i + " "); + } + } + } +} diff --git a/Task/Semiprime/Julia/semiprime.julia b/Task/Semiprime/Julia/semiprime.julia new file mode 100644 index 0000000000..0635e626ad --- /dev/null +++ b/Task/Semiprime/Julia/semiprime.julia @@ -0,0 +1 @@ +semiprime(n) = sum(values(factor(n))) == 2 diff --git a/Task/Semiprime/Mathematica/semiprime-1.math b/Task/Semiprime/Mathematica/semiprime-1.math new file mode 100644 index 0000000000..82ea8d0210 --- /dev/null +++ b/Task/Semiprime/Mathematica/semiprime-1.math @@ -0,0 +1,5 @@ +semiPrimeQ[n_Integer] := Module[{factors, numfactors}, + factors = FactorInteger[n] // Transpose; + numfactors = factors[[2]] // Total ; + numfactors == 2 + ] diff --git a/Task/Semiprime/Mathematica/semiprime-2.math b/Task/Semiprime/Mathematica/semiprime-2.math new file mode 100644 index 0000000000..d871383239 --- /dev/null +++ b/Task/Semiprime/Mathematica/semiprime-2.math @@ -0,0 +1,2 @@ +semiPrimeQ[#] & /@ Range[100]; +Position[%, True] // Flatten diff --git a/Task/Semiprime/Objeck/semiprime.objeck b/Task/Semiprime/Objeck/semiprime.objeck new file mode 100644 index 0000000000..9f68ecb2b8 --- /dev/null +++ b/Task/Semiprime/Objeck/semiprime.objeck @@ -0,0 +1,25 @@ +class SemiPrime { + function : Main(args : String[]) ~ Nil { + for(i := 0; i < 100; i+=1;) { + if(SemiPrime(i)) { + "{$i} "->Print(); + }; + }; + IO.Console->PrintLine(); + } + + function : native : SemiPrime(n : Int) ~ Bool { + nf := 0; + for(i := 2; i <= n; i+=1;) { + while(n%i = 0) { + if(nf = 2) { + return false; + }; + nf+=1; + n /= i; + }; + }; + + return nf = 2; + } +} diff --git a/Task/Semiprime/PARI-GP/semiprime-1.pari b/Task/Semiprime/PARI-GP/semiprime-1.pari new file mode 100644 index 0000000000..d021660196 --- /dev/null +++ b/Task/Semiprime/PARI-GP/semiprime-1.pari @@ -0,0 +1 @@ +issemi(n)=bigomega(n)==2 diff --git a/Task/Semiprime/PARI-GP/semiprime-2.pari b/Task/Semiprime/PARI-GP/semiprime-2.pari new file mode 100644 index 0000000000..4e54d2aa55 --- /dev/null +++ b/Task/Semiprime/PARI-GP/semiprime-2.pari @@ -0,0 +1,5 @@ +issemi(n)={ + forprime(p=2,97,if(n%p==0, return(isprime(n/p)))); + if(isprime(n), return(0)); + bigomega(n)==2 +}; diff --git a/Task/Semiprime/PARI-GP/semiprime-3.pari b/Task/Semiprime/PARI-GP/semiprime-3.pari new file mode 100644 index 0000000000..a952c1241a --- /dev/null +++ b/Task/Semiprime/PARI-GP/semiprime-3.pari @@ -0,0 +1,77 @@ +long +issemiprime(GEN n) +{ + if (typ(n) != t_INT) + pari_err_TYPE("issemiprime", n); + if (signe(n) <= 0) + return 0; + + ulong nn = itou_or_0(n); + if (nn) + return uissemiprime(nn); + + pari_sp ltop = avma; + if (!mpodd(n)) { + long ret = mod4(n) && isprime(shifti(n, -1)); + avma = ltop; + return ret; + } + + + long p; + forprime_t primepointer; + u_forprime_init(&primepointer, 3, 997); + while ((p = u_forprime_next(&primepointer))) { + if (dvdis(n, p)) { + long ret = isprime(diviuexact(n, p)); + avma = ltop; + return ret; + } + } + + if (isprime(n)) + return 0; + + if (DEBUGLEVEL > 3) + pari_printf("issemi: Number is a composite with no small prime factors; using general factoring mechanisms."); + + GEN fac = Z_factor_until(n, shifti(n, -1)); /* Find a nontrivial factor -- returns just the factored part */ + GEN expo = gel(fac, 2); + GEN pr = gel(fac, 1); + long len = glength(expo); + if (len > 2) { + avma = ltop; + return 0; + } + if (len == 2) { + if (cmpis(gel(expo, 1), 1) > 0 || cmpis(gel(expo, 2), 1) > 0) { + avma = ltop; + return 0; + } + GEN P = gel(pr, 1); + GEN Q = gel(pr, 2); + long ret = isprime(P) && isprime(Q) && equalii(mulii(P, Q), n); + avma = ltop; + return ret; + } + if (len == 1) { + long e = itos(gel(expo, 1)); + if (e == 2) { + GEN P = gel(pr, 1); + long ret = isprime(P) && equalii(sqri(P), n); + avma = ltop; + return ret; + } else if (e > 2) { + avma = ltop; + return 0; + } + GEN P = gel(pr, 1); + long ret = isprime(P) && isprime(diviiexact(n, P)); + avma = ltop; + return ret; + } + + pari_err_BUG(pari_sprintf("Z_factor_until returned an unexpected value %Ps at n = %Ps, exiting...", fac, n)); + avma = ltop; + return 0; /* never used */ +} diff --git a/Task/Semiprime/PL-I/semiprime.pli b/Task/Semiprime/PL-I/semiprime.pli new file mode 100644 index 0000000000..0e8e893f66 --- /dev/null +++ b/Task/Semiprime/PL-I/semiprime.pli @@ -0,0 +1,89 @@ +*process source attributes xref nest or(!); + /*-------------------------------------------------------------------- + * 22.02.2014 Walter Pachl using the is_prime code from + * PL/I 'prime decomposition' + * 23.02. WP start test for second prime with 2 or first prime found + *-------------------------------------------------------------------*/ + spb: Proc options(main); + Dcl a(10) Bin Fixed(31) + Init(900660121,2,4,1679,1234567,32768,99,9876543,100,5040); + Dcl (x,n,nf,i,j) Bin Fixed(31) Init(0); + Dcl f(3) Bin Fixed(31); + Dcl txt Char(30) Var; + Dcl bit Bit(1); + Do i=1 To hbound(a); + bit=is_semiprime(a(i)); + Select(nf); + When(0,1) txt=' is prime'; + When(2) txt=' is semiprime '!!factors(a(i)); + Otherwise txt=' is NOT semiprime '!!factors(a(i)); + End; + Put Edit(a(i),bit,txt)(Skip,f(10),x(1),b(1),a); + End; + + is_semiprime: Proc(x) Returns(bit(1)); + /*-------------------------------------------------------------------- + * Returns '1'b if x is semiprime, '0'b otherwise + * in addition + * it sets f(1) and f(2) to the first (or only) prime factor(s) + *-------------------------------------------------------------------*/ + Dcl x Bin Fixed(31); + nf=0; + f=0; + x=a(i); + n=x; + f(1)=2; + loop: + Do While(nf<=2 & n>1); + If is_prime(n) Then Do; + Call mem(n); + Leave loop; + End; + Else Do; + loop2: + Do j=f(1) By 1 While(j*j<=n); + If is_prime(j)&mod(n,j)=0 Then Do; + Call mem(j); + n=n/j; + Leave loop2; + End; + End; + End; + End; + Return(nf=2); + End; + + is_prime: Proc(n) Returns(bit(1)); + Dcl n Bin Fixed(31); + Dcl i Bin Fixed(31); + If n < 2 Then Return('0'b); + If n = 2 Then Return('1'b); + If mod(n,2)=0 Then Return('0'b); + Do i = 3 by 2 While(i*i<=n); + If mod(n,i)=0 Then Return('0'b); + End; + Return('1'b); + End is_prime; + + mem: Proc(x); + Dcl x Bin Fixed(31); + nf+=1; + f(nf)=x; + End; + + factors: Proc(x) Returns(Char(150) Var); + Dcl x Bin Fixed(31); + Dcl (res,net) Char(150) Var Init(''); + Dcl (i,f3) Bin Fixed(31); + res=f(1)!!'*'!!f(2); + f3=x/(f(1)*f(2)); + If f3>1 Then + res=res!!'*'!!f3; + Do i=1 To length(res); + If substr(res,i,1)>' ' Then + net=net!!substr(res,i,1); + End; + Return(net); + End; + + End spb; diff --git a/Task/Semiprime/Pascal/semiprime.pascal b/Task/Semiprime/Pascal/semiprime.pascal new file mode 100644 index 0000000000..ec0f582094 --- /dev/null +++ b/Task/Semiprime/Pascal/semiprime.pascal @@ -0,0 +1,41 @@ +program SemiPrime; +{$IFDEF FPC} + {$Mode objfpc}// compiler switch to use result +{$ELSE} + {$APPTYPE CONSOLE} // for Delphi +{$ENDIF} +uses + primTrial; + +function isSemiprime(n: longWord;doWrite:boolean): boolean; +var + fac1 : LongWord; +begin + //a simple isAlmostPrime(n,2) would do without output; + fac1 := SmallFactor(n); + IF fac1 < n then + Begin + n := n div fac1; + result := SmallFactor(n) = n; + if result AND doWrite then + write(fac1:10,'*',n:11) + end + else + result := false; +end; +var + i,k : longWord; +BEGIN + For i := 2 to 97 do + IF isSemiPrime(i,false) then + write(i:3); + writeln; + //test for big numbers + k := 4000*1000*1000; + i := k-100; + repeat + IF isSemiPrime(i,true) then + writeln(' = ',i:10); + inc(i); + until i> k; +END. diff --git a/Task/Semiprime/Perl-6/semiprime.pl6 b/Task/Semiprime/Perl-6/semiprime.pl6 new file mode 100644 index 0000000000..e28515ca60 --- /dev/null +++ b/Task/Semiprime/Perl-6/semiprime.pl6 @@ -0,0 +1,15 @@ +sub is-semiprime (Int $n --> Bool) { + not $n.is-prime and + .is-prime given + $n div first $n %% *, + grep &is-prime, 2 .. *; +} + +use Test; +my @primes = grep &is-prime, 2 .. 100; +for ^5 { + nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1; + ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2; + nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3; + nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4; +} diff --git a/Task/Semiprime/Perl/semiprime-1.pl b/Task/Semiprime/Perl/semiprime-1.pl new file mode 100644 index 0000000000..863eefa3c8 --- /dev/null +++ b/Task/Semiprime/Perl/semiprime-1.pl @@ -0,0 +1,4 @@ +use ntheory "factor"; +print join(" ", grep { scalar factor($_) == 2 } 1..100),"\n"; +print join(" ", grep { scalar factor($_) == 2 } 1675..1681),"\n"; +print join(" ", grep { scalar factor($_) == 2 } (2,4,99,100,1679,5040,32768,1234567,9876543,900660121)),"\n"; diff --git a/Task/Semiprime/Perl/semiprime-2.pl b/Task/Semiprime/Perl/semiprime-2.pl new file mode 100644 index 0000000000..d00e3dbd8a --- /dev/null +++ b/Task/Semiprime/Perl/semiprime-2.pl @@ -0,0 +1,9 @@ +use ntheory qw/factor is_prime trial_factor/; +sub issemi { + my $n = shift; + if ((my @p = trial_factor($n,500)) > 1) { + return 0 if @p > 2; + return !!is_prime($p[1]) if @p == 2; + } + 2 == factor($n); +} diff --git a/Task/Semiprime/PicoLisp/semiprime.l b/Task/Semiprime/PicoLisp/semiprime.l new file mode 100644 index 0000000000..f9792acb16 --- /dev/null +++ b/Task/Semiprime/PicoLisp/semiprime.l @@ -0,0 +1,21 @@ +(de factor (N) + (make + (let + (D 2 + L (1 2 2 . (4 2 4 2 4 6 2 6 .)) + M (sqrt N) ) + (while (>= M D) + (if (=0 (% N D)) + (setq M + (sqrt (setq N (/ N (link D)))) ) + (inc 'D (pop 'L)) ) ) + (link N) ) ) ) + +(println + (filter + '((X) + (let L (factor X) + (and (cdr L) (not (cddr L))) ) ) + (conc (range 1 100) (range 1675 1680)) ) ) + +(bye) diff --git a/Task/Semiprime/Python/semiprime-1.py b/Task/Semiprime/Python/semiprime-1.py new file mode 100644 index 0000000000..d1167b6e0c --- /dev/null +++ b/Task/Semiprime/Python/semiprime-1.py @@ -0,0 +1,8 @@ +from prime_decomposition import decompose + +def semiprime(n): + d = decompose(n) + try: + return next(d) * next(d) == n + except: + return False diff --git a/Task/Semiprime/Python/semiprime-2.py b/Task/Semiprime/Python/semiprime-2.py new file mode 100644 index 0000000000..4db1e086c7 --- /dev/null +++ b/Task/Semiprime/Python/semiprime-2.py @@ -0,0 +1,5 @@ +>>> semiprime(1679) +True +>>> [n for n in range(1,101) if semiprime(n)] +[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95] +>>> diff --git a/Task/Semiprime/README b/Task/Semiprime/README new file mode 100644 index 0000000000..2a6aebefeb --- /dev/null +++ b/Task/Semiprime/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Semiprime diff --git a/Task/Semiprime/REXX/semiprime-1.rexx b/Task/Semiprime/REXX/semiprime-1.rexx new file mode 100644 index 0000000000..5863de24ab --- /dev/null +++ b/Task/Semiprime/REXX/semiprime-1.rexx @@ -0,0 +1,56 @@ +/* REXX --------------------------------------------------------------- +* 20.02.2014 Walter Pachl relying on 'prime decomposition' +* 21.02.2014 WP Clarification: I copied the algorithm created by +* Gerard Schildberger under the task referred to above +* 21.02.2014 WP Make sure that factr is not called illegally +*--------------------------------------------------------------------*/ +Call test 4 +Call test 9 +Call test 10 +Call test 12 +Call test 1679 +Exit + +test: +Parse Arg z +If is_semiprime(z) Then Say z 'is semiprime' fl + Else Say z 'is NOT semiprime' fl +Return + +is_semiprime: + Parse Arg z + If z<1 | datatype(z,'W')=0 Then Do + Say 'Argument ('z') must be a natural number (1, 2, 3, ...)' + fl='' + End + Else + fl=factr(z) + Return words(fl)=2 + +/*----------------------------------FACTR subroutine-----------------*/ +factr: procedure; parse arg x 1 z,list /*sets X&Z to arg1, LIST=''. */ +if x==1 then return '' /*handle the special case of X=1.*/ +j=2; call .factr /*factor for the only even prime.*/ +j=3; call .factr /*factor for the 1st odd prime.*/ +j=5; call .factr /*factor for the 2nd odd prime.*/ +j=7; call .factr /*factor for the 3rd odd prime.*/ +j=11; call .factr /*factor for the 4th odd prime.*/ +j=13; call .factr /*factor for the 5th odd prime.*/ +j=17; call .factr /*factor for the 6th odd prime.*/ + /* [?] could be optimized more.*/ + /* [?] J in loop starts at 17+2*/ + do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by 3. */ + if right(j,1)==5 then iterate /*fast check for divisible by 5. */ + if j*j>z then leave /*are we higher than the v of Z ?*/ + if j>Z then leave /*are we higher than value of Z ?*/ + call .factr /*invoke .FACTR for some factors.*/ + end /*y*/ /* [?] only tests up to the v X.*/ + /* [?] LIST has a leading blank.*/ +if z==1 then return list /*if residual=unity, don't append*/ + return list z /*return list, append residual. */ +/*-------------------------------.FACTR internal subroutine----------*/ +.factr: do while z//j==0 /*keep dividing until we can't. */ + list=list j /*add number to the list (J). */ + z=z%j /*% (percent) is integer divide.*/ + end /*while z··· */ /* // ?---remainder integer ÷.*/ +return /*finished, now return to invoker*/ diff --git a/Task/Semiprime/REXX/semiprime-2.rexx b/Task/Semiprime/REXX/semiprime-2.rexx new file mode 100644 index 0000000000..5035063758 --- /dev/null +++ b/Task/Semiprime/REXX/semiprime-2.rexx @@ -0,0 +1,30 @@ +/*REXX program determines if any number (or a range) is/are semiprime.*/ +parse arg bot top . /*obtain #s from the command line*/ +if bot=='' then bot=random() /*so, the user wants us to guess.*/ +if top=='' then top=bot /*maybe define a range of numbers*/ +w=max(length(bot), length(top)) /*get maximum width of numbers. */ +if w>digits() then numeric digits w /*is there enough digits ? */ + do n=bot to top /*show results for a range of #s.*/ + if isSemiPrime(n) then say right(n,w) ' is semiprime.' + else say right(n,w) " isn't semiprime." + end /*n*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPRIME subroutine──────────────────*/ +isPrime: procedure; parse arg x; if x<2 then return 0 +if wordpos(x,'2 3 5 7')\==0 then return 1 /*handle some special cases*/ + do i=2 for 2; if x//i==0 then return 0; end /*i*/ /*÷ by 2 & 3*/ + do j=5 by 6 until j*j>x; if x//j==0 then return 0 /*¬ a prime#*/ + if x//(j+2)==0 then return 0 /*¬ a prime#*/ + end /*j*/ +return 1 /*X is a prime number, for sure.*/ +/*──────────────────────────────────ISSEMIPRIME subroutine──────────────*/ +isSemiPrime: procedure; arg x; if \datatype(x,'W') | x<4 then return 0 +x=x/1 /*normalize the X number. */ + do i=2 for 2; if x//i==0 then if isPrime(x%i) then return 1 + else return 0 + end /*i*/ /* [↑] divides by two and three.*/ + do j=5 by 6; if j*j>x then return 0 /*÷ by #s. */ + do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1 + else return 0 + end /*k*/ /*see if 2nd factor is prime or ¬*/ + end /*j*/ /*[↑] never ÷ by # divisible by 3*/ diff --git a/Task/Semiprime/Racket/semiprime-1.rkt b/Task/Semiprime/Racket/semiprime-1.rkt new file mode 100644 index 0000000000..ee737562b5 --- /dev/null +++ b/Task/Semiprime/Racket/semiprime-1.rkt @@ -0,0 +1,15 @@ +#lang racket +(require math) + +(define (pair-factorize n) + "Return all two-number factorizations of a number" + (let ([up-limit (integer-sqrt n)]) + (map (λ (x) (list x (/ n x))) + (filter (λ (x) (<= x up-limit)) (divisors n))))) + +(define (semiprime n) + "Determine if a number is semiprime i.e. a product of two primes. +Check if any pair of complete factors consists of primes." + (for/or ((pair (pair-factorize n))) + (for/and ((el pair)) + (prime? el)))) diff --git a/Task/Semiprime/Racket/semiprime-2.rkt b/Task/Semiprime/Racket/semiprime-2.rkt new file mode 100644 index 0000000000..843ec1dc61 --- /dev/null +++ b/Task/Semiprime/Racket/semiprime-2.rkt @@ -0,0 +1,12 @@ +#lang racket +(require math) + +(define (semiprime n) + "Alternative implementation. +Check if there are two prime factors whose product is the argument +or if there is a single prime factor whose square is the argument" + (let ([prime-factors (factorize n)]) + (or (and (= (length prime-factors) 1) + (= (expt (caar prime-factors) (cadar prime-factors)) n)) + (and (= (length prime-factors) 2) + (= (foldl (λ (x y) (* (car x) y)) 1 prime-factors) n))))) diff --git a/Task/Semiprime/Ruby/semiprime.rb b/Task/Semiprime/Ruby/semiprime.rb new file mode 100644 index 0000000000..37e6ef853e --- /dev/null +++ b/Task/Semiprime/Ruby/semiprime.rb @@ -0,0 +1,12 @@ +require 'prime' +# 75.prime_division # Returns the factorization.75 divides by 3 once and by 5 twice => [[3, 1], [5, 2]] + +class Integer + def semi_prime? + prime_division.map( &:last ).inject( &:+ ) == 2 + end +end + +p 1679.semi_prime? # true +p ( 1..100 ).select( &:semi_prime? ) +# [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95] diff --git a/Task/Semiprime/Scala/semiprime.scala b/Task/Semiprime/Scala/semiprime.scala new file mode 100644 index 0000000000..2f1995dae9 --- /dev/null +++ b/Task/Semiprime/Scala/semiprime.scala @@ -0,0 +1,20 @@ +object Semiprime extends App { + + def isSP(n: Int): Boolean = { + var nf: Int = 0 + var l = n + for (i <- 2 to l/2) { + while (l % i == 0) { + if (nf == 2) return false + nf +=1 + l /= i + } + } + nf == 2 + } + + (2 to 100) filter {isSP(_) == true} foreach {i => print("%d ".format(i))} + println + 1675 to 1681 foreach {i => println(i+" -> "+isSP(i))} + +} diff --git a/Task/Semiprime/Seed7/semiprime.seed7 b/Task/Semiprime/Seed7/semiprime.seed7 new file mode 100644 index 0000000000..281c2d7bae --- /dev/null +++ b/Task/Semiprime/Seed7/semiprime.seed7 @@ -0,0 +1,27 @@ +$ include "seed7_05.s7i"; + +const func boolean: semiPrime (in var integer: n) is func + result + var boolean: isSemiPrime is TRUE; + local + var integer: p is 2; + var integer: f is 0; + begin + while f < 2 and p**2 <= n do + while n rem p = 0 do + n := n div p; + incr(f); + end while; + incr(p); + end while; + isSemiPrime := f + ord(n > 1) = 2; + end func; + +const proc: main is func + local + var integer: v is 0; + begin + for v range 1675 to 1680 do + writeln(v <& " -> " <& semiPrime(v)); + end for; + end func; diff --git a/Task/Semiprime/Tcl/semiprime.tcl b/Task/Semiprime/Tcl/semiprime.tcl new file mode 100644 index 0000000000..04e68536ce --- /dev/null +++ b/Task/Semiprime/Tcl/semiprime.tcl @@ -0,0 +1,24 @@ +package require math::numtheory + +proc isSemiprime n { + if {!($n & 1)} { + return [::math::numtheory::isprime [expr {$n >> 1}]] + } + for {set i 3} {$i*$i < $n} {incr i 2} { + if {$n / $i * $i != $n && [::math::numtheory::isprime $i]} { + if {[::math::numtheory::isprime [expr {$n/$i}]]} { + return 1 + } + } + } + return 0 +} + +for {set n 1675} {$n <= 1680} {incr n} { + puts -nonewline "$n is ... " + if {[isSemiprime $n]} { + puts "a semiprime" + } else { + puts "NOT a semiprime" + } +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION b/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION new file mode 100644 index 0000000000..461d54472e --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION @@ -0,0 +1,7 @@ +Generate a sequence of primes by means of trial division. + +Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. + +The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the [[Primality by trial division]] page (i.e., add yours there if it isn't there already). + +* Closely related to: [[Primality by trial division]], [[Sieve of Eratosthenes]]. diff --git a/Task/Sequence-of-primes-by-Trial-Division/00META.yaml b/Task/Sequence-of-primes-by-Trial-Division/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Sequence-of-primes-by-Trial-Division/ATS/sequence-of-primes-by-trial-division.ats b/Task/Sequence-of-primes-by-Trial-Division/ATS/sequence-of-primes-by-trial-division.ats new file mode 100644 index 0000000000..bbdac49dc5 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/ATS/sequence-of-primes-by-trial-division.ats @@ -0,0 +1,70 @@ +(* +// Lazy-evaluation: +// sieve for primes +*) +(* ****** ****** *) +// +// How to compile: +// with no GC: +// patscc -D_GNU_SOURCE -DATS_MEMALLOC_LIBC -o sieve sieve.dats +// with Boehm-GC: +// patscc -D_GNU_SOURCE -DATS_MEMALLOC_GCBDW -o sieve sieve.dats -lgc +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +#define :: stream_cons +#define cons stream_cons +#define nil stream_nil + +(* ****** ****** *) +// +fun +from{n:int} (n: int n) + : stream (intGte(n)) = $delay (cons{intGte(n)}(n, from (n+1))) +// +(* ****** ****** *) + +typedef N2 = intGte(2) + +(* ****** ****** *) + +fun sieve +( + ns: stream N2 +) : + stream (N2) = $delay +( +let + val-cons(n, ns) = !ns +in + cons{N2}(n, sieve (stream_filter_cloref (ns, lam x => g1int_nmod(x, n) > 0))) +end : stream_con (N2) +) // end of [sieve] + +// + +val primes: stream (N2) = sieve (from(2)) + +// + +macdef prime_get (n) = stream_nth_exn (primes, ,(n)) + +// + +implement +main0 () = begin +// +println! ("prime 1000 = ", prime_get (1000)) ; // = 7927 +(* +println! ("prime 5000 = ", prime_get (5000)) ; // = 48619 +println! ("prime 10000 = ", prime_get (10000)) ; // = 104743 +*) +// +end // end of [main0] + +(* ****** ****** *) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Ada/sequence-of-primes-by-trial-division.ada b/Task/Sequence-of-primes-by-Trial-Division/Ada/sequence-of-primes-by-trial-division.ada new file mode 100644 index 0000000000..9c9e2ffe10 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Ada/sequence-of-primes-by-trial-division.ada @@ -0,0 +1,18 @@ +with Prime_Numbers, Ada.Text_IO, Ada.Command_Line; + +procedure Sequence_Of_Primes is + + package Integer_Numbers is new + Prime_Numbers (Natural, 0, 1, 2); + use Integer_Numbers; + + Start: Natural := Natural'Value(Ada.Command_Line.Argument(1)); + Stop: Natural := Natural'Value(Ada.Command_Line.Argument(2)); + +begin + for I in Start .. Stop loop + if Is_Prime(I) then + Ada.Text_IO.Put(Natural'Image(I)); + end if; + end loop; +end Sequence_Of_Primes; diff --git a/Task/Sequence-of-primes-by-Trial-Division/D/sequence-of-primes-by-trial-division.d b/Task/Sequence-of-primes-by-Trial-Division/D/sequence-of-primes-by-trial-division.d new file mode 100644 index 0000000000..267ab5e534 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/D/sequence-of-primes-by-trial-division.d @@ -0,0 +1,23 @@ +import std.stdio, std.range, std.algorithm, std.traits, + std.numeric, std.concurrency; + +Generator!(ForeachType!R) nubBy(alias pred, R)(R items) { + return new typeof(return)({ + ForeachType!R[] seen; + + OUTER: foreach (x; items) { + foreach (y; seen) + if (pred(x, y)) + continue OUTER; + yield(x); + seen ~= x; + } + }); +} + +void main() /*@safe*/ { + sequence!q{n + 2} + .nubBy!((x, y) => gcd(x, y) > 1) + .take(20) + .writeln; +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-1.go b/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-1.go new file mode 100644 index 0000000000..ebbc9d635d --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-1.go @@ -0,0 +1,52 @@ +package main + +import "fmt" + +func NumsFromBy(from int, by int, ch chan<- int) { + for i := from; ; i+=by { + ch <- i + } +} + +func Filter(in <-chan int, out chan<- int, prime int) { + for { + i := <-in + if i%prime != 0 { // here is the trial division + out <- i + } + } +} + +func Sieve(out chan<- int) { + out <- 2 + out <- 3 + q := 9 + ps := make(chan int) + go Sieve(ps) // separate primes supply + p := <-ps + p = <-ps + nums := make(chan int) + go NumsFromBy(5,2,nums) // end of setup + for i := 0; ; i++ { + n := <-nums + if n < q { + out <- n // n is prime + } else { + ch1 := make(chan int) + go Filter(nums, ch1, p) // postponed creation of a filter + nums = ch1 + p = <-ps + q = p*p + } + } +} + +func main() { + ch := make(chan int) + go Sieve(ch) + fmt.Print("First twenty:") + for i := 0; i < 20; i++ { + fmt.Print(" ", <-ch) + } + fmt.Println() +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-2.go b/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-2.go new file mode 100644 index 0000000000..fcaadaf98f --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Go/sequence-of-primes-by-trial-division-2.go @@ -0,0 +1,32 @@ +package main + +import "fmt" + +func newP() func() int { + n := 1 + return func() int { + for { + n++ + // Trial division as naïvely as possible. For a candidate n, + // numbers between 1 and n are checked to see if they divide n. + // If no number divides n, n is prime. + for f := 2; ; f++ { + if f == n { + return n + } + if n%f == 0 { // here is the trial division + break + } + } + } + } +} + +func main() { + p := newP() + fmt.Print("First twenty:") + for i := 0; i < 20; i++ { + fmt.Print(" ", p()) + } + fmt.Println() +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-1.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-1.hs new file mode 100644 index 0000000000..698797d55c --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-1.hs @@ -0,0 +1 @@ +primesFromTo n m = filter isPrime [n..m] diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-2.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-2.hs new file mode 100644 index 0000000000..50a2967ae8 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-2.hs @@ -0,0 +1,3 @@ +import Data.List (nubBy) + +primes = nubBy (((>1).).gcd) [2..] diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-3.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-3.hs new file mode 100644 index 0000000000..7df982ee69 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-3.hs @@ -0,0 +1,2 @@ +primes = 2 : 3 : [n | n <- [5,7..], foldr (\p r-> p*p > n || rem n p > 0 && r) + True (drop 1 primes)] diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-4.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-4.hs new file mode 100644 index 0000000000..132f64e500 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-4.hs @@ -0,0 +1,5 @@ +primesT = sieve [2..] + where + sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0] +-- map head +-- . iterate (\(p:xs)-> [x | x <- xs, rem x p /= 0]) $ [2..] diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-5.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-5.hs new file mode 100644 index 0000000000..75bad55f76 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-5.hs @@ -0,0 +1,6 @@ +primesTo m = 2 : sieve [3,5..m] + where + sieve (p:xs) | p*p > m = p : xs + | otherwise = p : sieve [x | x <- xs, rem x p /= 0] +-- map fst a ++ b:c where (a,(b,c):_) = span ((< m).(^2).fst) +-- . iterate (\(_,p:xs)-> (p, [x | x <- xs, rem x p /= 0])) $ (2, [3,5..m]) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-6.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-6.hs new file mode 100644 index 0000000000..ce1d956e4a --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-6.hs @@ -0,0 +1,8 @@ +primesPT = 2 : 3 : sieve [5,7..] 9 (tail primesPT) + where + sieve (x:xs) q ps@(p:t) + | x < q = x : sieve xs q ps -- inlined (span (< q)) + | otherwise = sieve [y | y <- xs, rem y p /= 0] (head t^2) t +-- ps = concat . map fst +-- . iterate (\(_,(ns,p:t))-> let (h,xs)=span (< p*p) ns in +-- (h, ([y | y <- xs, rem y p /= 0], t))) $ ([2,3], ([5,7..], tail ps)) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-7.hs b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-7.hs new file mode 100644 index 0000000000..f658b8cb00 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Haskell/sequence-of-primes-by-trial-division-7.hs @@ -0,0 +1,6 @@ +import Data.List (inits) + +primesST = 2 : 3 : sieve 5 9 (drop 2 primesST) (inits $ tail primesST) + where + sieve x q ps (fs:ft) = filter (\y-> all ((/=0).rem y) fs) [x,x+2..q-2] + ++ sieve (q+2) (head ps^2) (tail ps) ft diff --git a/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-1.j b/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-1.j new file mode 100644 index 0000000000..50c65181a0 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-1.j @@ -0,0 +1,5 @@ +primTrial=:3 :0 + try=. i.&.(p:inv) %: >./ y + candidate=. (y>1)*y=<.y + y #~ candidate*(y e.try) = +/ 0= try|/ y +) diff --git a/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-2.j b/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-2.j new file mode 100644 index 0000000000..acc10aea79 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/J/sequence-of-primes-by-trial-division-2.j @@ -0,0 +1,2 @@ + primTrial 1e6+i.100 +1000003 1000033 1000037 1000039 1000081 1000099 diff --git a/Task/Sequence-of-primes-by-Trial-Division/Perl-6/sequence-of-primes-by-trial-division.pl6 b/Task/Sequence-of-primes-by-Trial-Division/Perl-6/sequence-of-primes-by-trial-division.pl6 new file mode 100644 index 0000000000..b1707906fb --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Perl-6/sequence-of-primes-by-trial-division.pl6 @@ -0,0 +1,3 @@ +constant @primes = 2, 3, { first * %% none(@_), (@_[* - 1], * + 2 ... *) } ... *; + +say @primes[^100]; diff --git a/Task/Sequence-of-primes-by-Trial-Division/README b/Task/Sequence-of-primes-by-Trial-Division/README new file mode 100644 index 0000000000..f3cee42919 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Sequence_of_primes_by_Trial_Division diff --git a/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-1.rexx b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-1.rexx new file mode 100644 index 0000000000..f1c6e6e7dc --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-1.rexx @@ -0,0 +1,18 @@ +/*REXX pgm lists a sequence of primes by testing primality by trial div.*/ +parse arg n . /*let user choose how many, maybe*/ +if n=='' then n=26 /*if not, then assume the default*/ +tell=n>0; n=abs(n) /*N is negative? Don't display.*/ +@.1=2; if tell then say right(@.1,9) /*display 2 as a special case. */ +#=1 /*# is the number of primes found*/ + /* [↑] N default lists up to 101*/ + do j=3 by 2 while #0; n=abs(n) /*N is negative? Don't display.*/ +@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #=5; s=@.#+2 + /* [↑] is the # of low primes.*/ + do p=1 for # while p<=n /* [↓] don't compute, just list.*/ + if tell then say right(@.p,9) /*display some low primes. */ + !.p=@.p**2 /*also compute the squared value.*/ + end /*p*/ /* [↑] allows faster loop below.*/ + /* [↓] N default lists up to 101*/ + do j=s by 2 while #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 (nats) (for ([i (in-naturals 1)]) (out! i))) +(define-thread-loop (filter pred? c) + (let ([x (channel-get c)]) (when (pred? x) (out! x)))) +(define (sift n c) (filter (λ(x) (not (zero? (modulo x n)))) c)) +(define-thread-loop (sieve c) + (let ([x (channel-get c)]) (out! x) (set! c (sift x c)))) +(define primes (let ([ns (nats)]) (channel-get ns) (sieve ns))) +(for/list ([i 25] [x (in-producer (λ() (channel-get primes)))]) x) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-4.rkt b/Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-4.rkt new file mode 100644 index 0000000000..39499081d6 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Racket/sequence-of-primes-by-trial-division-4.rkt @@ -0,0 +1,10 @@ +#lang racket +(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))) +(for/list ([i 25] [x (in-producer primes)]) x) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Ruby/sequence-of-primes-by-trial-division.rb b/Task/Sequence-of-primes-by-Trial-Division/Ruby/sequence-of-primes-by-trial-division.rb new file mode 100644 index 0000000000..78996587fb --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Ruby/sequence-of-primes-by-trial-division.rb @@ -0,0 +1,5 @@ +require "prime" + +pg = Prime::TrialDivisionGenerator.new +p pg.take(10) # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] +p pg.next # => 31 diff --git a/Task/Sequence-of-primes-by-Trial-Division/Scala/sequence-of-primes-by-trial-division.scala b/Task/Sequence-of-primes-by-Trial-Division/Scala/sequence-of-primes-by-trial-division.scala new file mode 100644 index 0000000000..97403f9747 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Scala/sequence-of-primes-by-trial-division.scala @@ -0,0 +1,6 @@ +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)) + + println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) + println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Tcl/sequence-of-primes-by-trial-division.tcl b/Task/Sequence-of-primes-by-Trial-Division/Tcl/sequence-of-primes-by-trial-division.tcl new file mode 100644 index 0000000000..9be249dcab --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Tcl/sequence-of-primes-by-trial-division.tcl @@ -0,0 +1,16 @@ +set primes {} +proc havePrime n { + global primes + foreach p $primes { + # Do the test-by-trial-division + if {$n/$p*$p == $n} {return false} + } + return true +} +for {set n 2} {$n < 100} {incr n} { + if {[havePrime $n]} { + lappend primes $n + puts -nonewline "$n " + } +} +puts "" diff --git a/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION b/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION new file mode 100644 index 0000000000..01eaadcea7 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION @@ -0,0 +1,24 @@ +Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing some pennies on some squares and requiring that a Knight's tour that avoids squares with pennies be constructed. + +This kind of knight's tour puzzle is similar to [[Solve a Hidato puzzle|Hidato]]. + +The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: + +;Example 1 +
+  0 0 0
+  0   0 0
+  0 0 0 0 0 0 0
+0 0 0     0   0
+0   0     0 0 0
+1 0 0 0 0 0 0
+    0 0   0
+      0 0 0
+
+ +Extra credit is available for other interesting examples. + +* [[Solve a Hidato puzzle]] +* [[Solve a Hopido puzzle]] +* [[Solve a Numbrix puzzle]] +* [[Knight's tour]] diff --git a/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada b/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada new file mode 100644 index 0000000000..11e7e51328 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada @@ -0,0 +1,36 @@ +with Knights_Tour, Ada.Text_IO, Ada.Command_Line; + +procedure Holy_Knight is + + Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + package KT is new Knights_Tour(Size => Size); + Board: KT.Tour := (others => (others => Natural'Last)); + + Start_X, Start_Y: KT.Index:= 1; -- default start place (1,1) + S: String(KT.Index); + I: Positive := KT.Index'First; +begin + -- read the board from standard input + while not Ada.Text_IO.End_Of_File and I <= Size loop + S := Ada.Text_IO.Get_Line; + for J in KT.Index loop + if S(J) = ' ' or S(J) = '-' then + Board(I,J) := Natural'Last; + elsif S(J) = '1' then + Start_X := I; Start_Y := J; Board(I,J) := 1; + else Board(I,J) := 0; + end if; + end loop; + I := I + 1; + end loop; + + -- print the board + Ada.Text_IO.Put_Line("Start Configuration (Length:" + & Natural'Image(KT.Count_Moves(Board)) & "):"); + KT.Tour_IO(Board, Width => 1); + Ada.Text_IO.New_Line; + + -- search for the tour and print it + Ada.Text_IO.Put_Line("Tour:"); + KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); +end Holy_Knight; diff --git a/Task/Solve-a-Holy-Knights-tour/Bracmat/solve-a-holy-knights-tour.bracmat b/Task/Solve-a-Holy-Knights-tour/Bracmat/solve-a-holy-knights-tour.bracmat new file mode 100644 index 0000000000..80cfa99870 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Bracmat/solve-a-holy-knights-tour.bracmat @@ -0,0 +1,213 @@ +( ( Holy-Knight + = begin colWidth crumbs non-empty pairs path parseLine + , display isolateStartCell minDistance numberElementsAndSort + , parseBoard reverseList rightAlign solve strlen + . "'non-empty' is a pattern that is used several times in bigger patterns." + & ( non-empty + = + = %@ + : ~( "." + | "-" + | " " + | \t + | \r + | \n + ) + ) + & ( reverseList + = a L + . :?L + & whl'(!arg:%?a ?arg&!a !L:?L) + & !L + ) + & (strlen=e.@(!arg:? [?e)&!e) + & ( rightAlign + = string width + . !arg:(?width,?string) + & !width+-1*strlen$!string:?width + & whl + ' ( !width+-1:~<0:?width + & " " !string:?string + ) + & str$!string + ) + & ( minDistance + = board pat1 pat2 minWidth pos1 pos2 pattern + . !arg:(?board,(=?pat1),(=?pat2)) + & -1:?minWidth + & "Construct a pattern using a template. + The pattern finds the smallest distance between any two columns in the input. + Assumption: all columns have the same width and columns are separated by one or + more spaces. The function can also be used to find the width of the first column + by letting pat1 match a new line." + & + ' ( ? + ( $pat1 + [?pos1 + (? " "|`) + ()$pat2 + [?pos2 + ? + & !pos2+-1*!pos1 + : ( +#include +#include +#include +#include +#include + +using namespace std; + +struct node +{ + int val; + unsigned char neighbors; +}; + +class nSolver +{ +public: + nSolver() + { + dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; + dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; + dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; + dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; + } + + void solve( vector& puzz, int max_wid ) + { + if( puzz.size() < 1 ) return; + wid = max_wid; hei = static_cast( puzz.size() ) / wid; + int len = wid * hei, c = 0; max = len; + arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); + + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } + arr[c].val = atoi( ( *i ).c_str() ); + c++; + } + + solveIt(); c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "." ) + { + ostringstream o; o << arr[c].val; + ( *i ) = o.str(); + } + c++; + } + delete [] arr; + } + +private: + bool search( int x, int y, int w ) + { + if( w > max ) return true; + + node* n = &arr[x + y * wid]; + n->neighbors = getNeighbors( x, y ); + + for( int d = 0; d < 8; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == 0 ) + { + arr[a + b * wid].val = w; + if( search( a, b, w + 1 ) ) return true; + arr[a + b * wid].val = 0; + } + } + } + return false; + } + + unsigned char getNeighbors( int x, int y ) + { + unsigned char c = 0; int a, b; + for( int xx = 0; xx < 8; xx++ ) + { + a = x + dx[xx], b = y + dy[xx]; + if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; + if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); + } + return c; + } + + void solveIt() + { + int x, y, z; findStart( x, y, z ); + if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } + search( x, y, z + 1 ); + } + + void findStart( int& x, int& y, int& z ) + { + z = 99999; + for( int b = 0; b < hei; b++ ) + for( int a = 0; a < wid; a++ ) + if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) + { + x = a; y = b; + z = arr[a + wid * b].val; + } + + } + + int wid, hei, max, dx[8], dy[8]; + node* arr; +}; + +int main( int argc, char* argv[] ) +{ + int wid; string p; + //p = "* . . . * * * * * . * . . * * * * . . . . . . . . . . * * . * . . * . * * . . . 1 . . . . . . * * * . . * . * * * * * . . . * *"; wid = 8; + p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; + istringstream iss( p ); vector puzz; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) ); + nSolver s; s.solve( puzz, wid ); + int c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) != "*" && ( *i ) != "." ) + { + if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; + cout << ( *i ) << " "; + } + else cout << " "; + if( ++c >= wid ) { cout << endl; c = 0; } + } + cout << endl << endl; + return system( "pause" ); +} diff --git a/Task/Solve-a-Holy-Knights-tour/D/solve-a-holy-knights-tour.d b/Task/Solve-a-Holy-Knights-tour/D/solve-a-holy-knights-tour.d new file mode 100644 index 0000000000..cfd5fb980f --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/D/solve-a-holy-knights-tour.d @@ -0,0 +1,133 @@ +import std.stdio, std.conv, std.string, std.range, std.algorithm, + std.typecons, std.typetuple; + + +struct HolyKnightPuzzle { + private alias InputCellBaseType = char; + private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } + private alias Cell = uint; + private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } // Special Cell values. + + // Neighbors, [shift row, shift column]. + static struct P { int x, y; } + alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), + P(-1, -2), P(1, -2), P(-1, 2), P(1, 2)); + + immutable size_t gridWidth, gridHeight; + private immutable Cell nAvailableCells; + private /*immutable*/ const InputCell[] flatPuzzle; + private Cell[] grid; // Flattened mutable game grid. + + @disable this(); + + + this(in string[] rawPuzzle) pure @safe + in { + assert(!rawPuzzle.empty); + assert(!rawPuzzle[0].empty); + assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. + assert(rawPuzzle.join.count(InputCell.start) == 1); // Exactly one start point. + } body { + //immutable puzzle = rawPuzzle.to!(InputCell[][]); + immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); + + gridWidth = puzzle[0].length; + gridHeight = puzzle.length; + flatPuzzle = puzzle.join; + + // This counts the start cell too. + nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable); + + grid = flatPuzzle + .map!(ic => ic.predSwitch(InputCell.available, unknownCell, + InputCell.unavailable, unavailableCell, + InputCell.start, startCell)) + .array; + } + + + Nullable!(string[][]) solve(size_t width)() pure /*nothrow*/ @safe + out(result) { + if (!result.isNull) + assert(!grid.canFind(unknownCell)); + } body { + assert(width == gridWidth); + + // Find start position. + foreach (immutable r; 0 .. gridHeight) + foreach (immutable c; 0 .. width) + if (grid[r * width + c] == startCell && + search!width(r, c, startCell + 1)) { + auto result = zip(flatPuzzle, grid) // Not nothrow. + //.map!({p, c} => ... + .map!(pc => (pc[0] == InputCell.available) ? + pc[1].text : + InputCellBaseType(pc[0]).text) + .array + .chunks(width) + .array; + return typeof(return)(result); + } + + return typeof(return)(); + } + + + private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { + if (cell > nAvailableCells) + return true; // One solution found. + + // This doesn't use the Warnsdorff rule. + foreach (immutable sh; shifts) { + immutable r2 = r + sh.x, + c2 = c + sh.y, + pos = r2 * width + c2; + // No need to test for >= 0 because uint wraps around. + if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { + grid[pos] = cell; // Try. + if (search!width(r2, c2, cell + 1)) + return true; + grid[pos] = unknownCell; // Restore. + } + } + + return false; + } +} + + +void main() @safe { + // Enum HolyKnightPuzzle to catch malformed puzzles at compile-time. + enum puzzle1 = ".###.... + .#.##... + .####### + ###..#.# + #.#..### + 1######. + ..##.#.. + ...###..".split.HolyKnightPuzzle; + + enum puzzle2 = ".....1.#..... + .....#.#..... + ....#####.... + .....###..... + ..#..#.#..#.. + #####...##### + ..##.....##.. + #####...##### + ..#..#.#..#.. + .....###..... + ....#####.... + .....#.#..... + .....#.#.....".split.HolyKnightPuzzle; + + foreach (/*enum*/ puzzle; TypeTuple!(puzzle1, puzzle2)) { + //immutable solution = puzzle.solve!(puzzle.gridWidth); + enum width = puzzle.gridWidth; + immutable solution = puzzle.solve!width; // Solved at run-time. + if (solution.isNull) + writeln("No solution found for puzzle.\n"); + else + writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); + } +} diff --git a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs new file mode 100644 index 0000000000..0b3fd56797 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs @@ -0,0 +1,105 @@ +import qualified Data.Array as Arr +import qualified Data.Foldable as Fold +import qualified Data.List as List +import Data.Maybe + +type Position = (Int, Int) +type KnightBoard = Arr.Array Position (Maybe Int) + +toSlot :: Char -> Maybe Int +toSlot '0' = Just 0 +toSlot '1' = Just 1 +toSlot _ = Nothing + +toString :: Maybe Int -> String +toString Nothing = replicate 3 ' ' +toString (Just n) = replicate (3 - length nn) ' ' ++ nn + where + nn = show n + +chunksOf :: Int -> [a] -> [[a]] +chunksOf _ [] = [] +chunksOf n xs = take n xs : (chunksOf n $ drop n xs) + +showBoard :: KnightBoard -> String +showBoard board = + List.intercalate "\n" . map concat . List.transpose + . chunksOf (height + 1) . map toString $ Arr.elems board + where + (_, (_, height)) = Arr.bounds board + +toBoard :: [String] -> KnightBoard +toBoard strs = board + where + height = length strs + width = minimum $ map length strs + board = Arr.listArray ((0, 0), (width - 1, height - 1)) + . map toSlot . concat . List.transpose $ map (take width) strs + + +add :: Num a => (a, a) -> (a, a) -> (a, a) +add (a, b) (x, y) = (a + x, b + y) + +within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool +within ((a, b), (c, d)) (x, y) = + a <= x && x <= c && + b <= y && y <= d + +-- Enumerate valid moves given a board and a knight's position. +validMoves :: KnightBoard -> Position -> [Position] +validMoves board position = filter isValid plausible + where + bound = Arr.bounds board + plausible = map (add position) [(1, 2), (2, 1), (2, -1), (-1, 2), + (-2, 1), (1, -2), (-1, -2), (-2, -1)] + isValid pos = within bound pos && maybe False (== 0) (board Arr.! pos) + +isSolved :: KnightBoard -> Bool +isSolved = Fold.all (maybe True (/= 0)) + +-- Solve the knight's tour with a simple Depth First Search. +solveKnightTour :: KnightBoard -> Maybe KnightBoard +solveKnightTour board = solve board 1 initPosition + where + initPosition = fst $ head $ filter ((== (Just 1)) . snd) $ Arr.assocs board + solve boardA depth position = + let boardB = boardA Arr.// [(position, Just depth)] + in if isSolved boardB + then Just boardB + else listToMaybe $ mapMaybe (solve boardB $ depth + 1) + $ validMoves boardB position + +tourExA :: [String] +tourExA = + [" 000 " + ," 0 00 " + ," 0000000" + ,"000 0 0" + ,"0 0 000" + ,"1000000 " + ," 00 0 " + ," 000 "] + +tourExB :: [String] +tourExB = + ["-----1-0-----" + ,"-----0-0-----" + ,"----00000----" + ,"-----000-----" + ,"--0--0-0--0--" + ,"00000---00000" + ,"--00-----00--" + ,"00000---00000" + ,"--0--0-0--0--" + ,"-----000-----" + ,"----00000----" + ,"-----0-0-----" + ,"-----0-0-----"] + +main :: IO () +main = + flip mapM_ [tourExA, tourExB] + (\board -> + case solveKnightTour $ toBoard board of + Nothing -> putStrLn "No solution.\n" + Just solution -> putStrLn $ showBoard solution ++ "\n") diff --git a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs new file mode 100644 index 0000000000..82902128f8 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs @@ -0,0 +1,128 @@ +import Control.Monad.ST +import qualified Data.Array.Base as AB +import qualified Data.Array.ST as AST +import qualified Data.Array.Unboxed as AU +import qualified Data.List as List + +type Position = (Int, Int) +type KnightBoard = AU.UArray Position Int + +toSlot :: Char -> Int +toSlot '0' = 0 +toSlot '1' = 1 +toSlot _ = -1 + +toString :: Int -> String +toString (-1) = replicate 3 ' ' +toString n = replicate (3 - length nn) ' ' ++ nn + where + nn = show n + +chunksOf :: Int -> [a] -> [[a]] +chunksOf _ [] = [] +chunksOf n xs = take n xs : (chunksOf n $ drop n xs) + +showBoard :: KnightBoard -> String +showBoard board = + List.intercalate "\n" . map concat . List.transpose + . chunksOf (height + 1) . map toString $ AU.elems board + where + (_, (_, height)) = AU.bounds board + +toBoard :: [String] -> KnightBoard +toBoard strs = board + where + height = length strs + width = minimum $ map length strs + board = AU.listArray ((0, 0), (width - 1, height - 1)) + . map toSlot . concat . List.transpose $ map (take width) strs + +add :: Num a => (a, a) -> (a, a) -> (a, a) +add (a, b) (x, y) = (a + x, b + y) + +within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool +within ((a, b), (c, d)) (x, y) = + a <= x && x <= c && + b <= y && y <= d + +-- Solve the knight's tour with a simple Depth First Search. +solveKnightTour :: KnightBoard -> Maybe KnightBoard +solveKnightTour board = + runST $ do + let + assocs = AU.assocs board + bounds = AU.bounds board + + array <- (AST.newListArray bounds (AU.elems board)) + :: ST s (AST.STUArray s Position Int) + + let + initPosition = fst $ head $ filter ((== 1) . snd) assocs + maxDepth = fromIntegral $ 1 + (length $ filter ((== 0) . snd) assocs) + offsets = + [(1, 2), (2, 1), (2, -1), (-1, 2), + (-2, 1), (1, -2), (-1, -2), (-2, -1)] + + solve depth position = do + if within bounds position + then do + oldValue <- AST.readArray array position + if oldValue == 0 + then do + AST.writeArray array position depth + if depth == maxDepth + then return True + else do + -- This mapM-any combo can be reduced to a string of ||'s + -- with the goal of removing the allocation overhead due to consing + -- which the compiler may not be able to optimize out. + results <- mapM ((solve $ depth + 1) . add position) offsets + if any (== True) results + then return True + else do + AST.writeArray array position oldValue + return False + else return False + else return False + + AST.writeArray array initPosition 0 + result <- solve 1 initPosition + farray <- AB.unsafeFreeze array + return $ if result + then Just farray + else Nothing + +tourExA :: [String] +tourExA = + [" 000 " + ," 0 00 " + ," 0000000" + ,"000 0 0" + ,"0 0 000" + ,"1000000 " + ," 00 0 " + ," 000 "] + +tourExB :: [String] +tourExB = + ["-----1-0-----" + ,"-----0-0-----" + ,"----00000----" + ,"-----000-----" + ,"--0--0-0--0--" + ,"00000---00000" + ,"--00-----00--" + ,"00000---00000" + ,"--0--0-0--0--" + ,"-----000-----" + ,"----00000----" + ,"-----0-0-----" + ,"-----0-0-----"] + +main :: IO () +main = + flip mapM_ [tourExA, tourExB] + (\board -> + case solveKnightTour $ toBoard board of + Nothing -> putStrLn "No solution.\n" + Just solution -> putStrLn $ showBoard solution ++ "\n") diff --git a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-3.hs b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-3.hs new file mode 100644 index 0000000000..3f07bf498b --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-3.hs @@ -0,0 +1,98 @@ +global nCells, cMap, best +record Pos(r,c) + +procedure main(A) + puzzle := showPuzzle("Input",readPuzzle()) + QMouse(puzzle,findStart(puzzle),&null,0) + showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") +end + +procedure readPuzzle() + # Start with a reduced puzzle space + p := [[-1],[-1]] + nCells := maxCols := 0 + every line := !&input do { + put(p,[: -1 | -1 | gencells(line) | -1 | -1 :]) + maxCols <:= *p[-1] + } + every put(p, [-1]|[-1]) + # Now normalize all rows to the same length + every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] + return p +end + +procedure gencells(s) + static WS, NWS + initial { + NWS := ~(WS := " \t") + cMap := table() # Map to/from internal model + cMap["#"] := -1; cMap["_"] := 0 + cMap[-1] := " "; cMap[0] := "_" + } + + s ? while not pos(0) do { + w := (tab(many(WS))|"", tab(many(NWS))) | break + w := numeric(\cMap[w]|w) + if -1 ~= w then nCells +:= 1 + suspend w + } +end + +procedure showPuzzle(label, p) + write(label," with ",nCells," cells:") + every r := !p do { + every c := !r do writes(right((\cMap[c]|c),*nCells+1)) + write() + } + return p +end + +procedure findStart(p) + if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) +end + +procedure solvePuzzle(puzzle) + if path := \best then { + repeat { + loc := path.getLoc() + puzzle[loc.r][loc.c] := path.getVal() + path := \path.getParent() | break + } + return puzzle + } +end + +class QMouse(puzzle, loc, parent, val) + + method getVal(); return val; end + method getLoc(); return loc; end + method getParent(); return parent; end + method atEnd(); return nCells = val; end + + method visit(r,c) + if /best & validPos(r,c) then return Pos(r,c) + end + + method validPos(r,c) + v := val+1 + xv := (0 <= puzzle[r][c]) | fail + if xv = (v|0) then { # make sure this path hasn't already gone there + ancestor := self + while xl := (ancestor := \ancestor.getParent()).getLoc() do + if (xl.r = r) & (xl.c = c) then fail + return + } + end + +initially + val := val+1 + if atEnd() then return best := self + QMouse(puzzle, visit(loc.r-2,loc.c-1), self, val) + QMouse(puzzle, visit(loc.r-2,loc.c+1), self, val) + QMouse(puzzle, visit(loc.r-1,loc.c+2), self, val) + QMouse(puzzle, visit(loc.r+1,loc.c+2), self, val) + QMouse(puzzle, visit(loc.r+2,loc.c+1), self, val) + QMouse(puzzle, visit(loc.r+2,loc.c-1), self, val) + QMouse(puzzle, visit(loc.r+1,loc.c-2), self, val) + QMouse(puzzle, visit(loc.r-1,loc.c-2), self, val) +end diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-1.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-1.j new file mode 100644 index 0000000000..7bc0a0f9ff --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-1.j @@ -0,0 +1,33 @@ +9!:21]2^34 + +unpack=:verb define + mask=. +./' '~:y + board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y +) + +ex1=:unpack ];._2]0 :0 + 0 0 0 + 0 0 0 + 0 0 0 0 0 0 0 +0 0 0 0 0 +0 0 0 0 0 +1 0 0 0 0 0 0 + 0 0 0 + 0 0 0 +) + +solve=:verb define + board=.,:y + for_move.1+i.+/({.a.)=,y do. + board=. ;move <@knight"2 board + end. +) + +kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 + +knight=:dyad define + pos=. ($y)#:(,y)i.x{a. + moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves + moves=. (#~ (0{a.)={&y) moves + moves y adverb def (':';'y x} m')"0 (x+1){a. +) diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-2.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-2.j new file mode 100644 index 0000000000..e15fa57a05 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-2.j @@ -0,0 +1,2 @@ + $~.sol +48422 8 8 diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-3.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-3.j new file mode 100644 index 0000000000..9c61a643f4 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-3.j @@ -0,0 +1,9 @@ + (a.i.{.sol){(i.255),__ +__ 11 28 13 __ __ __ __ +__ 22 __ 10 29 __ __ __ +__ 27 12 21 14 9 16 31 +23 2 25 __ __ 30 __ 8 +26 __ 20 __ __ 15 32 17 + 1 24 3 34 5 18 7 __ +__ __ 36 19 __ 33 __ __ +__ __ __ 4 35 6 __ __ diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-4.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-4.j new file mode 100644 index 0000000000..507688d927 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-4.j @@ -0,0 +1,18 @@ + (a.i.{:sol){(i.255),__ +__ 5 8 31 __ __ __ __ +__ 32 __ 6 9 __ __ __ +__ 7 4 33 30 23 10 21 + 3 34 29 __ __ 20 __ 24 +36 __ 2 __ __ 11 22 19 + 1 28 35 12 15 18 25 __ +__ __ 16 27 __ 13 __ __ +__ __ __ 14 17 26 __ __ + (a.i.24211{sol){(i.255),__ +__ 11 14 33 __ __ __ __ +__ 34 __ 10 13 __ __ __ +__ 19 12 15 32 9 6 25 +35 16 31 __ __ 24 __ 8 +18 __ 20 __ __ 7 26 5 + 1 36 17 30 27 4 23 __ +__ __ 2 21 __ 29 __ __ +__ __ __ 28 3 22 __ __ diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-5.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-5.j new file mode 100644 index 0000000000..46aca3408c --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-5.j @@ -0,0 +1,43 @@ +unpack=:verb define + mask=. +./' '~:y + board=. __ 0 1 {~ {.@:>:@:"."0 mask#"1 y +) + +ex1=:unpack ];._2]0 :0 + 0 0 0 + 0 0 0 + 0 0 0 0 0 0 0 +0 0 0 0 0 +0 0 0 0 0 +1 0 0 0 0 0 0 + 0 0 0 + 0 0 0 +) + +solve1=:verb define + (1,+/0=,y) solve1 ,:y +: + for_block._10 <\ y do. + board=. ;({.x) <@knight"2 ;block + if. #board do. + if. =/x do. + {.board return. + else. + board=. (1 0+x) solve1 board + if. #board do. + board return. + end. + end. + end. + end. + i.0 0 +) + +kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4 + +knight=:dyad define + pos=. ($y)#:(,y)i.x + moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves + moves=. (#~ 0={&y) moves + moves y adverb def (':';'y x} m')"0 x+1 +) diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-6.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-6.j new file mode 100644 index 0000000000..753ba1a035 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-6.j @@ -0,0 +1,9 @@ + solve1 ex1 +__ 11 28 13 __ __ __ __ +__ 22 __ 10 29 __ __ __ +__ 27 12 21 14 9 16 31 +23 2 25 __ __ 30 __ 8 +26 __ 20 __ __ 15 32 17 + 1 24 3 34 5 18 7 __ +__ __ 36 19 __ 33 __ __ +__ __ __ 4 35 6 __ __ diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-7.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-7.j new file mode 100644 index 0000000000..23e32ae375 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-7.j @@ -0,0 +1,15 @@ +ex2=:unpack ];._2]0 :0 + 1 0 + 0 0 + 0 0 0 0 0 + 0 0 0 + 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 + 0 0 0 + 0 0 0 0 0 + 0 0 + 0 0 +) diff --git a/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-8.j b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-8.j new file mode 100644 index 0000000000..f76d47628e --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/J/solve-a-holy-knights-tour-8.j @@ -0,0 +1,14 @@ + solve1 ex2 +__ __ __ __ __ 1 __ 5 __ __ __ __ __ +__ __ __ __ __ 6 __ 46 __ __ __ __ __ +__ __ __ __ 48 45 2 7 4 __ __ __ __ +__ __ __ __ __ 8 47 44 __ __ __ __ __ +__ __ 56 __ __ 49 __ 3 __ __ 42 __ __ +13 52 11 50 9 __ __ __ 43 38 31 36 33 +__ __ 14 55 __ __ __ __ __ 41 34 __ __ +53 12 51 10 15 __ __ __ 39 30 37 32 35 +__ __ 54 __ __ 23 __ 29 __ __ 40 __ __ +__ __ __ __ __ 16 19 22 __ __ __ __ __ +__ __ __ __ 24 21 26 17 28 __ __ __ __ +__ __ __ __ __ 18 __ 20 __ __ __ __ __ +__ __ __ __ __ 25 __ 27 __ __ __ __ __ diff --git a/Task/Solve-a-Holy-Knights-tour/Perl-6/solve-a-holy-knights-tour.pl6 b/Task/Solve-a-Holy-Knights-tour/Perl-6/solve-a-holy-knights-tour.pl6 new file mode 100644 index 0000000000..168d8d3bf8 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Perl-6/solve-a-holy-knights-tour.pl6 @@ -0,0 +1,16 @@ +my @adjacent = + [ -2, -1], [ -2, 1], + [-1,-2], [-1,+2], + [+1,-2], [+1,+2], + [ +2, -1], [ +2, 1]; + +solveboard q:to/END/; + . 0 0 0 + . 0 . 0 0 + . 0 0 0 0 0 0 0 + 0 0 0 . . 0 . 0 + 0 . 0 . . 0 0 0 + 1 0 0 0 0 0 0 + . . 0 0 . 0 + . . . 0 0 0 + END diff --git a/Task/Solve-a-Holy-Knights-tour/README b/Task/Solve-a-Holy-Knights-tour/README new file mode 100644 index 0000000000..285dbc65aa --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Solve_a_Holy_Knight's_tour diff --git a/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx b/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx new file mode 100644 index 0000000000..a9615e4ba7 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx @@ -0,0 +1,62 @@ +/*REXX pgm solves the holy knight's tour problem for a NxN chessboard.*/ +blank=pos('//',space(arg(1),0))\==0 /*see if pennies are to be shown.*/ +parse arg ops '/' cent /*obtain the options and pennies.*/ +parse var ops N sRank sFile . /*boardsize, starting pos, pennys*/ +if N=='' | N==',' then N=8 /*Boardsize specified? Default. */ +if sRank=='' then sRank=N /*starting rank given? Default. */ +if sFile=='' then sFile=1 /* " file " " */ +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*/ + /*[↑] blank the NxN chessboard.*/ +cent=space(translate(cent,,',')) /*allow use of comma (,) for sep.*/ +cents=0 /*number of pennies on chessboard*/ + do while cent\='' /* [↓] possibly place pennies. */ + parse var cent cr cf x '/' cent /*extract where to place pennies.*/ + if x='' then x=1 /*if # not specified, use 1 penny*/ + if cr='' then iterate /*support the "blanking" option. */ + do cf=cf for x /*now, place X pennies on board*/ + @.cr.cf='¢' /*mark board position with penny.*/ + end /*cf*/ /* [↑] places X pennies on board*/ + end /*while cent¬='' */ /* [↑] allows of placing X ¢s.*/ + /* [↓] traipse through the board*/ + do r=1 for N; do f=1 for N; cents=cents+(@.r.f=='¢'); end; end + /* [↑] count number of pennies. */ +if cents\==0 then say cents 'pennies placed on chessboard.' +target=NN-cents /*use this as the number of moves*/ +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 words(Kr) /*legal knight moves*/ + Kr.i = word(Kr,i); Kf.i = word(Kf,i) + end /*i*/ /*for fast indexing.*/ +!=left('', 9*(n<18)) /*used for indentation of board. */ +if @.sRank.sFile==' ' then @.sRank.sFile=1 /*knight's starting pos*/ +if @.sRank.sFile\==1 then do sRank=1 for N /*find a starting rank.*/ + do sFile=1 for N /* " " " file.*/ + if @.sRank.sFile==' ' then do /*got a spot*/ + @.sRank.sFile=1 + leave sRank + end + end /*sRank*/ + end /*sFile*/ +if \move(2,sRank,sFile) & , + \(N==1) then say "No holy knight's tour solution for" NxN'.' + else say "A solution for the holy 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*/ + if blank then L=translate(L,,'¢') /*blank out the pennies ? */ + 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*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────MOVE subroutine─────────────────────*/ +move: procedure expose @. Kr. Kf. N target; 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 #==target 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*/ +return 0 /*the tour not possible.*/ diff --git a/Task/Solve-a-Holy-Knights-tour/Racket/solve-a-holy-knights-tour.rkt b/Task/Solve-a-Holy-Knights-tour/Racket/solve-a-holy-knights-tour.rkt new file mode 100644 index 0000000000..bcc8f7dd8c --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Racket/solve-a-holy-knights-tour.rkt @@ -0,0 +1,38 @@ +#lang racket +(require "hidato-family-solver.rkt") + +(define knights-neighbour-offsets + '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1))) + +(define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets)) + +(displayln + (puzzle->string + (solve-a-knights-tour + #(#(_ 0 0 0 _ _ _ _) + #(_ 0 _ 0 0 _ _ _) + #(_ 0 0 0 0 0 0 0) + #(0 0 0 _ _ 0 _ 0) + #(0 _ 0 _ _ 0 0 0) + #(1 0 0 0 0 0 0 _) + #(_ _ 0 0 _ 0 _ _) + #(_ _ _ 0 0 0 _ _))))) + +(newline) + +(displayln + (puzzle->string + (solve-a-knights-tour + #(#(- - - - - 1 - 0 - - - - -) + #(- - - - - 0 - 0 - - - - -) + #(- - - - 0 0 0 0 0 - - - -) + #(- - - - - 0 0 0 - - - - -) + #(- - 0 - - 0 - 0 - - 0 - -) + #(0 0 0 0 0 - - - 0 0 0 0 0) + #(- - 0 0 - - - - - 0 0 - -) + #(0 0 0 0 0 - - - 0 0 0 0 0) + #(- - 0 - - 0 - 0 - - 0 - -) + #(- - - - - 0 0 0 - - - - -) + #(- - - - 0 0 0 0 0 - - - -) + #(- - - - - 0 - 0 - - - - -) + #(- - - - - 0 - 0 - - - - -))))) diff --git a/Task/Solve-a-Holy-Knights-tour/Ruby/solve-a-holy-knights-tour.rb b/Task/Solve-a-Holy-Knights-tour/Ruby/solve-a-holy-knights-tour.rb new file mode 100644 index 0000000000..3b34e59676 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Ruby/solve-a-holy-knights-tour.rb @@ -0,0 +1,17 @@ +require 'HLPsolver' + +ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] + +boardy = <=0}] + } + } + if {![info exist start]} { + return -code error "no starting position found" + } + } + method moves {} { + return { + -1 -2 1 -2 + -2 -1 2 -1 + -2 1 2 1 + -1 2 1 2 + } + } + method Moves {g r c} { + set valid {} + foreach {dr dc} [my moves] { + set R [expr {$r + $dr}] + set C [expr {$c + $dc}] + if {[lindex $g $R $C] == 0} { + lappend valid $R $C + } + } + return $valid + } + + method Solve {g r c v} { + lset g $r $c [incr v] + if {$v >= $limit} {return $g} + foreach {r c} [my Moves $g $r $c] { + return [my Solve $g $r $c $v] + } + return -code continue + } + + method solve {} { + while {[incr i]==1} { + set grid [my Solve $grid {*}$start 0] + return + } + return -code error "solution not possible" + } + method solution {} {return $grid} +} + +proc parsePuzzle {str} { + foreach line [split $str "\n"] { + if {[string trim $line] eq ""} continue + lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { + string map {" " -1} $c + }] + } + set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] + for {set i 0} {$i < [llength $rows]} {incr i} { + while {[llength [lindex $rows $i]] < $len} { + lset rows $i end+1 -1 + } + } + return $rows +} +proc showPuzzle {grid name} { + foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} + set len [string length $c] + set u [string repeat "_" $len] + puts "$name with $c cells" + foreach row $grid { + puts [format " %s" [join [lmap c $row { + format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] + }]]] + } +} + +set puzzle [parsePuzzle { + 0 0 0 + 0 0 0 + 0 0 0 0 0 0 0 +0 0 0 0 0 +0 0 0 0 0 +1 0 0 0 0 0 0 + 0 0 0 + 0 0 0 +}] +showPuzzle $puzzle "Input" +HKTSolver create hkt $puzzle +hkt solve +showPuzzle [hkt solution] "Output" diff --git a/Task/Solve-a-Hopido-puzzle/00DESCRIPTION b/Task/Solve-a-Hopido-puzzle/00DESCRIPTION new file mode 100644 index 0000000000..a7f8b03db8 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/00DESCRIPTION @@ -0,0 +1,22 @@ +Hopido puzzles are similar to [[Solve a Hidato puzzle | Hidato]]. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. [http://gamesandinnovation.com/2010/02/10/hopido-design-post-mortem/ Hopido Design Post Mortem] contains the following: + +"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" + +Knowing the kindness in the heart of every contributor to Rosetta Code I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. + +Example: + + . 0 0 . 0 0 . + 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 + . 0 0 0 0 0 . + . . 0 0 0 . . + . . . 0 . . . + +Extra credits are available for other interesting designs. + +Realated Tasks: +* [[Solve a Hidato puzzle]] +* [[Solve a Holy Knight's tour]] +* [[Solve a Numbrix puzzle]] +* [[Knight's tour]] diff --git a/Task/Solve-a-Hopido-puzzle/C++/solve-a-hopido-puzzle.cpp b/Task/Solve-a-Hopido-puzzle/C++/solve-a-hopido-puzzle.cpp new file mode 100644 index 0000000000..349db6417f --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/C++/solve-a-hopido-puzzle.cpp @@ -0,0 +1,133 @@ +#include +#include +#include +#include +#include +#include + +using namespace std; + +struct node +{ + int val; + unsigned char neighbors; +}; + +class nSolver +{ +public: + nSolver() + { + dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; + dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; + dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; + dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; + } + + void solve( vector& puzz, int max_wid ) + { + if( puzz.size() < 1 ) return; + wid = max_wid; hei = static_cast( puzz.size() ) / wid; + int len = wid * hei, c = 0; max = len; + arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); + + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } + arr[c].val = atoi( ( *i ).c_str() ); + c++; + } + + solveIt(); c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "." ) + { + ostringstream o; o << arr[c].val; + ( *i ) = o.str(); + } + c++; + } + delete [] arr; + } + +private: + bool search( int x, int y, int w ) + { + if( w > max ) return true; + + node* n = &arr[x + y * wid]; + n->neighbors = getNeighbors( x, y ); + + for( int d = 0; d < 8; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == 0 ) + { + arr[a + b * wid].val = w; + if( search( a, b, w + 1 ) ) return true; + arr[a + b * wid].val = 0; + } + } + } + return false; + } + + unsigned char getNeighbors( int x, int y ) + { + unsigned char c = 0; int a, b; + for( int xx = 0; xx < 8; xx++ ) + { + a = x + dx[xx], b = y + dy[xx]; + if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; + if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); + } + return c; + } + + void solveIt() + { + int x, y, z; findStart( x, y, z ); + if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } + search( x, y, z + 1 ); + } + + void findStart( int& x, int& y, int& z ) + { + for( int b = 0; b < hei; b++ ) + for( int a = 0; a < wid; a++ ) + if( arr[a + wid * b].val == 0 ) + { + x = a; y = b; z = 1; + arr[a + wid * b].val = z; + return; + } + } + + int wid, hei, max, dx[8], dy[8]; + node* arr; +}; + +int main( int argc, char* argv[] ) +{ + int wid; string p; + p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; + istringstream iss( p ); vector puzz; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) ); + nSolver s; s.solve( puzz, wid ); + int c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) != "*" && ( *i ) != "." ) + { + if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; + cout << ( *i ) << " "; + } + else cout << " "; + if( ++c >= wid ) { cout << endl; c = 0; } + } + cout << endl << endl; + return system( "pause" ); +} diff --git a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d new file mode 100644 index 0000000000..f1b9bdaf4a --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d @@ -0,0 +1,114 @@ +import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons; + + +struct HopidoPuzzle { + private alias InputCellBaseType = char; + private enum InputCell : InputCellBaseType { available = '#', unavailable = '.' } + private alias Cell = uint; + private enum : Cell { unknownCell = 0, unavailableCell = Cell.max } // Special Cell values. + + // Neighbors, [shift row, shift column]. + private static immutable int[2][8] shifts = [[-2, -2], [2, -2], [-2, 2], [2, 2], + [ 0, -3], [0, 3], [-3, 0], [3, 0]]; + + private immutable size_t gridWidth, gridHeight; + private immutable Cell nAvailableCells; + private /*immutable*/ const InputCell[] flatPuzzle; + private Cell[] grid; // Flattened mutable game grid. + + @disable this(); + + + this(in string[] rawPuzzle) pure @safe + in { + assert(!rawPuzzle.empty); + assert(!rawPuzzle[0].empty); + assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. + + // Has at least one start point. + assert(rawPuzzle.join.representation.canFind(InputCell.available)); + } body { + //immutable puzzle = rawPuzzle.to!(InputCell[][]); + immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); + + gridWidth = puzzle[0].length; + gridHeight = puzzle.length; + flatPuzzle = puzzle.join; + nAvailableCells = flatPuzzle.representation.count!(ic => ic == InputCell.available); + + grid = flatPuzzle + .representation + .map!(ic => ic == InputCell.available ? unknownCell : unavailableCell) + .array; + } + + + Nullable!(string[][]) solve() pure /*nothrow*/ @safe + out(result) { + if (!result.isNull) + assert(!grid.canFind(unknownCell)); + } body { + // Try all possible start positions. + foreach (immutable r; 0 .. gridHeight) { + foreach (immutable c; 0 .. gridWidth) { + immutable pos = r * gridWidth + c; + if (grid[pos] == unknownCell) { + immutable Cell startCell = 1; // To lay the first cell value. + grid[pos] = startCell; // Try. + if (search(r, c, startCell + 1)) { + auto result = zip(flatPuzzle, grid) + //.map!({p, c} => ... + .map!(pc => (pc[0] == InputCell.available) ? + pc[1].text : + InputCellBaseType(pc[0]).text) + .array + .chunks(gridWidth) + .array; + return typeof(return)(result); + } + grid[pos] = unknownCell; // Restore. + } + } + } + + return typeof(return)(); + } + + + private bool search(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { + if (cell > nAvailableCells) + return true; // One solution found. + + foreach (immutable sh; shifts) { + immutable r2 = r + sh[0], + c2 = c + sh[1], + pos = r2 * gridWidth + c2; + // No need to test for >= 0 because uint wraps around. + if (c2 < gridWidth && r2 < gridHeight && grid[pos] == unknownCell) { + grid[pos] = cell; // Try. + if (search(r2, c2, cell + 1)) + return true; + grid[pos] = unknownCell; // Restore. + } + } + + return false; + } +} + + +void main() @safe { + // enum HopidoPuzzle to catch malformed puzzles at compile-time. + enum puzzle = ".##.##. + ####### + ####### + .#####. + ..###.. + ...#...".split.HopidoPuzzle; + + immutable solution = puzzle.solve; // Solved at run-time. + if (solution.isNull) + writeln("No solution found."); + else + writefln("One solution:\n%(%-(%2s %)\n%)", solution); +} diff --git a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d new file mode 100644 index 0000000000..8b9f27784c --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d @@ -0,0 +1,98 @@ +global nCells, cMap, best +record Pos(r,c) + +procedure main(A) + puzzle := showPuzzle("Input",readPuzzle()) + QMouse(puzzle,findStart(puzzle),&null,0) + showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") +end + +procedure readPuzzle() + # Start with a reduced puzzle space + p := [[-1],[-1]] + nCells := maxCols := 0 + every line := !&input do { + put(p,[: -1 | -1 | gencells(line) | -1 | -1 :]) + maxCols <:= *p[-1] + } + every put(p, [-1]|[-1]) + # Now normalize all rows to the same length + every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] + return p +end + +procedure gencells(s) + static WS, NWS + initial { + NWS := ~(WS := " \t") + cMap := table() # Map to/from internal model + cMap["#"] := -1; cMap["_"] := 0 + cMap[-1] := " "; cMap[0] := "_" + } + + s ? while not pos(0) do { + w := (tab(many(WS))|"", tab(many(NWS))) | break + w := numeric(\cMap[w]|w) + if -1 ~= w then nCells +:= 1 + suspend w + } +end + +procedure showPuzzle(label, p) + write(label," with ",nCells," cells:") + every r := !p do { + every c := !r do writes(right((\cMap[c]|c),*nCells+1)) + write() + } + return p +end + +procedure findStart(p) + if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) +end + +procedure solvePuzzle(puzzle) + if path := \best then { + repeat { + loc := path.getLoc() + puzzle[loc.r][loc.c] := path.getVal() + path := \path.getParent() | break + } + return puzzle + } +end + +class QMouse(puzzle, loc, parent, val) + + method getVal(); return val; end + method getLoc(); return loc; end + method getParent(); return parent; end + method atEnd(); return nCells = val; end + + method visit(r,c) + if /best & validPos(r,c) then return Pos(r,c) + end + + method validPos(r,c) + v := val+1 + xv := (0 <= puzzle[r][c]) | fail + if xv = (v|0) then { # make sure this path hasn't already gone there + ancestor := self + while xl := (ancestor := \ancestor.getParent()).getLoc() do + if (xl.r = r) & (xl.c = c) then fail + return + } + end + +initially + val := val+1 + if atEnd() then return best := self + QMouse(puzzle, visit(loc.r-3,loc.c), self, val) + QMouse(puzzle, visit(loc.r-2,loc.c-2), self, val) + QMouse(puzzle, visit(loc.r, loc.c-3), self, val) + QMouse(puzzle, visit(loc.r+2,loc.c-2), self, val) + QMouse(puzzle, visit(loc.r+3,loc.c), self, val) + QMouse(puzzle, visit(loc.r+2,loc.c+2), self, val) + QMouse(puzzle, visit(loc.r, loc.c+3), self, val) + QMouse(puzzle, visit(loc.r-2,loc.c+2), self, val) +end diff --git a/Task/Solve-a-Hopido-puzzle/Perl-6/solve-a-hopido-puzzle.pl6 b/Task/Solve-a-Hopido-puzzle/Perl-6/solve-a-hopido-puzzle.pl6 new file mode 100644 index 0000000000..238f52c2f9 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Perl-6/solve-a-hopido-puzzle.pl6 @@ -0,0 +1,14 @@ +my @adjacent = [3, 0], + [2, -2], [2, 2], + [0, -3], [0, 3], + [-2, -2], [-2, 2], + [-3, 0]; + +solveboard q:to/END/; + . 0 0 . 0 0 . + 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 + . 0 0 0 0 0 . + . . 0 0 0 . . + . . . 1 . . . + END diff --git a/Task/Solve-a-Hopido-puzzle/README b/Task/Solve-a-Hopido-puzzle/README new file mode 100644 index 0000000000..a180727ef6 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Solve_a_Hopido_puzzle diff --git a/Task/Solve-a-Hopido-puzzle/REXX/solve-a-hopido-puzzle.rexx b/Task/Solve-a-Hopido-puzzle/REXX/solve-a-hopido-puzzle.rexx new file mode 100644 index 0000000000..c85870294c --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/REXX/solve-a-hopido-puzzle.rexx @@ -0,0 +1,57 @@ +/*REXX program solves a Hopido puzzle, displays puzzle and the solution.*/ +call time 'Reset' /*reset the REXX elapsed timer. */ +maxr=0; maxc=0; maxx=0; minr=9e9; minc=9e9; minx=9e9; cells=0; @.= +parse arg xxx; /*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 + if datatype(x,'N') then x=x/1 /*normalize X*/ + minr=min(minr,r); maxr=max(maxr,r) + minc=min(minc,c); maxc=max(maxc,c) + if x==1 then do; !r=r; !c=c; end /*start cell.*/ + if _\=='' then call err "cell at" r c 'is already occupied with:' _ + @.r.c=x; c=c+1; cells=cells+1 /*assign mark*/ + if x==. then iterate /*hole? Skip.*/ + if \datatype(x,'W') then call err 'illegal marker specified:' x + minx=min(minx,x); maxx=max(maxx,x) /*min & max X*/ + end /*while marks¬='' */ + end /*while xxx ¬='' */ +call showGrid /* [↓] used for making fast moves*/ +Nr = '0 3 0 -3 -2 2 2 -2' /*possible row for the next move.*/ +Nc = '3 0 -3 0 2 -2 2 -2' /* " col " " " " */ +pMoves=words(Nr) /*the number of possible moves. */ + 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 for this Hopido puzzle.' +say 'A solution for the Hopido exists.'; say; call showGrid +et=format(time('Elapsed'),,2) /*get REXX elapsed time (in secs)*/ +if et<.1 then say 'and took less than 1/10 of a second.' + else say 'and took' et "seconds." +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ERR subroutine──────────────────────*/ +err: say; say '***error!*** (from Hopido): ' arg(1); say; exit 13 +/*──────────────────────────────────NEXT subroutine─────────────────────*/ +next: procedure expose @. Nr. Nc. cells pMoves; parse arg #,r,c; ##=#+1 + do t=1 for pMoves /* [↓] try some moves.*/ + parse value r+Nr.t c+Nc.t with nr nc /*next move coördinates*/ + if @.nr.nc==. then do; @.nr.nc=# /*a move.*/ + if #==cells then leave /*last 1?*/ + if next(##,nr,nc) then return 1 + @.nr.nc=. /*undo the above move. */ + iterate /*go & try another move*/ + end + if @.nr.nc==# then do /*is this a fill-in ? */ + if #==cells then return 1 /*last 1.*/ + if next(##,nr,nc) then return 1 /*fill-in*/ + end + end /*t*/ +return 0 /*This ain't working. */ +/*──────────────────────────────────SHOWGRID subroutine─────────────────*/ +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' +w=length(cells); do r=maxr to minr by -1; _= + do c=minc to maxc; _=_ right(@.r.c,w); end /*c*/ + say _ + end /*r*/ +say; return diff --git a/Task/Solve-a-Hopido-puzzle/Racket/solve-a-hopido-puzzle.rkt b/Task/Solve-a-Hopido-puzzle/Racket/solve-a-hopido-puzzle.rkt new file mode 100644 index 0000000000..d2c91d4c40 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Racket/solve-a-hopido-puzzle.rkt @@ -0,0 +1,17 @@ +#lang racket +(require "hidato-family-solver.rkt") + +(define hoppy-moore-neighbour-offsets + '((+3 0) (-3 0) (0 +3) (0 -3) (+2 +2) (-2 -2) (-2 +2) (+2 -2))) + +(define solve-hopido (solve-hidato-family hoppy-moore-neighbour-offsets)) + +(displayln + (puzzle->string + (solve-hopido + #(#(_ 0 0 _ 0 0 _) + #(0 0 0 0 0 0 0) + #(0 0 0 0 0 0 0) + #(_ 0 0 0 0 0 _) + #(_ _ 0 0 0 _ _) + #(_ _ _ 0 _ _ _))))) diff --git a/Task/Solve-a-Hopido-puzzle/Ruby/solve-a-hopido-puzzle.rb b/Task/Solve-a-Hopido-puzzle/Ruby/solve-a-hopido-puzzle.rb new file mode 100644 index 0000000000..ceba5680f4 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Ruby/solve-a-hopido-puzzle.rb @@ -0,0 +1,15 @@ +require 'HLPsolver' + +ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]] + +board1 = <=0}] + } + } + if {![info exist start]} { + return -code error "no starting position found" + } + } + method moves {} { + return { + 0 -3 + -2 -2 -2 2 + -3 0 3 0 + -2 2 2 2 + 0 3 + } + } + method Moves {g r c} { + set valid {} + foreach {dr dc} [my moves] { + set R [expr {$r + $dr}] + set C [expr {$c + $dc}] + if {[lindex $g $R $C] == 0} { + lappend valid $R $C + } + } + return $valid + } + + method Solve {g r c v} { + lset g $r $c [incr v] + if {$v >= $limit} {return $g} + foreach {r c} [my Moves $g $r $c] { + return [my Solve $g $r $c $v] + } + return -code continue + } + + method solve {} { + while {[incr i]==1} { + set grid [my Solve $grid {*}$start 0] + return + } + return -code error "solution not possible" + } + method solution {} {return $grid} +} + +proc parsePuzzle {str} { + foreach line [split $str "\n"] { + if {[string trim $line] eq ""} continue + lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] { + string map {" " -1 "." -1} $c + }] + } + set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]] + for {set i 0} {$i < [llength $rows]} {incr i} { + while {[llength [lindex $rows $i]] < $len} { + lset rows $i end+1 -1 + } + } + return $rows +} +proc showPuzzle {grid name} { + foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}} + set len [string length $c] + set u [string repeat "_" $len] + puts "$name with $c cells" + foreach row $grid { + puts [format " %s" [join [lmap c $row { + format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}] + }]]] + } +} +set puzzle [parsePuzzle { +. 0 0 . 0 0 . +0 0 0 0 0 0 0 +0 0 0 0 0 0 0 +. 0 0 0 0 0 . +. . 0 0 0 . . +. . . 1 . . . +}] +showPuzzle $puzzle "Input" +HopidoSolver create hop $puzzle +hop solve +showPuzzle [hop solution] "Output" diff --git a/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION b/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION new file mode 100644 index 0000000000..30ce54d3fd --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION @@ -0,0 +1,65 @@ +Numbrix puzzles are similar to [[Solve a Hidato puzzle|Hidato]]. +The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the [[wp:Von Neumann neighborhood|Von Neumann neighborhood]]). +Published puzzles also tend not to have holes in the grid and may not always indicate the end node. +Two examples follow: + +;Example 1 +Problem. +
+ 0  0  0  0  0  0  0  0  0
+ 0  0 46 45  0 55 74  0  0
+ 0 38  0  0 43  0  0 78  0
+ 0 35  0  0  0  0  0 71  0
+ 0  0 33  0  0  0 59  0  0
+ 0 17  0  0  0  0  0 67  0
+ 0 18  0  0 11  0  0 64  0
+ 0  0 24 21  0  1  2  0  0
+ 0  0  0  0  0  0  0  0  0
+
+Solution. +
+ 49 50 51 52 53 54 75 76 81
+ 48 47 46 45 44 55 74 77 80
+ 37 38 39 40 43 56 73 78 79
+ 36 35 34 41 42 57 72 71 70
+ 31 32 33 14 13 58 59 68 69
+ 30 17 16 15 12 61 60 67 66
+ 29 18 19 20 11 62 63 64 65
+ 28 25 24 21 10  1  2  3  4
+ 27 26 23 22  9  8  7  6  5
+
+;Example 2 +Problem. +
+ 0  0  0  0  0  0  0  0  0
+ 0 11 12 15 18 21 62 61  0
+ 0  6  0  0  0  0  0 60  0
+ 0 33  0  0  0  0  0 57  0
+ 0 32  0  0  0  0  0 56  0
+ 0 37  0  1  0  0  0 73  0
+ 0 38  0  0  0  0  0 72  0
+ 0 43 44 47 48 51 76 77  0
+ 0  0  0  0  0  0  0  0  0
+
+Solution. +
+  9 10 13 14 19 20 63 64 65
+  8 11 12 15 18 21 62 61 66
+  7  6  5 16 17 22 59 60 67
+ 34 33  4  3 24 23 58 57 68
+ 35 32 31  2 25 54 55 56 69
+ 36 37 30  1 26 53 74 73 70
+ 39 38 29 28 27 52 75 72 71
+ 40 43 44 47 48 51 76 77 78
+ 41 42 45 46 49 50 81 80 79
+
+;Task +Write a program to solve puzzles of this ilk, +demonstrating your program by solving the above examples. +Extra credit for other interesting examples. + +Related Tasks: +* [[Solve a Hidato puzzle]] +* [[Solve a Holy Knight's tour]] +* [[Solve a Hopido puzzle]] +* [[Knight's tour]] diff --git a/Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp b/Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp new file mode 100644 index 0000000000..17ed017ee4 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp @@ -0,0 +1,155 @@ +#include +#include +#include +#include +#include +#include + + +using namespace std; + +struct node +{ + int val; + unsigned char neighbors; +}; + +class nSolver +{ +public: + nSolver() + { + dx[0] = -1; dy[0] = 0; dx[1] = 1; dy[1] = 0; + dx[2] = 0; dy[2] = -1; dx[3] = 0; dy[3] = 1; + } + + void solve( vector& puzz, int max_wid ) + { + if( puzz.size() < 1 ) return; + wid = max_wid; hei = static_cast( puzz.size() ) / wid; + int len = wid * hei, c = 0; max = len; + arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); + weHave = new bool[len + 1]; memset( weHave, 0, len + 1 ); + + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } + arr[c].val = atoi( ( *i ).c_str() ); + if( arr[c].val > 0 ) weHave[arr[c].val] = true; + c++; + } + + solveIt(); c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "." ) + { + ostringstream o; o << arr[c].val; + ( *i ) = o.str(); + } + c++; + } + delete [] arr; + delete [] weHave; + } + +private: + bool search( int x, int y, int w, int dr ) + { + if( ( w > max && dr > 0 ) || ( w < 1 && dr < 0 ) || ( w == max && weHave[w] ) ) return true; + + node* n = &arr[x + y * wid]; + n->neighbors = getNeighbors( x, y ); + if( weHave[w] ) + { + for( int d = 0; d < 4; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == w ) + if( search( a, b, w + dr, dr ) ) return true; + } + } + return false; + } + + for( int d = 0; d < 4; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == 0 ) + { + arr[a + b * wid].val = w; + if( search( a, b, w + dr, dr ) ) return true; + arr[a + b * wid].val = 0; + } + } + } + return false; + } + + unsigned char getNeighbors( int x, int y ) + { + unsigned char c = 0; int a, b; + for( int xx = 0; xx < 4; xx++ ) + { + a = x + dx[xx], b = y + dy[xx]; + if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; + if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); + } + return c; + } + + void solveIt() + { + int x, y, z; findStart( x, y, z ); + if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } + search( x, y, z + 1, 1 ); + if( z > 1 ) search( x, y, z - 1, -1 ); + } + + void findStart( int& x, int& y, int& z ) + { + z = 99999; + for( int b = 0; b < hei; b++ ) + for( int a = 0; a < wid; a++ ) + if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) + { + x = a; y = b; + z = arr[a + wid * b].val; + } + + } + + int wid, hei, max, dx[4], dy[4]; + node* arr; + bool* weHave; +}; +//------------------------------------------------------------------------------ +int main( int argc, char* argv[] ) +{ + int wid; string p; + //p = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . ."; wid = 9; + //p = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . ."; wid = 9; + p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; + + istringstream iss( p ); vector puzz; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) ); + nSolver s; s.solve( puzz, wid ); + + int c = 0; + for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) != "*" && ( *i ) != "." ) + { + if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; + cout << ( *i ) << " "; + } + else cout << " "; + if( ++c >= wid ) { cout << endl; c = 0; } + } + cout << endl << endl; + return system( "pause" ); +} diff --git a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d new file mode 100644 index 0000000000..473a5bd2fd --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d @@ -0,0 +1,209 @@ +import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm; + +struct { + alias BitSet8 = ubyte; // A set of 8 bits. + alias Cell = uint; + enum : string { unavailableInCell = "#", availableInCell = "." } + enum : Cell { unavailableCell = Cell.max, availableCell = 0 } + + this(in string inPuzzle) pure @safe { + const rawPuzzle = inPuzzle.splitLines.map!(row => row.split).array; + assert(!rawPuzzle.empty); + assert(!rawPuzzle[0].empty); + assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. + + gridWidth = rawPuzzle[0].length; + gridHeight = rawPuzzle.length; + immutable nMaxCells = gridWidth * gridHeight; + grid = new Cell[nMaxCells]; + auto knownMutable = new bool[nMaxCells + 1]; + uint nAvailableMutable = nMaxCells; + bool[Cell] seenCells; // To avoid duplicate input numbers. + + uint i = 0; + foreach (const piece; rawPuzzle.join) { + if (piece == unavailableInCell) { + nAvailableMutable--; + grid[i++] = unavailableCell; + continue; + } else if (piece == availableInCell) { + grid[i] = availableCell; + } else { + immutable cell = piece.to!Cell; + assert(cell > 0 && cell <= nMaxCells); + assert(cell !in seenCells); + seenCells[cell] = true; + knownMutable[cell] = true; + grid[i] = cell; + } + + i++; + } + + known = knownMutable.idup; + nAvailable = nAvailableMutable; + } + + @disable this(); + + + auto solve() pure nothrow @safe @nogc + out(result) { + if (!result.isNull) { + // Can't verify 'result' here because it's const. + // assert(!result.get.join.canFind(availableCell.text)); + + assert(!grid.canFind(availableCell)); + auto values = grid.filter!(c => c != unavailableCell); + auto interval = iota(reduce!min(values.front, values.dropOne), + reduce!max(values.front, values.dropOne) + 1); + assert(values.walkLength == interval.length); + assert(interval.all!(c => values.count(c) == 1)); // Quadratic. + } + } body { + auto result = grid + .map!(c => (c == unavailableCell) ? unavailableInCell : c.text) + .chunks(gridWidth); + alias OutRange = Nullable!(typeof(result)); + + const start = findStart; + if (start.isNull) + return OutRange(); + + search(start.r, start.c, start.cell + 1, 1); + if (start.cell > 1) { + immutable direction = -1; + search(start.r, start.c, start.cell + direction, direction); + } + + if (grid.any!(c => c == availableCell)) + return OutRange(); + else + return OutRange(result); + } + + private: + + + bool search(in uint r, in uint c, in Cell cell, in int direction) + pure nothrow @safe @nogc { + if ((cell > nAvailable && direction > 0) || (cell == 0 && direction < 0) || + (cell == nAvailable && known[cell])) + return true; // One solution found. + + immutable neighbors = getNeighbors(r, c); + + if (known[cell]) { + foreach (immutable i, immutable rc; shifts) { + if (neighbors & (1u << i)) { + immutable c2 = c + rc[0], + r2 = r + rc[1]; + if (grid[r2 * gridWidth + c2] == cell) + if (search(r2, c2, cell + direction, direction)) + return true; + } + } + return false; + } + + foreach (immutable i, immutable rc; shifts) { + if (neighbors & (1u << i)) { + immutable c2 = c + rc[0], + r2 = r + rc[1], + pos = r2 * gridWidth + c2; + if (grid[pos] == availableCell) { + grid[pos] = cell; // Try. + if (search(r2, c2, cell + direction, direction)) + return true; + grid[pos] = availableCell; // Restore. + } + } + } + return false; + } + + + BitSet8 getNeighbors(in uint r, in uint c) const pure nothrow @safe @nogc { + typeof(return) usable = 0; + + foreach (immutable i, immutable rc; shifts) { + immutable c2 = c + rc[0], + r2 = r + rc[1]; + if (c2 >= gridWidth || r2 >= gridHeight) + continue; + if (grid[r2 * gridWidth + c2] != unavailableCell) + usable |= (1u << i); + } + + return usable; + } + + + auto findStart() const pure nothrow @safe @nogc { + alias Triple = Tuple!(uint,"r", uint,"c", Cell,"cell"); + Nullable!Triple result; + + auto cell = Cell.max; + foreach (immutable r; 0 .. gridHeight) { + foreach (immutable c; 0 .. gridWidth) { + immutable pos = gridWidth * r + c; + if (grid[pos] != availableCell && + grid[pos] != unavailableCell && grid[pos] < cell) { + cell = grid[pos]; + result = Triple(r, c, cell); + } + } + } + + return result; + } + + static immutable int[2][4] shifts = [[0, -1], [0, 1], [-1, 0], [1, 0]]; + immutable uint gridWidth, gridHeight; + immutable int nAvailable; + immutable bool[] known; // Given known cells of the puzzle. + Cell[] grid; // Flattened mutable game grid. +} + + +void main() { + // enum NumbrixPuzzle to catch malformed puzzles at compile-time. + enum puzzle1 = ". . . . . . . . . + . . 46 45 . 55 74 . . + . 38 . . 43 . . 78 . + . 35 . . . . . 71 . + . . 33 . . . 59 . . + . 17 . . . . . 67 . + . 18 . . 11 . . 64 . + . . 24 21 . 1 2 . . + . . . . . . . . .".NumbrixPuzzle; + + enum puzzle2 = ". . . . . . . . . + . 11 12 15 18 21 62 61 . + . 6 . . . . . 60 . + . 33 . . . . . 57 . + . 32 . . . . . 56 . + . 37 . 1 . . . 73 . + . 38 . . . . . 72 . + . 43 44 47 48 51 76 77 . + . . . . . . . . .".NumbrixPuzzle; + + enum puzzle3 = "17 . . . 11 . . . 59 + . 15 . . 6 . . 61 . + . . 3 . . . 63 . . + . . . . 66 . . . . + 23 24 . 68 67 78 . 54 55 + . . . . 72 . . . . + . . 35 . . . 49 . . + . 29 . . 40 . . 47 . + 31 . . . 39 . . . 45".NumbrixPuzzle; + + + foreach (puzzle; [puzzle1, puzzle2, puzzle3]) { + auto solution = puzzle.solve; // Solved at run-time. + if (solution.isNull) + writeln("No solution found for puzzle.\n"); + else + writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); + } +} diff --git a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d new file mode 100644 index 0000000000..c2e2906849 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d @@ -0,0 +1,90 @@ +global nCells, cMap, best +record Pos(r,c) + +procedure main(A) + puzzle := showPuzzle("Input",readPuzzle()) + QMouse(puzzle,findStart(puzzle),&null,0) + showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") +end + +procedure readPuzzle() + # Start with a reduced puzzle space + p := [] + nCells := maxCols := 0 + every line := !&input do { + put(p,[: gencells(line) :]) + maxCols <:= *p[-1] + } + # Now normalize all rows to the same length + every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] + return p +end + +procedure gencells(s) + static WS, NWS + initial { + NWS := ~(WS := " \t") + cMap := table() # Map to/from internal model + cMap["_"] := 0; cMap[0] := "_" + } + + s ? while not pos(0) do { + w := (tab(many(WS))|"", tab(many(NWS))) | break + w := numeric(\cMap[w]|w) + if -1 ~= w then nCells +:= 1 + suspend w + } +end + +procedure showPuzzle(label, p) + write(label," with ",nCells," cells:") + every r := !p do { + every c := !r do writes(right((\cMap[c]|c),*nCells+1)) + write() + } + return p +end + +procedure findStart(p) + if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) +end + +procedure solvePuzzle(puzzle) + if path := \best then { + repeat { + loc := path.getLoc() + puzzle[loc.r][loc.c] := path.getVal() + path := \path.getParent() | break + } + return puzzle + } +end + +class QMouse(puzzle, loc, parent, val) + + method getVal(); return val; end + method getLoc(); return loc; end + method getParent(); return parent; end + method atEnd(); return (nCells = val, puzzle[loc.r,loc.c] = (val|0)); end + method visit(r,c); return (/best, validPos(r,c), Pos(r,c)); end + + method validPos(r,c) + v := val+1 # number we're looking for + xv := puzzle[r,c] | fail + if (xv ~= 0) & (xv != v) then fail + if xv = (0|v) then { + ancestor := self + while xl := (ancestor := \ancestor.getParent()).getLoc() do + if (xl.r = r) & (xl.c = c) then fail + return + } + end + +initially + val := val+1 + if atEnd() then return best := self + QMouse(puzzle, visit(loc.r-1,loc.c) , self, val) # North + QMouse(puzzle, visit(loc.r, loc.c+1), self, val) # East + QMouse(puzzle, visit(loc.r+1,loc.c), self, val) # South + QMouse(puzzle, visit(loc.r, loc.c-1), self, val) # West +end diff --git a/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-1.pl6 b/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-1.pl6 new file mode 100644 index 0000000000..b32c8219c7 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-1.pl6 @@ -0,0 +1,15 @@ +my @adjacent = [-1, 0], + [ 0, -1], [ 0, 1], + [ 1, 0]; + +solveboard q:to/END/; + __ __ __ __ __ __ __ __ __ + __ __ 46 45 __ 55 74 __ __ + __ 38 __ __ 43 __ __ 78 __ + __ 35 __ __ __ __ __ 71 __ + __ __ 33 __ __ __ 59 __ __ + __ 17 __ __ __ __ __ 67 __ + __ 18 __ __ 11 __ __ 64 __ + __ __ 24 21 __ 1 2 __ __ + __ __ __ __ __ __ __ __ __ + END diff --git a/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-2.pl6 b/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-2.pl6 new file mode 100644 index 0000000000..d90e4463d6 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle-2.pl6 @@ -0,0 +1,11 @@ +solveboard q:to/END/; + 0 0 0 0 0 0 0 0 0 + 0 11 12 15 18 21 62 61 0 + 0 6 0 0 0 0 0 60 0 + 0 33 0 0 0 0 0 57 0 + 0 32 0 0 0 0 0 56 0 + 0 37 0 1 0 0 0 73 0 + 0 38 0 0 0 0 0 72 0 + 0 43 44 47 48 51 76 77 0 + 0 0 0 0 0 0 0 0 0 +END diff --git a/Task/Solve-a-Numbrix-puzzle/README b/Task/Solve-a-Numbrix-puzzle/README new file mode 100644 index 0000000000..52c8c32b63 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle diff --git a/Task/Solve-a-Numbrix-puzzle/REXX/solve-a-numbrix-puzzle.rexx b/Task/Solve-a-Numbrix-puzzle/REXX/solve-a-numbrix-puzzle.rexx new file mode 100644 index 0000000000..bedd38c55a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/REXX/solve-a-numbrix-puzzle.rexx @@ -0,0 +1,53 @@ +/*REXX program solves a Numbrix (R) puzzle, displays puzzle & solution.*/ +maxr=0; maxc=0; maxx=0; minr=9e9; minc=9e9; minx=9e9; cells=0; @.= +parse arg xxx; PZ='Numbrix 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 + if datatype(x,'N') then x=abs(x/1) /*normalize X*/ + minr=min(minr,r); maxr=max(maxr,r) + minc=min(minc,c); maxc=max(maxc,c) + if x==1 then do; !r=r; !c=c; end /*start cell.*/ + if _\=='' then call err "cell at" r c 'is already occupied with:' _ + @.r.c=x; c=c+1; cells=cells+1 /*assign mark*/ + if x==. then iterate /*hole? Skip.*/ + if \datatype(x,'W') then call err 'illegal marker specified:' x + minx=min(minx,x); maxx=max(maxx,x) /*min & max X*/ + end /*while marks¬='' */ + end /*while xxx ¬='' */ +call showGrid /* [↓] used for making fast moves*/ +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 for this' PZ"." +say; 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 +/*──────────────────────────────────NEXT subroutine─────────────────────*/ +next: procedure expose @. Nr. Nc. cells pMoves; parse arg #,r,c; ##=#+1 + do t=1 for pMoves /* [↓] try some moves.*/ + parse value r+Nr.t c+Nc.t with nr nc /*next move coördinates*/ + if @.nr.nc==. then do; @.nr.nc=# /*a move.*/ + if #==cells then return 1 /*last 1?*/ + if next(##,nr,nc) then return 1 + @.nr.nc=. /*undo the above move. */ + iterate /*go & try another move*/ + end + if @.nr.nc==# then do /*is this a fill-in ? */ + if #==cells then return 1 /*last 1.*/ + if next(##,nr,nc) then return 1 /*fill-in*/ + end + end /*t*/ +return 0 /*This ain't working. */ +/*──────────────────────────────────SHOWGRID subroutine─────────────────*/ +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' +w=length(cells); do r=maxr to minr by -1; _= + do c=minc to maxc; _=_ right(@.r.c,w); end /*c*/ + say _ + end /*r*/ +say; return diff --git a/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-1.rkt b/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-1.rkt new file mode 100644 index 0000000000..e9a03b76cf --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-1.rkt @@ -0,0 +1,95 @@ +#lang racket +;;; Used in my solutions of: +;;; "Solve a Hidato Puzzle" +;;; "Solve a Holy Knights Tour" +;;; "Solve a Numbrix Puzzle" +;;; "Solve a Hopido Puzzle" + +;;; As well as the solver being common, the solution renderer and input formats are common +(provide + ;; Input: list of neighbour offsets + ;; Output: a solver function: + ;; Input: a puzzle + ;; Output: either the solved puzzle or #f if impossible + solve-hidato-family + ;; Input: puzzle + ;; optional minimum cell width + ;; Output: a pretty string that can be printed + puzzle->string) + +;; Cell values are: +;; zero? - unvisited +;; positive? - nth visitied +;; else - unvisitable. In the puzzle layout, it's a _. In the hash it's a -1, so we can care less +;; about number type checking. +;; A puzzle is a sequence of sequences of cell values +;; We work with a puzzle as a hash keyed on (cons row-num col-num) + +;; Take a puzzle and get a working hash of it +(define (puzzle->hash p) + (for*/hash + (((r row-num) (in-parallel p (in-naturals))) + ((v col-num) (in-parallel r (in-naturals))) + #:when (integer? v)) + (values (cons row-num col-num) v))) + +;; Takes a hash and recreates a vector of vectors puzzle +(define (hash->puzzle h# (blank '_)) + (define keys (hash-keys h#)) + (define n-rows (add1 (car (argmax car keys)))) + (define n-cols (add1 (cdr (argmax cdr keys)))) + (for/vector #:length n-rows ((r n-rows)) + (for/vector #:length n-cols ((c n-cols)) + (hash-ref h# (cons r c) blank)))) + +;; See "provide" section for description +(define (puzzle->string p (w #f)) + (match p + [#f "unsolved"] + [(? sequence? s) + (define (max-n-digits p) + (and p (add1 (order-of-magnitude (* (vector-length p) (vector-length (vector-ref p 0))))))) + (define min-width (or w (max-n-digits p))) + (string-join + (for/list ((r s)) + (string-join + (for/list ((c r)) (~a c #:align 'right #:min-width min-width)) + " ")) + "\n")])) + +(define ((solve-hidato-family neighbour-offsets) board) + (define board# (puzzle->hash board)) + ;; reverse mapping, will only take note of positive values + (define targets# (for/hash ([(k v) (in-hash board#)] #:when (positive? v)) (values v k))) + + (define (neighbours r.c) + (for/list ((r+.c+ neighbour-offsets)) + (match-define (list r+ c+) r+.c+) + (match-define (cons r c ) r.c) + (cons (+ r r+) (+ c c+)))) + + ;; Count the moves, rather than check for "no more zeros" in puzzle + (define last-move (length (filter number? (hash-values board#)))) + + ;; Depth first solution of the puzzle (we have to go deep, it's where the solutions are! + (define (inr-solve-pzl b# move r.c) + (cond + [(= move last-move) b#] ; no moves needed, so solved + [else + (define m++ (add1 move)) + (for*/or ; check each neighbour as an option + ((r.c+ (in-list (neighbours r.c))) + #:when (equal? (hash-ref targets# move r.c) r.c) ; we're where we should be! + #:when (match (hash-ref b# r.c+ -1) (0 #t) ((== m++) #t) (_ #f))) + (inr-solve-pzl (hash-set b# r.c+ m++) m++ r.c+))])) + + (define (solution-starting-at n) + (define start-r.c (for/first (((k v) (in-hash board#)) #:when (= n v)) k)) + (and start-r.c (inr-solve-pzl board# n start-r.c))) + + (define sltn + (cond [(solution-starting-at 1) => values] + ;; next clause starts from 0 for hopido + [(solution-starting-at 0) => values])) + + (and sltn (hash->puzzle sltn))) diff --git a/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-2.rkt b/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-2.rkt new file mode 100644 index 0000000000..a8d6bb6c7f --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Racket/solve-a-numbrix-puzzle-2.rkt @@ -0,0 +1,35 @@ +#lang racket +(require "hidato-family-solver.rkt") + +(define von-neumann-neighbour-offsets + '((+1 0) (-1 0) (0 +1) (0 -1))) + +(define solve-numbrix (solve-hidato-family von-neumann-neighbour-offsets)) + +(displayln + (puzzle->string + (solve-numbrix + #(#(0 0 0 0 0 0 0 0 0) + #(0 0 46 45 0 55 74 0 0) + #(0 38 0 0 43 0 0 78 0) + #(0 35 0 0 0 0 0 71 0) + #(0 0 33 0 0 0 59 0 0) + #(0 17 0 0 0 0 0 67 0) + #(0 18 0 0 11 0 0 64 0) + #(0 0 24 21 0 1 2 0 0) + #(0 0 0 0 0 0 0 0 0))))) + +(newline) + +(displayln + (puzzle->string + (solve-numbrix + #(#(0 0 0 0 0 0 0 0 0) + #(0 11 12 15 18 21 62 61 0) + #(0 6 0 0 0 0 0 60 0) + #(0 33 0 0 0 0 0 57 0) + #(0 32 0 0 0 0 0 56 0) + #(0 37 0 1 0 0 0 73 0) + #(0 38 0 0 0 0 0 72 0) + #(0 43 44 47 48 51 76 77 0) + #(0 0 0 0 0 0 0 0 0))))) diff --git a/Task/Solve-a-Numbrix-puzzle/Ruby/solve-a-numbrix-puzzle.rb b/Task/Solve-a-Numbrix-puzzle/Ruby/solve-a-numbrix-puzzle.rb new file mode 100644 index 0000000000..22125bfb10 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Ruby/solve-a-numbrix-puzzle.rb @@ -0,0 +1,29 @@ +require 'HLPsolver' + +ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]] + +board1 = < 8, Object_Size => 8, Pack; + + Function "&"( Left : Connection_List; Right : Node ) return Connection_List; + + -- The actual map of the network connections. + Network : Constant Array (Node) of Connection_List:= + ( + A => (C|D|E => True, others => False), + B => (D|E|F => True, others => False), + C => (A|D|G => True, others => False), + D => (C|A|B|E|H|G => True, others => False), + E => (D|A|B|F|H|G => True, others => False), + F => (B|E|H => True, others => False), + G => (C|D|E => True, others => False), + H => (D|E|F => True, others => False) + ); + + -- Values of the nodes. + Type Peg is range 1..8; + + -- Indicator for which values have been assigned. + Type Used_Peg is array(Peg) of Boolean + with Size => 8, Object_Size => 8, Pack; + + Function "&"( Left : Used_Peg; Right : Peg ) return Used_Peg; + + + -- Type describing the layout of the network. + Type Partial_Board is array(Node range <>) of Peg; + Subtype Board is Partial_Board(Node); + + -- Determines if the given board is a solution or partial-solution. + Function Is_Solution ( Input : Partial_Board ) return Boolean; + + -- Displays the board as text. + Function Image ( Input : Partial_Board ) Return String; + +End Connection_Types; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada new file mode 100644 index 0000000000..50128f6547 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada @@ -0,0 +1,6 @@ +Pragma Ada_2012; + +with Connection_Types; +use Connection_Types; + +Function Connection_Combinations return Partial_Board; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada new file mode 100644 index 0000000000..97c698b187 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada @@ -0,0 +1,73 @@ +Pragma Ada_2012; + +Package Body Connection_Types is + + New_Line : Constant String := ASCII.CR & ASCII.LF; + + --------------------- + -- Solution Test -- + --------------------- + + Function Is_Solution( Input : Partial_Board ) return Boolean is + (for all Index in Input'Range => + (for all Connection in Node'Range => + (if Network(Index)(Connection) and Connection in Input'Range + then abs (Input(Index) - Input(Connection)) > 1 + ) + ) + ); + + ------------------------ + -- Concat Operators -- + ------------------------ + + Function "&"( Left : Used_Peg; Right : Peg ) return Used_Peg is + begin + return Result : Used_Peg := Left do + Result(Right):= True; + end return; + end "&"; + + Function "&"(Left : Connection_List; Right : Node) return Connection_List is + begin + Return Result : Connection_List := Left do + Result(Right):= True; + end return; + end "&"; + + ----------------------- + -- IMAGE FUNCTIONS -- + ----------------------- + + Function Image(Input : Peg) Return Character is + ( Peg'Image(Input)(2) ); + + Function Image(Input : Peg) Return String is + ( 1 => Image(Input) ); + + Function Image(Input : Partial_Board; Item : Node) Return String is + ( 1 => (if Item not in Input'Range then '*' else Image(Input(Item)) )); + + Function Image( Input : Partial_Board ) Return String is + A : String renames Image(Input, Connection_Types.A); + B : String renames Image(Input, Connection_Types.B); + C : String renames Image(Input, Connection_Types.C); + D : String renames Image(Input, Connection_Types.D); + E : String renames Image(Input, Connection_Types.E); + F : String renames Image(Input, Connection_Types.F); + G : String renames Image(Input, Connection_Types.G); + H : String renames Image(Input, Connection_Types.H); + begin + return + " "&A&" "&B & New_Line & + " /|\ /|\" & New_Line & + " / | X | \" & New_Line & + " / |/ \| \" & New_Line & + " "&C&" - "&D&" - "&E&" - "&F & New_Line & + " \ |\ /| /" & New_Line & + " \ | X | /" & New_Line & + " \|/ \|/" & New_Line & + " "&G&" "&H & New_Line; + end Image; + +End Connection_Types; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada new file mode 100644 index 0000000000..2454f29c06 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada @@ -0,0 +1,73 @@ +Function Connection_Combinations return Partial_Board is + +begin + Return Result : Board do + declare + + -- The Generate task takes two parameters + -- (1) a list of pegs already in use, and + -- (2) a partial-board + -- and, if the state given is a viable yet incomplete solution, it + -- takes a peg and adds it to the state creating a new task with + -- that peg in its used list. + -- + -- When a complete solution is found it is copied into result. + task type Generate( + Pegs : not null access Used_Peg:= new Used_Peg'(others => False); + State : not null access Partial_Board:= new Partial_Board'(Node'Last..Node'First => <>) + ) is + end Generate; + + -- An access to Generate and array thereof, for creating the + -- children tasks. + type Generator is access all Generate; + type Generators is array(Peg range <>) of Generator; + + -- Gen handles the actual creation of a new task and state. + Function Gen(P : Peg; G : not null access Generate) return Generator is + begin + return (if G.Pegs(P) then null + else new Generate( + Pegs => new Used_Peg'(G.Pegs.all & P), + State => New Partial_Board'(G.All.State.All & P) + ) + ); + end; + + task body Generate is + begin + if Is_Solution(State.All) then + -- If the state is a partial board, we make children to + -- complete the calculations. + if State'Length <= Node'Pos(Node'Last) then + declare + Subtasks : Constant Generators:= + ( + Gen(1, Generate'Access), + Gen(2, Generate'Access), + Gen(3, Generate'Access), + Gen(4, Generate'Access), + Gen(5, Generate'Access), + Gen(6, Generate'Access), + Gen(7, Generate'Access), + Gen(8, Generate'Access) + ); + begin + null; + end; + else + Result:= State.All; + end if; + else + -- The current state is not a solution, so we do not continue it. + Null; + end if; + + end Generate; + + Master : Generate; + begin + null; + end; + End return; +End Connection_Combinations; diff --git a/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-1.d b/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-1.d new file mode 100644 index 0000000000..7e742a1c96 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-1.d @@ -0,0 +1,27 @@ +void main() @safe { + import std.stdio, std.math, std.algorithm, std.traits, std.string; + + enum Peg { A, B, C, D, E, F, G, H } + immutable Peg[2][15] connections = + [[Peg.A, Peg.C], [Peg.A, Peg.D], [Peg.A, Peg.E], + [Peg.B, Peg.D], [Peg.B, Peg.E], [Peg.B, Peg.F], + [Peg.C, Peg.D], [Peg.D, Peg.E], [Peg.E, Peg.F], + [Peg.G, Peg.C], [Peg.G, Peg.D], [Peg.G, Peg.E], + [Peg.H, Peg.D], [Peg.H, Peg.E], [Peg.H, Peg.F]]; + + immutable board = r" + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H"; + + Peg[EnumMembers!Peg.length] perm = [EnumMembers!Peg]; + do if (connections[].all!(con => abs(perm[con[0]] - perm[con[1]]) > 1)) + return board.tr("ABCDEFGH", "%(%d%)".format(perm)).writeln; + while (perm[].nextPermutation); +} diff --git a/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-2.d b/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-2.d new file mode 100644 index 0000000000..05a78d3489 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/D/solve-the-no-connection-puzzle-2.d @@ -0,0 +1,65 @@ +import std.stdio, std.algorithm, std.conv, std.string, std.typecons; + +// Holes A=0, B=1, ..., H=7 +// With connections: +const board = r" + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H"; + +struct Connection { uint a, b; } + +immutable Connection[] connections = [ + {0, 2}, {0, 3}, {0, 4}, // A to C,D,E + {1, 3}, {1, 4}, {1, 5}, // B to D,E,F + {6, 2}, {6, 3}, {6, 4}, // G to C,D,E + {7, 3}, {7, 4}, {7, 5}, // H to D,E,F + {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F +]; + +alias Pegs = uint[8]; + +int absDiff(in uint a, in uint b) pure nothrow @safe @nogc { + return (a > b) ? (a - b) : (b - a); +} + +/** Solution is a simple recursive brute force solver, +it stops at the first found solution. +It returns the solution, the number of positions tested, +and the number of pegs swapped. */ +Tuple!(Pegs,"p", uint,"tests", uint,"swaps") solve() pure nothrow @safe @nogc { + uint tests = 0, swaps = 0; + Pegs p = [1, 2, 3, 4, 5, 6, 7, 8]; + + bool recurse(in uint i) nothrow @safe @nogc { + if (i >= p.length.signed - 1) { + tests++; + return connections.all!(c => absDiff(p[c.a], p[c.b]) > 1); + } + + // Try each remain peg from. + foreach (immutable j; i .. p.length) { + swaps++; + swap(p[i], p[j]); + if (recurse(i + 1)) + return true; + swap(p[i], p[j]); + } + return false; + } + + recurse(0); + return typeof(return)(p, tests, swaps); +} + +void main() { + immutable sol = solve(); + board.tr("ABCDEFGH", "%(%d%)".format(sol.p)).writeln; + writeln("Tested ", sol.tests, " positions and did ", sol.swaps, " swaps."); +} diff --git a/Task/Solve-the-no-connection-puzzle/Go/solve-the-no-connection-puzzle.go b/Task/Solve-the-no-connection-puzzle/Go/solve-the-no-connection-puzzle.go new file mode 100644 index 0000000000..736a52e7be --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Go/solve-the-no-connection-puzzle.go @@ -0,0 +1,90 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + p, tests, swaps := Solution() + fmt.Println(p) + fmt.Println("Tested", tests, "positions and did", swaps, "swaps.") +} + +// Holes A=0, B=1, …, H=7 +// With connections: +const conn = ` + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H` + +var connections = []struct{ a, b int }{ + {0, 2}, {0, 3}, {0, 4}, // A to C,D,E + {1, 3}, {1, 4}, {1, 5}, // B to D,E,F + {6, 2}, {6, 3}, {6, 4}, // G to C,D,E + {7, 3}, {7, 4}, {7, 5}, // H to D,E,F + {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F +} + +type pegs [8]int + +// Valid checks if the pegs are a valid solution. +// If the absolute difference between any pair of connected pegs is +// greater than one it is a valid solution. +func (p *pegs) Valid() bool { + for _, c := range connections { + if absdiff(p[c.a], p[c.b]) <= 1 { + return false + } + } + return true +} + +// Solution is a simple recursive brute force solver, +// it stops at the first found solution. +// It returns the solution, the number of positions tested, +// and the number of pegs swapped. +func Solution() (p *pegs, tests, swaps int) { + var recurse func(int) bool + recurse = func(i int) bool { + if i >= len(p)-1 { + tests++ + return p.Valid() + } + // Try each remain peg from p[i:] in p[i] + for j := i; j < len(p); j++ { + swaps++ + p[i], p[j] = p[j], p[i] + if recurse(i + 1) { + return true + } + p[i], p[j] = p[j], p[i] + } + return false + } + p = &pegs{1, 2, 3, 4, 5, 6, 7, 8} + recurse(0) + return +} + +func (p *pegs) String() string { + return strings.Map(func(r rune) rune { + if 'A' <= r && r <= 'H' { + return rune(p[r-'A'] + '0') + } + return r + }, conn) +} + +func absdiff(a, b int) int { + if a > b { + return a - b + } + return b - a +} diff --git a/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-1.j b/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-1.j new file mode 100644 index 0000000000..f067adfb57 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-1.j @@ -0,0 +1,34 @@ +holes=:;:'A B C D E F G H' + +connections=:".;._2]0 :0 + holes e.;:'C D E' NB. A + holes e.;:'D E F' NB. B + holes e.;:'A D G' NB. C + holes e.;:'A B C E G H' NB. D + holes e.;:'A B D F G H' NB. E + holes e.;:'B E H' NB. F + holes e.;:'C D E' NB. G + holes e.;:'D E F' NB. H +) +assert (-:|:) connections NB. catch typos + +pegs=: 1+(A.&i.~ !)8 + +attempt=: [: <./@(-.&0)@,@:| connections * -/~ + + +box=:0 :0 + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H +) + +disp=:verb define + rplc&(,holes;&":&>y) box +) diff --git a/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-2.j b/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-2.j new file mode 100644 index 0000000000..dcc0a518fd --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/J/solve-the-no-connection-puzzle-2.j @@ -0,0 +1,17 @@ + (#~ 1 $y, $x { + take [$y,$x] if abs($x|$y) > 2; +} for -5 .. 5 X -5 .. 5; + +solveboard q:to/END/; + . 0 . . 0 . + . . . . . . + 0 . 0 1 . 0 + . . . . . . + . 0 . . 0 . + END diff --git a/Task/Solve-the-no-connection-puzzle/Prolog/solve-the-no-connection-puzzle.pro b/Task/Solve-the-no-connection-puzzle/Prolog/solve-the-no-connection-puzzle.pro new file mode 100644 index 0000000000..476577dd89 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Prolog/solve-the-no-connection-puzzle.pro @@ -0,0 +1,54 @@ +:- use_module(library(clpfd)). + +edge(a, c). +edge(a, d). +edge(a, e). +edge(b, d). +edge(b, e). +edge(b, f). +edge(c, d). +edge(c, g). +edge(d, e). +edge(d, g). +edge(d, h). +edge(e, f). +edge(e, g). +edge(e, h). +edge(f, h). + +connected(A, B) :- + ( edge(A,B); edge(B, A)). + +no_connection_puzzle(Vs) :- + % construct the arranged list of the nodes + bagof(A, B^(edge(A,B); edge(B, A)), Lst), + sort(Lst, L), + length(L, Len), + + % construct the list of the values + length(Vs, Len), + Vs ins 1..Len, + all_distinct(Vs), + + % two connected nodes must have values different for more than 1 + set_constraints(L, Vs), + label(Vs). + + +set_constraints([], []). + +set_constraints([H | T], [VH | VT]) :- + set_constraint(H, T, VH, VT), + set_constraints(T, VT). + + + +set_constraint(_, [], _, []). +set_constraint(H, [H1 | T1], V, [VH | VT]) :- + connected(H, H1), + ( V - VH #> 1; VH - V #> 1), + set_constraint(H, T1, V, VT). + +set_constraint(H, [H1 | T1], V, [_VH | VT]) :- + \+connected(H, H1), + set_constraint(H, T1, V, VT). diff --git a/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-1.py b/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-1.py new file mode 100644 index 0000000000..64eb934bd6 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-1.py @@ -0,0 +1,27 @@ +from __future__ import print_function +from itertools import permutations +from enum import Enum + +A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H') + +connections = ((A, C), (A, D), (A, E), + (B, D), (B, E), (B, F), + (G, C), (G, D), (G, E), + (H, D), (H, E), (H, F), + (C, D), (D, E), (E, F)) + + +def ok(conn, perm): + """Connected numbers ok?""" + this, that = (c.value - 1 for c in conn) + return abs(perm[this] - perm[that]) != 1 + + +def solve(): + return [perm for perm in permutations(range(1, 9)) + if all(ok(conn, perm) for conn in connections)] + + +if __name__ == '__main__': + solutions = solve() + print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0])) diff --git a/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-2.py b/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-2.py new file mode 100644 index 0000000000..ae25f2548d --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Python/solve-the-no-connection-puzzle-2.py @@ -0,0 +1,21 @@ +def pp(solution): + """Prettyprint a solution""" + boardformat = r""" + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H""" + for letter, number in zip("ABCDEFGH", solution): + boardformat = boardformat.replace(letter, str(number)) + print(boardformat) + + +if __name__ == '__main__': + for i, s in enumerate(solutions, 1): + print("\nSolution", i, end='') + pp(s) diff --git a/Task/Solve-the-no-connection-puzzle/README b/Task/Solve-the-no-connection-puzzle/README new file mode 100644 index 0000000000..154e692a5b --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Solve_the_no_connection_puzzle diff --git a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx new file mode 100644 index 0000000000..5732d65365 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx @@ -0,0 +1,55 @@ +/*REXX program solves the "no-connection" puzzle (with eight pegs). */ +parse arg limit . /*# solutions*/ /* ╔═══════════════════════════╗ */ +if limit=='' then limit=1 /* ║ A B ║ */ + /* ║ /│\ /│\ ║ */ +@. = /* ║ / │ \/ │ \ ║ */ +@.1 = 'A C D E' /* ║ / │ /\ │ \ ║ */ +@.2 = 'B D E F' /* ║ / │/ \│ \ ║ */ +@.3 = 'C A D G' /* ║ C────D────E────F ║ */ +@.4 = 'D A B C E G' /* ║ \ │\ /│ / ║ */ +@.5 = 'E A B D F H' /* ║ \ │ \/ │ / ║ */ +@.6 = 'F B E G' /* ║ \ │ /\ │ / ║ */ +@.7 = 'G C D E' /* ║ \│/ \│/ ║ */ +@.8 = 'H D E F' /* ║ G H ║ */ +cnt=0 /* ╚═══════════════════════════╝ */ + do nodes=1 while @.nodes\==''; _=word(@.nodes,1) + subs=0 /* [↓] create list of node paths*/ + do #=1 for words(@.nodes)-1 + __=word(@.nodes,#+1); if __>_ then iterate + subs=subs+1; !._.subs=__ + end /*#*/ + !._.0=subs /*assign the number of node paths*/ + end /*nodes*/ +pegs=nodes-1 /*number of pegs to be seated. */ +_=' ' /*_ is used for padding output.*/ + do a=1 for pegs; if ?('A') then iterate + do b=1 for pegs; if ?('B') then iterate + do c=1 for pegs; if ?('C') then iterate + do d=1 for pegs; if ?('D') then iterate + do e=1 for pegs; if ?('E') then iterate + do f=1 for pegs; if ?('F') then iterate + do g=1 for pegs; if ?('G') then iterate + do h=1 for pegs; if ?('H') then iterate + say _ 'a='a _ 'b='||b _ 'c='c _ 'd='d _ 'e='e _ 'f='f _ 'g='g _ 'h='h + cnt=cnt+1; if cnt==limit then leave a + end /*h*/ + end /*g*/ + end /*f*/ + end /*e*/ + end /*d*/ + end /*c*/ + end /*b*/ + end /*a*/ +say /*display a blank line to screen.*/ +s=left('s',cnt\==1) /*handle case of plurals (or not)*/ +say 'found ' cnt " solution"s'.' /*display the number of solutions*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────? subroutine────────────────────────*/ +?: parse arg node; nn=value(node); nL=nn-1; nH=nn+1 + do cn=c2d('A') to c2d(node)-1; if value(d2c(cn))==nn then return 1; end + /* [↑] see if any are duplicates*/ + do ch=1 for !.node.0 /* [↓] see if any ¬ = ±1 value*/ + $=!.node.ch; fn=value($) /*node name and its current peg#.*/ + if nL==fn | nH==fn then return 1 /*if ≡ ±1, then it can't be used.*/ + end /*ch*/ /* [↑] looking for suitable num.*/ +return 0 /*the sub arg value passed is OK.*/ diff --git a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx new file mode 100644 index 0000000000..6f960d8dda --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx @@ -0,0 +1,76 @@ +/*REXX program solves the "no-connection" puzzle (with eight pegs). */ +@abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +parse arg limit . /*# solutions*/ /* ╔═══════════════════════════╗ */ +if limit=='' then limit=1 /* ║ A B ║ */ +oLimit=limit; limit=abs(limit) /* ║ /│\ /│\ ║ */ +@. = /* ║ / │ \/ │ \ ║ */ +@.1 = 'A C D E' /* ║ / │ /\ │ \ ║ */ +@.2 = 'B D E F' /* ║ / │/ \│ \ ║ */ +@.3 = 'C A D G' /* ║ C────D────E────F ║ */ +@.4 = 'D A B C E G' /* ║ \ │\ /│ / ║ */ +@.5 = 'E A B D F H' /* ║ \ │ \/ │ / ║ */ +@.6 = 'F B E G' /* ║ \ │ /\ │ / ║ */ +@.7 = 'G C D E' /* ║ \│/ \│/ ║ */ +@.8 = 'H D E F' /* ║ G H ║ */ +cnt=0 /* ╚═══════════════════════════╝ */ + do nodes=1 while @.nodes\==''; _=word(@.nodes,1) + subs=0 /* [↓] create list of node paths*/ + do #=1 for words(@.nodes)-1 + __=word(@.nodes,#+1); if __>_ then iterate + subs=subs+1; !._.subs=__ + end /*#*/ + !._.0=subs /*assign the number of node paths*/ + end /*nodes*/ +pegs=nodes-1 /*number of pegs to be seated. */ + do a=1 for pegs; if ?('A') then iterate + do b=1 for pegs; if ?('B') then iterate + do c=1 for pegs; if ?('C') then iterate + do d=1 for pegs; if ?('D') then iterate + do e=1 for pegs; if ?('E') then iterate + do f=1 for pegs; if ?('F') then iterate + do g=1 for pegs; if ?('G') then iterate + do h=1 for pegs; if ?('H') then iterate + call showNodes + cnt=cnt+1; if cnt==limit then leave a + end /*h*/ + end /*g*/ + end /*f*/ + end /*e*/ + end /*d*/ + end /*c*/ + end /*b*/ + end /*a*/ +say /*display a blank line to screen.*/ +s=left('s',cnt\==1) /*handle case of plurals (or not)*/ +say 'found ' cnt " solution"s'.' /*display the number of solutions*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────? subroutine────────────────────────*/ +?: parse arg node; nn=value(node); nL=nn-1; nH=nn+1 + do cn=c2d('A') to c2d(node)-1; if value(d2c(cn))==nn then return 1; end + /* [↑] see if any are duplicates*/ + do ch=1 for !.node.0 /* [↓] see if any ¬ = ±1 value*/ + $=!.node.ch; fn=value($) /*node name and its current peg#.*/ + if nL==fn | nH==fn then return 1 /*if ≡ ±1, then it can't be used.*/ + end /*ch*/ /* [↑] looking for suitable num.*/ +return 0 /*the sub arg value passed is OK.*/ +/*──────────────────────────────────SHOWNODES subroutine────────────────*/ +showNodes: _=' ' /*_ is used for padding output.*/ +show=0 /*indicates graph not found yet. */ + + do box=1 for sourceline() while oLimit<0 /*Negative? Then show it*/ + xw=sourceline(box) /*get a line of this REXX program*/ + p2=lastpos('*',xw) /*position of last asterisk.*/ + p1=lastpos('*',xw,max(1,p2-1)) /* " " penultimate " */ + if pos('╔', xw)\==0 then show=1 /*Found the top-left box corner? */ + if \show then iterate /*Not found? Then skip this line*/ + xb=substr(xw, p1+1, p2-p1-2) /*extract the "box" part of line.*/ + xt=xb /*get a working copy of the box. */ + do jx=1 for pegs /*do a substitution for all pegs.*/ + aa=substr(@abc,jx,1) /*get the name of the peg (A──►Z)*/ + xt=translate(xt,value(aa),aa) /*substitute peg name with value.*/ + end /*jx*/ /* [↑] graph limited to 26 nodes*/ + say _ xb _ _ xt /*display one line of the graph. */ + if pos('╝',xw)\==0 then return /*Last line of graph? Then stop.*/ + end /*box*/ + /* [↓] show a simple solution. */ +say _ 'a='a _ 'b='||b _ 'c='c _ 'd='d _ 'e='e _ 'f='f _ 'g='g _ 'h='h diff --git a/Task/Solve-the-no-connection-puzzle/Racket/solve-the-no-connection-puzzle.rkt b/Task/Solve-the-no-connection-puzzle/Racket/solve-the-no-connection-puzzle.rkt new file mode 100644 index 0000000000..749f8b2928 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Racket/solve-the-no-connection-puzzle.rkt @@ -0,0 +1,43 @@ +#lang racket +;; Solve the no connection puzzle. Tim Brown Oct. 2014 + +;; absolute difference of a and b if they are both true +(define (and- a b) (and a b (abs (- a b)))) + +;; Finds the differences of all established connections in the network +(define (network-diffs (A #f) (B #f) (C #f) (D #f) (E #f) (F #f) (G #f) (H #f)) + (list (and- A C) (and- A D) (and- A E) + (and- B D) (and- B E) (and- B F) + (and- C D) (and- C G) + (and- D E) (and- D G) (and- D H) + (and- E F) (and- E G) (and- E H) + (and- F G))) + +;; Make sure there is “no connection” in the network N; return N if good +(define (good-network? N) + (and (for/and ((d (filter values (apply network-diffs N)))) (> d 1)) N)) + +;; possible optimisation is to reverse the arguments to network-diffs, reverse the return value from +;; this function and make this a cons but we're pretty quick here as it is. +(define (find-good-network pegs (n/w null)) + (if (null? pegs) n/w + (for*/or ((p pegs)) + (define n/w+ (append n/w (list p))) + (and (good-network? n/w+) + (find-good-network (remove p pegs =) n/w+))))) + +(define (render-puzzle pzl) + (apply printf (regexp-replace* "O" #< +(Unicode values U+2581 through U+2588). + +Use your program to show sparklines for the following input, +here on this page: +# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 +# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 +:(note the mix of separators in this second case)! + +;Notes: +* A space is not part of the generated sparkline. +* The sparkline may be accompanied by simple statistics of the data such as its range. diff --git a/Task/Sparkline-in-unicode/AutoHotkey/sparkline-in-unicode.ahk b/Task/Sparkline-in-unicode/AutoHotkey/sparkline-in-unicode.ahk new file mode 100644 index 0000000000..3c442d4739 --- /dev/null +++ b/Task/Sparkline-in-unicode/AutoHotkey/sparkline-in-unicode.ahk @@ -0,0 +1,23 @@ +SetFormat, FloatFast, 0.1 +strings := ["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" + , "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"] + +Loop, % strings.MaxIndex() +{ + SL := Sparklines(strings[A_Index]) + MsgBox, % "Min: " SL["Min"] ", Max: " SL["Max"] ", Range: " SL["Rng"] "`n" SL["Chars"] +} + +Sparklines(s) +{ + s := RegexReplace(s, "[^\d\.]+", ",") + Loop, Parse, s, `, + { + Max := A_LoopField > Max ? A_LoopField : Max + Min := !Min ? Max : A_LoopField < Min ? A_LoopField : Min + } + Rng := Max - Min + Loop, Parse, s, `, + Chars .= Chr(0x2581 + Round(7 * (A_LoopField - Min) / Rng)) + return, {"Min": Min, "Max": Max, "Rng": Rng, "Chars": Chars} +} diff --git a/Task/Sparkline-in-unicode/C++/sparkline-in-unicode.cpp b/Task/Sparkline-in-unicode/C++/sparkline-in-unicode.cpp new file mode 100644 index 0000000000..45ea1538e9 --- /dev/null +++ b/Task/Sparkline-in-unicode/C++/sparkline-in-unicode.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include + +class Sparkline { + public: + Sparkline(std::wstring &cs) : charset( cs ){ + } + virtual ~Sparkline(){ + } + + void print(std::string spark){ + const char *delim = ", "; + std::vector data; + // Get first non-delimiter + std::string::size_type last = spark.find_first_not_of(delim, 0); + // Get end of token + std::string::size_type pos = spark.find_first_of(delim, last); + + while( pos != std::string::npos || last != std::string::npos ){ + std::string tok = spark.substr(last, pos-last); + // Convert to float: + std::stringstream ss(tok); + float entry; + ss >> entry; + + data.push_back( entry ); + + last = spark.find_first_not_of(delim, pos); + pos = spark.find_first_of(delim, last); + } + + // Get range of dataset + float min = *std::min_element( data.begin(), data.end() ); + float max = *std::max_element( data.begin(), data.end() ); + + float skip = (charset.length()-1) / (max - min); + + std::wcout<::const_iterator it; + for(it = data.begin(); it != data.end(); it++){ + float v = ( (*it) - min ) * skip; + std::wcout< i.to!dchar).dtext; + immutable div = (mm[1] - mm[0]) / (bars.length - 1); + numbers.map!(n => bars[cast(int)((n - mm[0]) / div)]).writeln; +} diff --git a/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-1.elixir b/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-1.elixir new file mode 100644 index 0000000000..244fd1b8ff --- /dev/null +++ b/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-1.elixir @@ -0,0 +1,8 @@ +defmodule RC do + def sparkline(str) do + values = str |> String.split(~r/(,| )+/) + |> Enum.map(&(elem(Float.parse(&1), 0))) + {min, max} = {Enum.min(values), Enum.max(values)} + IO.puts Enum.map(values, &(round((&1 - min) / (max - min) * 7 + 0x2581))) + end +end diff --git a/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-2.elixir b/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-2.elixir new file mode 100644 index 0000000000..3be562bee6 --- /dev/null +++ b/Task/Sparkline-in-unicode/Elixir/sparkline-in-unicode-2.elixir @@ -0,0 +1,6 @@ +str1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" +str2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" + +RC.sparkline(str1) +IO.puts "" # newline +RC.sparkline(str2) diff --git a/Task/Sparkline-in-unicode/FALSE/sparkline-in-unicode.false b/Task/Sparkline-in-unicode/FALSE/sparkline-in-unicode.false new file mode 100644 index 0000000000..386f5c8479 --- /dev/null +++ b/Task/Sparkline-in-unicode/FALSE/sparkline-in-unicode.false @@ -0,0 +1,68 @@ +{ + variables: + s: sign (1 or -1) + u: current number + f: current number fraction length + v: current number is valid + t: number of numbers read + x: biggest fraction + y: smallest number (without fraction) + z: biggest number (without fraction) +} + +{function a: test if top is 0-9, without popping the value, codes 48-57 are in range} +[$$47>\57>~&]a: + +{function b: test if top is ',' or ' ', without popping the value} +[$$',=\' =|]b: + +{function c: read a number from the input, given that the first character of the input is already on the stack} +[ + 1s:0u:0f:0v: {reset values} + + $'-=[1_s:%^]? {if (it is negative) set the sign value to -1 move to next} + [a;!][48-u;10*+u:1_v:^]# {while (isnumber) do number = number * 10 + decimal and set valid number and move to next} + $'.=[ {if (it is a decimal) move forward and read fraction} + %^ + [a;!][48-u;10*+u:f;1+f:1_v:^]# {while (isnumber) do number = number * 10 + decimal and increase fraction length and set valid number and move to next} + ]? + $$'-=\'.=|[0v:]? {if next charachter is a '-' or a '.', set invalid} +]c: + +{function d: normalize number/fraction from stack to max fraction and push that number} +[ + [$x;=~][1+\10*\]# {while (fraction != max) fraction + 1, value * 10} + % {pop fraction} +]d: + +0t: +0x: +1_v: { nothing read, so we are still valid } +^[b;!][%^]# {read away any initial separators} +[$1_=~v;&][ {while input != -1 and valid input, leaving input on the stack} + c;! {read a number} + t;1+t:u;s;*f;@ {increase count, push number * sign and fraction length onto the stack and bring input back up} + f;x;>[f;x:]? {set fraction to biggest of current and previous biggest} + [b;!][%^]# {while (isseparator) move forward} +]# +v;~["error at charachter ",]? {if invalid number, tell them when} +v;[ {if last number also valid, do the math} + % {pop the -1} + t;2*1-q: {var q: points to next value} + 0p: {var p: whether min/max have been set} + [q;1+t;>][ {while q + 1 > t} + q;ø {current number} + q;ø {current fraction} + d;! {normalize} + p;[$y;\>[$y:]? $z;>[$z:]?]? {compare min/max} + p;~[1_p:$y:$z:]? {if (first)) set min/max} + q;1-q: {move pointer} + ]# + + t;q: {point q to first value} + [q;0>][ {while q > 0} + q;1-øy;-7*z;y;-/ {(number - minvalue) * 7 / (maxvalue - minvalue), should result in 0..7} + 9601+, {print character} + q;1-q: {move pointer} + ]# +]? diff --git a/Task/Sparkline-in-unicode/Go/sparkline-in-unicode.go b/Task/Sparkline-in-unicode/Go/sparkline-in-unicode.go new file mode 100644 index 0000000000..6ae3b50fc8 --- /dev/null +++ b/Task/Sparkline-in-unicode/Go/sparkline-in-unicode.go @@ -0,0 +1,74 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "math" + "os" + "regexp" + "strconv" + "strings" +) + +func main() { + fmt.Println("Numbers please separated by space/commas:") + sc := bufio.NewScanner(os.Stdin) + sc.Scan() + s, n, min, max, err := spark(sc.Text()) + if err != nil { + fmt.Println(err) + return + } + if n == 1 { + fmt.Println("1 value =", min) + } else { + fmt.Println(n, "values. Min:", min, "Max:", max) + } + fmt.Println(s) +} + +var sep = regexp.MustCompile(`[\s,]+`) + +func spark(s0 string) (sp string, n int, min, max float64, err error) { + ss := sep.Split(s0, -1) + n = len(ss) + vs := make([]float64, n) + var v float64 + min = math.Inf(1) + max = math.Inf(-1) + for i, s := range ss { + switch v, err = strconv.ParseFloat(s, 64); { + case err != nil: + case math.IsNaN(v): + err = errors.New("NaN not supported.") + case math.IsInf(v, 0): + err = errors.New("Inf not supported.") + default: + if v < min { + min = v + } + if v > max { + max = v + } + vs[i] = v + continue + } + return + } + if min == max { + sp = strings.Repeat("▄", n) + } else { + rs := make([]rune, n) + f := 8 / (max - min) + for j, v := range vs { + i := rune(f * (v - min)) + if i > 7 { + i = 7 + } + rs[j] = '▁' + i + } + sp = string(rs) + } + return +} diff --git a/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-1.groovy b/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-1.groovy new file mode 100644 index 0000000000..27b9b1b87d --- /dev/null +++ b/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-1.groovy @@ -0,0 +1,6 @@ +def sparkline(List list) { + def (min, max) = [list.min(), list.max()] + def div = (max - min) / 7 + list.collect { (char)(0x2581 + (it-min) * div) }.join() +} +def sparkline(String text) { sparkline(text.split(/[ ,]+/).collect { it as Double }) } diff --git a/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-2.groovy b/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-2.groovy new file mode 100644 index 0000000000..b2c601dcf1 --- /dev/null +++ b/Task/Sparkline-in-unicode/Groovy/sparkline-in-unicode-2.groovy @@ -0,0 +1,4 @@ +["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"].each { dataset -> + println " Dataset: $dataset" + println "Sparkline: ${sparkline(dataset)}" +} diff --git a/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs b/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs new file mode 100644 index 0000000000..4b15633f81 --- /dev/null +++ b/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs @@ -0,0 +1,39 @@ +import Data.Char (chr) +import Data.List.Split (splitOneOf) + +toSparkLine :: [Double] -> [Char] +toSparkLine xs = map cl xs + where + top = maximum xs + bot = minimum xs + range = top - bot + cl x = chr $ 0x2581 + round ((x - bot) / range * 7) + +makeSparkLine :: String -> (String, Stats) +makeSparkLine xs = (toSparkLine parsed, stats parsed) + where parsed = map read $ filter (not . null) $ splitOneOf " ," xs + +data Stats = Stats { minValue, maxValue, rangeOfValues :: Double, + numberOfValues :: Int } + +instance Show Stats where + show (Stats mn mx r n) = "min: " ++ show mn ++ "; max: " ++ show mx ++ + "; range: " ++ show r ++ "; no. of values: " ++ show n + +stats :: [Double] -> Stats +stats xs = Stats { minValue = mn, maxValue = mx, + rangeOfValues = mx - mn, numberOfValues = length xs } + where + mn = minimum xs + mx = maximum xs + +drawSparkLineWithStats :: String -> IO () +drawSparkLineWithStats xs = putStrLn sp >> print st + where (sp, st) = makeSparkLine xs + +main :: IO () +main = mapM_ drawSparkLineWithStats + ["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", + "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5", + "3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3", + "-1000 100 1000 500 200 -400 -700 621 -189 3"] diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-1.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-1.j new file mode 100644 index 0000000000..304026c49f --- /dev/null +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-1.j @@ -0,0 +1,7 @@ + spkln =: verb define + y spkln~ 4 u:16b2581+i.8 NB. ▁▂▃▄▅▆▇█ + : + 'MIN MAX' =. (<./ , >./) y + N =. # x + x {~ <. (N-1) * (y-MIN) % MAX-MIN + ) diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j new file mode 100644 index 0000000000..c80f79d100 --- /dev/null +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j @@ -0,0 +1 @@ + spkln =: (4 u:16b2581+i.8)&$: : ([ {~ <:@#@[ * ] (- % >./@[ - ]) <./@]) diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j new file mode 100644 index 0000000000..b1ed8c1dd6 --- /dev/null +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j @@ -0,0 +1 @@ + spkln =: (4 u:16b2581+i.8)&$: : ([ {~ ((* <:@#)~ ((- % (- >./))~ <./))) diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j new file mode 100644 index 0000000000..fe3a30b470 --- /dev/null +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j @@ -0,0 +1,4 @@ + spkln 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 +▁▂▃▄▅▆▇█▇▆▅▄▃▂▁ + spkln 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 +▁▅█▆▅▃▂▇▄▅ diff --git a/Task/Sparkline-in-unicode/Java/sparkline-in-unicode.java b/Task/Sparkline-in-unicode/Java/sparkline-in-unicode.java new file mode 100644 index 0000000000..3247a67a4b --- /dev/null +++ b/Task/Sparkline-in-unicode/Java/sparkline-in-unicode.java @@ -0,0 +1,41 @@ +public class Sparkline +{ + String bars="▁▂▃▄▅▆▇█"; + public static void main(String[] args) + { + Sparkline now=new Sparkline(); + float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; + now.display1D(arr); + System.out.println(now.getSparkline(arr)); + float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; + now.display1D(arr1); + System.out.println(now.getSparkline(arr1)); + } + public void display1D(float[] arr) + { + for(int i=0;imax) + max=arr[i]; + } + float range=max-min; + int num=bars.length()-1; + String line=""; + for(int i=0;i {" ", ","}]] + 16^^2581]; diff --git a/Task/Sparkline-in-unicode/NetRexx/sparkline-in-unicode.netrexx b/Task/Sparkline-in-unicode/NetRexx/sparkline-in-unicode.netrexx new file mode 100644 index 0000000000..ff28e4b50b --- /dev/null +++ b/Task/Sparkline-in-unicode/NetRexx/sparkline-in-unicode.netrexx @@ -0,0 +1,54 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method sparkline(spark) private static + spark = spark.changestr(',', ' ') + bars = '\u2581 \u2582 \u2583 \u2584 \u2585 \u2586 \u2587 \u2588' + barK = bars.words() + nmin = spark.word(1) + nmax = nmin + -- get min & max values + loop iw = 1 to spark.words() + nval = spark.word(iw) + nmin = nval.min(nmin) + nmax = nval.max(nmax) + end iw + range = nmax - nmin + 1 + slope = '' + loop iw = 1 to spark.words() + point = Math.ceil((spark.word(iw) - nmin + 1) / range * barK) + slope = slope || bars.word(point) + end iw + return slope nmin nmax range + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + -- sample data setup + parse arg vals + sparks = 0 + sparks[0] = 0 + if vals = '' then do + si = sparks[0] + 1; sparks[0] = si; sparks[si] = 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 + si = sparks[0] + 1; sparks[0] = si; sparks[si] = '1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5' + end + else do + loop until vals = '' + -- split input on a ! character + parse vals lst '!' vals + si = sparks[0] + 1; sparks[0] = si; sparks[si] = lst + end + end + -- run the samples + loop si = 1 to sparks[0] + vals = sparks[si] + parse sparkline(vals) slope . + say 'Input: ' vals + say 'Sparkline: ' slope + say + end si + + return diff --git a/Task/Sparkline-in-unicode/Perl-6/sparkline-in-unicode.pl6 b/Task/Sparkline-in-unicode/Perl-6/sparkline-in-unicode.pl6 new file mode 100644 index 0000000000..5a620bff31 --- /dev/null +++ b/Task/Sparkline-in-unicode/Perl-6/sparkline-in-unicode.pl6 @@ -0,0 +1,8 @@ +constant @bars = '▁' ... '█'; +while prompt 'Numbers separated by anything: ' -> $_ { + my @numbers = map +*, .comb(/ '-'? \d+ ['.' \d+]? /); + my ($mn,$mx) = @numbers.minmax.bounds; + say "min: $mn.fmt('%5f'); max: $mx.fmt('%5f')"; + my $div = ($mx - $mn) / (@bars - 1); + say @bars[ (@numbers X- $mn) X/ $div ].join; +} diff --git a/Task/Sparkline-in-unicode/Perl/sparkline-in-unicode.pl b/Task/Sparkline-in-unicode/Perl/sparkline-in-unicode.pl new file mode 100644 index 0000000000..a928df919d --- /dev/null +++ b/Task/Sparkline-in-unicode/Perl/sparkline-in-unicode.pl @@ -0,0 +1,19 @@ +binmode(STDOUT, ":utf8"); + +sub sparkline { + my $s = shift; + my @n = split(/[\s,]+/,$s); + return unless @n; + my($min,$max) = ($n[0],$n[0]); + for my $v (@n) { $min = $v if $v < $min; $max = $v if $v > $max; } + printf "min: %5f; max %5f\n", $min, $max; + my @bars = map { chr($_) } 0x2581 .. 0x2588; + my $div = ($max - $min) / $#bars; + print join("", map { $bars[$div ? ($_-$min) / $div : @bars/2] } @n), "\n"; + 1; +} + +while (1) { + print "Numbers separated by spaces/commas: "; + exit unless sparkline(scalar(<>)); +} diff --git a/Task/Sparkline-in-unicode/Python/sparkline-in-unicode.py b/Task/Sparkline-in-unicode/Python/sparkline-in-unicode.py new file mode 100644 index 0000000000..ae6cbfdff3 --- /dev/null +++ b/Task/Sparkline-in-unicode/Python/sparkline-in-unicode.py @@ -0,0 +1,17 @@ +import re +try: raw_input +except: raw_input = input + +# Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608 +try: bar = u'▁▂▃▄▅▆▇█' +except: bar = '▁▂▃▄▅▆▇█' +barcount = len(bar) - 1 +while True: + line = raw_input('Numbers please separated by space/commas: ') + numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] + mn, mx = min(numbers), max(numbers) + extent = mx - mn + sparkline = ''.join(bar[int( (n - mn) / extent * barcount)] + for n in numbers) + print('min: %5f; max: %5f' % (mn, mx)) + print(sparkline) diff --git a/Task/Sparkline-in-unicode/README b/Task/Sparkline-in-unicode/README new file mode 100644 index 0000000000..633df4c388 --- /dev/null +++ b/Task/Sparkline-in-unicode/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Sparkline_in_unicode diff --git a/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-1.rexx b/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-1.rexx new file mode 100644 index 0000000000..65f540959e --- /dev/null +++ b/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-1.rexx @@ -0,0 +1,67 @@ +/* Rexx */ + +parse arg aaa +call runSample aaa +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +sparkline: + procedure + parse arg spark + spark = changestr(',', spark, ' ') + bars = '▁ ▂ ▃ ▄ ▅ ▆ ▇ █' + barK = words(bars) + nmin = word(spark, 1) + nmax = nmin + -- get min & max values + do iw = 1 to words(spark) + nval = word(spark, iw) + nmin = min(nval, nmin) + nmax = max(nval, nmax) + end iw + range = nmax - nmin + 1 + slope = '' + do iw = 1 to words(spark) + point = ceiling((word(spark, iw) - nmin + 1) / range * barK) + slope = slope || word(bars, point) + end iw + return slope nmin nmax range + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +ceiling: +procedure + parse arg ceil + return trunc(ceil) + (ceil > 0) * (ceil \= trunc(ceil)) +floor: +procedure + parse arg flor + return trunc(flor) - (flor < 0) * (flor \= trunc(flor)) + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +runSample: +procedure + -- sample data setup + parse arg vals + sparks = 0 + sparks.0 = 0 + if vals = '' then do + si = sparks.0 + 1; sparks.0 = si; sparks.si = 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 + si = sparks.0 + 1; sparks.0 = si; sparks.si = '1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5' + end + else do + do until vals = '' + -- split input on a ! character + parse var vals lst '!' vals + si = sparks.0 + 1; sparks.0 = si; sparks.si = lst + end + end + -- run the samples + do si = 1 to sparks.0 + vals = sparks.si + parse value sparkline(vals) with slope . + say 'Input: ' vals + say 'Sparkline: ' slope + say + end si + + return diff --git a/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-2.rexx b/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-2.rexx new file mode 100644 index 0000000000..d605611c4d --- /dev/null +++ b/Task/Sparkline-in-unicode/REXX/sparkline-in-unicode-2.rexx @@ -0,0 +1,26 @@ +/*REXX program displays a sparkline (spark graph) for a group of values.*/ +if arg()==0 then do /*No arguments? Use defaults.*/ + call sparkGraph 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 + call sparkGraph '1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5' + end + else call sparkGraph arg(1) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CEIL subroutine─────────────────────*/ +ceil: procedure; parse arg ?; _=trunc(?); return _+(?>0)*(?\=_) +/*──────────────────────────────────SPARKGRAPH subroutine───────────────*/ +sparkGraph: procedure; parse arg x; say ' input: ' x /*echo values*/ +x=translate(x, ' ', ",") /*remove any superfluous commas. */ +$='▁▂▃▄▅▆▇█' /*chars to be used for the graph.*/ +xmin=word(x,1); xmax=xmin /*assume a minimum and a maximum.*/ + + do n=2 to words(x); _=word(x,n) /*examine successive words in X.*/ + xmin=min(_,xmin) /*find the minimum value in X. */ + xmax=max(_,xmax) /* " " maximum " " " */ + end /*n*/ + +z=; do j=1 for words(x) /*build the output spark graph. */ + z=z||substr($,ceil((word(x,j)-xmin+1)/(xmax-xmin+1)*length($)),1) + end /*j*/ + +say 'output: ' z; say /*show the output, + a blank line*/ +return diff --git a/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-1.rkt b/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-1.rkt new file mode 100644 index 0000000000..4299d4cd3b --- /dev/null +++ b/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-1.rkt @@ -0,0 +1,13 @@ +#lang racket (require syntax/parse) + +(define bars "▁▂▃▄▅▆▇█") +(define bar-count (string-length bars)) + +(define (sparks str) + (define ns (map string->number (string-split str #rx"[ ,]" #:repeat? #t))) + (define mn (apply min ns)) + (define bar-width (/ (- (apply max ns) mn) (- bar-count 1))) + (apply string (for/list ([n ns]) (string-ref bars (exact-floor (/ (- n mn) bar-width)))))) + +(sparks "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1") +(sparks "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") diff --git a/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-2.rkt b/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-2.rkt new file mode 100644 index 0000000000..bfb2f3e7fe --- /dev/null +++ b/Task/Sparkline-in-unicode/Racket/sparkline-in-unicode-2.rkt @@ -0,0 +1,2 @@ +"▁▂▃▄▅▆▇█▇▆▅▄▃▂▁" +"▂▁▄▃▆▅█▇" diff --git a/Task/Sparkline-in-unicode/Ruby/sparkline-in-unicode.rb b/Task/Sparkline-in-unicode/Ruby/sparkline-in-unicode.rb new file mode 100644 index 0000000000..a44e28234d --- /dev/null +++ b/Task/Sparkline-in-unicode/Ruby/sparkline-in-unicode.rb @@ -0,0 +1,8 @@ +bar = ('▁'..'█').to_a +loop {print 'Numbers please separated by space/commas: ' + numbers = gets.split(/[\s,]+/).map(&:to_f) + min, max = numbers.minmax + puts "min: %5f; max: %5f"% [min, max] + div = (max - min) / (bar.size - 1) + puts min == max ? bar.last*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i]}.join +} diff --git a/Task/Sparkline-in-unicode/Scala/sparkline-in-unicode.scala b/Task/Sparkline-in-unicode/Scala/sparkline-in-unicode.scala new file mode 100644 index 0000000000..40d9e56a42 --- /dev/null +++ b/Task/Sparkline-in-unicode/Scala/sparkline-in-unicode.scala @@ -0,0 +1,16 @@ +def mkSparks( numStr:String ) : String = + numStr.split( "[\\s,]+" ).map(_.toFloat) match { + case v if v.isEmpty => "" + case v if v.length == 1 => "\u2581" + case v => + (for( i <- v; + s = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588".toCharArray; + d = (v.max - v.min) / (s.length - 1) + ) yield s( ((i - v.min) / d).toInt)).mkString + } + +println( mkSparks( "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" ) ) +println( mkSparks( "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" ) ) + +// A random test... +println( mkSparks( Stream.continually( math.abs(util.Random.nextInt % 8)).take(64).mkString(" ") )) diff --git a/Task/Sparkline-in-unicode/Seed7/sparkline-in-unicode.seed7 b/Task/Sparkline-in-unicode/Seed7/sparkline-in-unicode.seed7 new file mode 100644 index 0000000000..79861dfa41 --- /dev/null +++ b/Task/Sparkline-in-unicode/Seed7/sparkline-in-unicode.seed7 @@ -0,0 +1,53 @@ +$ include "seed7_05.s7i"; + include "scanfile.s7i"; + include "float.s7i"; + include "utf8.s7i"; + +const func array float: readDataLine is func + result + var array float: data is 0 times 0.0; + begin + write("Numbers separated by anything: "); + IN.bufferChar := getc(IN); + skipSpace(IN); + while IN.bufferChar <> '\n' do + data &:= float parse getNumber(IN); + skipSpace(IN); + if IN.bufferChar = ',' then + IN.bufferChar := getc(IN); + end if; + skipSpace(IN); + end while; + end func; + + +const proc: main is func + local + const string: bars is "▁▂▃▄▅▆▇█"; + var array float: data is 0 times 0.0; + var float: min is 0.0; + var float: max is 0.0; + var float: number is 0.0; + var integer: index is 0; + begin + OUT := STD_UTF8_OUT; + data := readDataLine; + while length(data) >= 1 do + min := data[1]; + max := data[1]; + for number range data do + if number < min then + min := number; + end if; + if number > max then + max := number; + end if; + end for; + for number range data do + index := succ(min(trunc((number - min) * 8.0 / max), 7)); + write(bars[index]); + end for; + writeln; + data := readDataLine; + end while; + end func; diff --git a/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-1.tcl b/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-1.tcl new file mode 100644 index 0000000000..3b8bde0c31 --- /dev/null +++ b/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-1.tcl @@ -0,0 +1,15 @@ +package require Tcl 8.6 + +proc extractValues {series} { + return [regexp -all -inline {\d+(?:\.\d*)?|\.\d+} $series] +} +proc renderValue {min max value} { + set band [expr {int(8*($value-$min)/(($max-$min)*1.01))}] + return [format "%c" [expr {0x2581 + $band}]] +} +proc sparkline {series} { + set values [extractValues $series] + set min [tcl::mathfunc::min {*}$values] + set max [tcl::mathfunc::max {*}$values] + return [join [lmap v $values {renderValue $min $max $v}] ""] +} diff --git a/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-2.tcl b/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-2.tcl new file mode 100644 index 0000000000..dfc8a54be7 --- /dev/null +++ b/Task/Sparkline-in-unicode/Tcl/sparkline-in-unicode-2.tcl @@ -0,0 +1,8 @@ +set data { + "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" + "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" +} +foreach series $data { + puts "Series: $series" + puts "Sparkline: [sparkline $series]" +} diff --git a/Task/State-name-puzzle/00DESCRIPTION b/Task/State-name-puzzle/00DESCRIPTION new file mode 100644 index 0000000000..ef72fa6abf --- /dev/null +++ b/Task/State-name-puzzle/00DESCRIPTION @@ -0,0 +1,40 @@ +'''Background''' + +This task is inspired by [http://drdobbs.com/windows/198701685 Mark Nelson's DDJ Column "Wordplay"] and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [http://www.npr.org/templates/story/story.php?storyId=9264290] and originally attributed to David Edelheit. + +The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two ''different'' U.S. States (so that all four state names differ from one another). What states are these? + +The problem was reissued on [https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle the Unicon Discussion Web] which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to [[wp:Goedel_numbering|Gödel numbering]], [[wp:Equivalence_relation|equivalence relations]], and [[wp:Equivalence_classes|equivalence classes]]. The basic merits of these were discussed in the Unicon Discussion Web. + +A second challenge in the form of a set of fictitious new states was also presented. + +'''Task:'''
+Write a program to solve the challenge using both the original list of states and the fictitious list. + +Caveats: +* case and spacing isn't significant - just letters (harmonize case) +* don't expect the names to be in any order - such as being sorted +* don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) + +Comma separated list of state names used in the original puzzle: +
+    "Alabama", "Alaska", "Arizona", "Arkansas",
+    "California", "Colorado", "Connecticut",
+    "Delaware",
+    "Florida", "Georgia", "Hawaii",
+    "Idaho", "Illinois", "Indiana", "Iowa",
+    "Kansas", "Kentucky", "Louisiana",
+    "Maine", "Maryland", "Massachusetts", "Michigan",
+    "Minnesota", "Mississippi", "Missouri", "Montana",
+    "Nebraska", "Nevada", "New Hampshire", "New Jersey",
+    "New Mexico", "New York", "North Carolina", "North Dakota",
+    "Ohio", "Oklahoma", "Oregon",
+    "Pennsylvania", "Rhode Island",
+    "South Carolina", "South Dakota", "Tennessee", "Texas",
+    "Utah", "Vermont", "Virginia",
+    "Washington", "West Virginia", "Wisconsin", "Wyoming"
+
+Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): +
+"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
+
diff --git a/Task/State-name-puzzle/00META.yaml b/Task/State-name-puzzle/00META.yaml new file mode 100644 index 0000000000..31274225a6 --- /dev/null +++ b/Task/State-name-puzzle/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Puzzles diff --git a/Task/State-name-puzzle/Bracmat/state-name-puzzle.bracmat b/Task/State-name-puzzle/Bracmat/state-name-puzzle.bracmat new file mode 100644 index 0000000000..e1aa710b6f --- /dev/null +++ b/Task/State-name-puzzle/Bracmat/state-name-puzzle.bracmat @@ -0,0 +1,91 @@ +( Alabama + Alaska + Arizona + Arkansas + California + Colorado + Connecticut + Delaware + Florida + Georgia + Hawaii + Idaho + Illinois + Indiana + Iowa + Kansas + Kentucky + Louisiana + Maine + Maryland + Massachusetts + Michigan + Minnesota + Mississippi + Missouri + Montana + Nebraska + Nevada + "New Hampshire" + "New Jersey" + "New Mexico" + "New York" + "North Carolina" + "North Dakota" + Ohio + Oklahoma + Oregon + Pennsylvania + "Rhode Island" + "South Carolina" + "South Dakota" + Tennessee + Texas + Utah + Vermont + Virginia + Washington + "West Virginia" + Wisconsin + Wyoming + : ?states +& "New Kory" "Wen Kory" "York New" "Kory New" "New Kory":?extrastates +& ( "State name puzzle" + = allStates State state statechars char + , A Z S1 S2 S3 S4 L1 L2 L3 L4 L12 + . 0:?allStates + & whl + ' ( !arg:%?State ?arg + & low$!State:?state + & 0:?statechars + & whl + ' ( @(!state:? (%@:~" ":?char) ?state) + & !char+!statechars:?statechars + ) + & (!State.!statechars)+!allStates:?allStates + ) + & ( !allStates + : ? + + ?*(?S1.?L1) + + ?A + + ?*(?S2.?L2) + + ( ?Z + & !L1+!L2:?L12 + & !A+!Z + : ? + + ?*(?S3.?L3&!L12+-1*!L3:?L4) + + ? + + ? + * ( ?S4 + . !L4 + & out$(!S1 "+" !S2 "=" !S3 "+" !S4) + & ~ + ) + + ? + ) + | out$"No more solutions" + ) + ) +& "State name puzzle"$!states +& "State name puzzle"$(!states !extrastates) +); diff --git a/Task/State-name-puzzle/C/state-name-puzzle.c b/Task/State-name-puzzle/C/state-name-puzzle.c new file mode 100644 index 0000000000..2f999cb600 --- /dev/null +++ b/Task/State-name-puzzle/C/state-name-puzzle.c @@ -0,0 +1,106 @@ +#include +#include +#include + +#define USE_FAKES 1 + +const char *states[] = { +#if USE_FAKES + "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", +#endif + "Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", + "Delaware", + "Florida", "Georgia", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", + "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", + "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming" +}; + +int n_states = sizeof(states)/sizeof(*states); +typedef struct { unsigned char c[26]; const char *name[2]; } letters; + +void count_letters(letters *l, const char *s) +{ + int c; + if (!l->name[0]) l->name[0] = s; + else l->name[1] = s; + + while ((c = *s++)) { + if (c >= 'a' && c <= 'z') l->c[c - 'a']++; + if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; + } +} + +int lcmp(const void *aa, const void *bb) +{ + int i; + const letters *a = aa, *b = bb; + for (i = 0; i < 26; i++) + if (a->c[i] > b->c[i]) return 1; + else if (a->c[i] < b->c[i]) return -1; + return 0; +} + +int scmp(const void *a, const void *b) +{ + return strcmp(*(const char *const *)a, *(const char *const *)b); +} + +void no_dup() +{ + int i, j; + + qsort(states, n_states, sizeof(const char*), scmp); + + for (i = j = 0; i < n_states;) { + while (++i < n_states && !strcmp(states[i], states[j])); + if (i < n_states) states[++j] = states[i]; + } + + n_states = j + 1; +} + +void find_mix() +{ + int i, j, n; + letters *l, *p; + + no_dup(); + n = n_states * (n_states - 1) / 2; + p = l = calloc(n, sizeof(letters)); + + for (i = 0; i < n_states; i++) + for (j = i + 1; j < n_states; j++, p++) { + count_letters(p, states[i]); + count_letters(p, states[j]); + } + + qsort(l, n, sizeof(letters), lcmp); + + for (j = 0; j < n; j++) { + for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { + if (l[j].name[0] == l[i].name[0] + || l[j].name[1] == l[i].name[0] + || l[j].name[1] == l[i].name[1]) + continue; + printf("%s + %s => %s + %s\n", + l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); + } + } + free(l); +} + +int main(void) +{ + find_mix(); + return 0; +} diff --git a/Task/State-name-puzzle/D/state-name-puzzle.d b/Task/State-name-puzzle/D/state-name-puzzle.d new file mode 100644 index 0000000000..896ecf4dd6 --- /dev/null +++ b/Task/State-name-puzzle/D/state-name-puzzle.d @@ -0,0 +1,28 @@ +import std.stdio, std.algorithm, std.string, std.exception; + +auto states = ["Alabama", "Alaska", "Arizona", "Arkansas", +"California", "Colorado", "Connecticut", "Delaware", "Florida", +"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", +"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", +"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", +"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", +"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", +"Oregon", "Pennsylvania", "Rhode Island", "South Carolina", +"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", +"Washington", "West Virginia", "Wisconsin", "Wyoming", +// Uncomment the next line for the fake states. +// "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" +]; + +void main() { + states.length -= states.sort().uniq.copy(states).length; + + string[][const ubyte[]] smap; + foreach (immutable i, s1; states[0 .. $ - 1]) + foreach (s2; states[i + 1 .. $]) + smap[(s1 ~ s2).dup.representation.sort().release.assumeUnique] + ~= s1 ~ " + " ~ s2; + + writefln("%-(%-(%s = %)\n%)", + smap.values.sort().filter!q{ a.length > 1 }); +} diff --git a/Task/State-name-puzzle/Go/state-name-puzzle.go b/Task/State-name-puzzle/Go/state-name-puzzle.go new file mode 100644 index 0000000000..3bd6b5f752 --- /dev/null +++ b/Task/State-name-puzzle/Go/state-name-puzzle.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "unicode" +) + +var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", + "Delaware", + "Florida", "Georgia", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", + "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", + "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming"} + +func main() { + play(states) + play(append(states, + "New Kory", "Wen Kory", "York New", "Kory New", "New Kory")) +} + +func play(states []string) { + fmt.Println(len(states), "states:") + // get list of unique state names + set := make(map[string]bool, len(states)) + for _, s := range states { + set[s] = true + } + // make parallel arrays for unique state names and letter histograms + s := make([]string, len(set)) + h := make([][26]byte, len(set)) + var i int + for us := range set { + s[i] = us + for _, c := range us { + if u := uint(unicode.ToLower(c)) - 'a'; u < 26 { + h[i][u]++ + } + } + i++ + } + // use map to find matches. map key is sum of histograms of + // two different states. map value is indexes of the two states. + type pair struct { + i1, i2 int + } + m := make(map[string][]pair) + b := make([]byte, 26) // buffer for summing histograms + for i1, h1 := range h { + for i2 := i1 + 1; i2 < len(h); i2++ { + // sum histograms + for i := range b { + b[i] = h1[i] + h[i2][i] + } + k := string(b) // make key from buffer. + // now loop over any existing pairs with the same key, + // printing any where both states of this pair are different + // than the states of the existing pair + for _, x := range m[k] { + if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 { + fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2], + s[x.i1], s[x.i2]) + } + } + // store this pair in the map whether printed or not. + m[k] = append(m[k], pair{i1, i2}) + } + } +} diff --git a/Task/State-name-puzzle/Icon/state-name-puzzle-1.icon b/Task/State-name-puzzle/Icon/state-name-puzzle-1.icon new file mode 100644 index 0000000000..7dc4ff3d4e --- /dev/null +++ b/Task/State-name-puzzle/Icon/state-name-puzzle-1.icon @@ -0,0 +1,49 @@ +link strings # for csort and deletec + +procedure main(arglist) + ECsolve(S1 := getStates()) # original state names puzzle + ECsolve(S2 := getStates2()) # modified fictious names puzzle + GNsolve(S1) + GNsolve(S2) +end + +procedure ECsolve(S) # Solve challenge using equivalence classes + local T,x,y,z,i,t,s,l,m + st := &time # mark runtime + /S := getStates() # default + every insert(states := set(),deletec(map(!S),' \t')) # ignore case & space + + # Build a table containing sets of state name pairs + # keyed off of canonical form of the pair + # Use csort(s) rather than cset(s) to preserve the numbers of each letter + # Since we care not of X&Y .vs. Y&X keep only X&Y + + T := table() + every (x := !states ) & ( y := !states ) do + if z := csort(x || (x << y)) then { + /T[z] := [] + put(T[z],set(x,y)) + } + + # For each unique key (canonical pair) find intersection of all pairs + # Output is + + i := m := 0 # keys (i) and pairs (m) matched + every z := key(T) do { + s := &null + every l := !T[z] do { + /s := l + s **:= l + } + if *s = 0 then { + i +:= 1 + m +:= *T[z] + every x := !T[z] do { + #writes(i," ",z) # uncomment for equiv class and match count + every writes(!x," ") + write() + } + } + } + write("... runtime ",(&time - st)/1000.,"\n",m," matches found.") +end diff --git a/Task/State-name-puzzle/Icon/state-name-puzzle-2.icon b/Task/State-name-puzzle/Icon/state-name-puzzle-2.icon new file mode 100644 index 0000000000..aad05780af --- /dev/null +++ b/Task/State-name-puzzle/Icon/state-name-puzzle-2.icon @@ -0,0 +1,21 @@ +procedure getStates() # return list of state names +return ["Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", + "Delaware", + "Florida", "Georgia", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", + "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", + "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming"] +end + +procedure getStates2() # return list of state names + fictious states +return getStates() ||| ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"] +end diff --git a/Task/State-name-puzzle/Icon/state-name-puzzle-3.icon b/Task/State-name-puzzle/Icon/state-name-puzzle-3.icon new file mode 100644 index 0000000000..9693820ddf --- /dev/null +++ b/Task/State-name-puzzle/Icon/state-name-puzzle-3.icon @@ -0,0 +1,58 @@ +link factors + +procedure GNsolve(S) + local min, max + st := &time + equivClasses := table() + statePairs := table() + /S := getStates() + every put(states := [], map(!S)) # Make case insignificant + min := proc("min",0) # Link "factors" loses max/min functions + max := proc("max",0) # ... these statements get them back + + # Build a table of equivalence classes (all state pairs in the + # same equivalence class have the same characters in them) + # Output new pair couples *before* adding each state pair to class. + + every (state1 := |get(states)) & (state2 := !states) do { + if state1 ~== state2 then { + statePair := min(state1, state2)||":"||max(state1,state2) + if /statePairs[statePair] := set(state1, state2) then { + signature := getClassSignature(state1, state2) + /equivClasses[signature] := set() + every *(statePairs[statePair] ** # require 4 distinct states + statePairs[pair := !equivClasses[signature]]) == 0 do { + write(statePair, " and ", pair) + } + insert(equivClasses[signature], statePair) + } + } + } + + write(&errout, "Time: ", (&time-st)/1000.0) +end + +# Build a (Godel) signature identifying the equivalence class for state pair s. + +procedure getClassSignature(s1, s2) + static G + initial G := table() + /G[s1] := gn(s1) + /G[s2] := gn(s2) + return G[s1]*G[s2] +end + +procedure gn(s) # Compute the Godel number for a string (letters only) + static xlate + local p, i, z + initial { + xlate := table(1) + p := create prime() + every i := 1 to 26 do { + xlate[&lcase[i]] := xlate[&ucase[i]] := @p + } + } + z := 1 + every z *:= xlate[!s] + return z +end diff --git a/Task/State-name-puzzle/J/state-name-puzzle-1.j b/Task/State-name-puzzle/J/state-name-puzzle-1.j new file mode 100644 index 0000000000..d4aa2fcb7e --- /dev/null +++ b/Task/State-name-puzzle/J/state-name-puzzle-1.j @@ -0,0 +1,21 @@ +require'strings stats' + +states=:<;._2]0 :0-.LF + +Alabama,Alaska,Arizona,Arkansas,California,Colorado, +Connecticut,Delaware,Florida,Georgia,Hawaii,Idaho, +Illinois,Indiana,Iowa,Kansas,Kentucky,Louisiana, +Maine,Maryland,Massachusetts,Michigan,Minnesota, +Mississippi,Missouri,Montana,Nebraska,Nevada, +New Hampshire,New Jersey,New Mexico,New York, +North Carolina,North Dakota,Ohio,Oklahoma,Oregon, +Pennsylvania,Rhode Island,South Carolina, +South Dakota,Tennessee,Texas,Utah,Vermont,Virginia, +Washington,West Virginia,Wisconsin,Wyoming, +Maine,Maine,Maine,Maine,Maine,Maine,Maine,Maine, + +) + +pairUp=: (#~ matchUp)@({~ 2 comb #)@~. +matchUp=: (i.~ ~: i:~)@:(<@normalize@;"1) +normalize=: /:~@tolower@-.&' ' diff --git a/Task/State-name-puzzle/J/state-name-puzzle-2.j b/Task/State-name-puzzle/J/state-name-puzzle-2.j new file mode 100644 index 0000000000..7fc1c9882c --- /dev/null +++ b/Task/State-name-puzzle/J/state-name-puzzle-2.j @@ -0,0 +1,6 @@ + pairUp states +┌──────────────┬──────────────┐ +│North Carolina│South Dakota │ +├──────────────┼──────────────┤ +│North Dakota │South Carolina│ +└──────────────┴──────────────┘ diff --git a/Task/State-name-puzzle/J/state-name-puzzle-3.j b/Task/State-name-puzzle/J/state-name-puzzle-3.j new file mode 100644 index 0000000000..053f5db5e3 --- /dev/null +++ b/Task/State-name-puzzle/J/state-name-puzzle-3.j @@ -0,0 +1,2 @@ +isolatePairs=: ~.@matchUp2@(#~ *./@matchUp"2)@({~ 2 comb #) +matchUp2=: /:~"2@:(/:~"1)@(#~ 4=#@~.@,"2) diff --git a/Task/State-name-puzzle/J/state-name-puzzle-4.j b/Task/State-name-puzzle/J/state-name-puzzle-4.j new file mode 100644 index 0000000000..619426aed5 --- /dev/null +++ b/Task/State-name-puzzle/J/state-name-puzzle-4.j @@ -0,0 +1,96 @@ + isolatePairs pairUp 'New Kory';'Wen Kory';'York New';'Kory New';'New Kory';states +┌──────────────┬──────────────┐ +│Kory New │York New │ +├──────────────┼──────────────┤ +│New Kory │Wen Kory │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│New Kory │Wen Kory │ +├──────────────┼──────────────┤ +│New York │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New York │ +├──────────────┼──────────────┤ +│New Kory │Wen Kory │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │Wen Kory │ +├──────────────┼──────────────┤ +│New Kory │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│New Kory │York New │ +├──────────────┼──────────────┤ +│New York │Wen Kory │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New York │ +├──────────────┼──────────────┤ +│New Kory │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New Kory │ +├──────────────┼──────────────┤ +│Wen Kory │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New Kory │ +├──────────────┼──────────────┤ +│New York │Wen Kory │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New Kory │ +├──────────────┼──────────────┤ +│New York │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│New Kory │New York │ +├──────────────┼──────────────┤ +│Wen Kory │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │Wen Kory │ +├──────────────┼──────────────┤ +│New Kory │New York │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │York New │ +├──────────────┼──────────────┤ +│New Kory │New York │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │New York │ +├──────────────┼──────────────┤ +│Wen Kory │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │Wen Kory │ +├──────────────┼──────────────┤ +│New York │York New │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│Kory New │York New │ +├──────────────┼──────────────┤ +│New York │Wen Kory │ +└──────────────┴──────────────┘ + +┌──────────────┬──────────────┐ +│North Carolina│South Dakota │ +├──────────────┼──────────────┤ +│North Dakota │South Carolina│ +└──────────────┴──────────────┘ diff --git a/Task/State-name-puzzle/Java/state-name-puzzle.java b/Task/State-name-puzzle/Java/state-name-puzzle.java new file mode 100644 index 0000000000..bac068d2b7 --- /dev/null +++ b/Task/State-name-puzzle/Java/state-name-puzzle.java @@ -0,0 +1,60 @@ +import java.util.*; +import java.util.stream.*; + +public class StateNamePuzzle { + + static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", "Delaware", "Florida", + "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", + "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", + "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", + "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", + "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming", + "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; + + public static void main(String[] args) { + solve(Arrays.asList(states)); + } + + static void solve(List input) { + Map orig = input.stream().collect(Collectors.toMap( + s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); + + input = new ArrayList<>(orig.keySet()); + + Map> map = new HashMap<>(); + for (int i = 0; i < input.size() - 1; i++) { + String pair0 = input.get(i); + for (int j = i + 1; j < input.size(); j++) { + + String[] pair = {pair0, input.get(j)}; + String s = pair0 + pair[1]; + String key = Arrays.toString(s.chars().sorted().toArray()); + + List val; + if ((val = map.get(key)) == null) + val = new ArrayList<>(); + val.add(pair); + map.put(key, val); + } + } + + map.forEach((key, list) -> { + for (int i = 0; i < list.size() - 1; i++) { + String[] a = list.get(i); + for (int j = i + 1; j < list.size(); j++) { + String[] b = list.get(j); + + if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) + continue; + + System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]), + orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); + } + } + }); + } +} diff --git a/Task/State-name-puzzle/Mathematica/state-name-puzzle.math b/Task/State-name-puzzle/Mathematica/state-name-puzzle.math new file mode 100644 index 0000000000..8a883130b4 --- /dev/null +++ b/Task/State-name-puzzle/Mathematica/state-name-puzzle.math @@ -0,0 +1,13 @@ +letters[words_,n_] := Sort[Flatten[Characters /@ Take[words,n]]]; +groupSameQ[g1_, g2_] := Sort /@ Partition[g1, 2] === Sort /@ Partition[g2, 2]; +permutations[{a_, b_, c_, d_}] = Union[Permutations[{a, b, c, d}], SameTest -> groupSameQ]; + +Select[Flatten[ + permutations /@ + Subsets[Union[ToLowerCase/@{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", + "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", + "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", + "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", + "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", + "West Virginia", "Wisconsin", "Wyoming"}], {4}], 1], + letters[#, 2] === letters[#, -2] &] diff --git a/Task/State-name-puzzle/Perl-6/state-name-puzzle.pl6 b/Task/State-name-puzzle/Perl-6/state-name-puzzle.pl6 new file mode 100644 index 0000000000..85a9fed9f6 --- /dev/null +++ b/Task/State-name-puzzle/Perl-6/state-name-puzzle.pl6 @@ -0,0 +1,36 @@ +my @states = < + Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware + Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky + Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi + Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico + New_York North_Carolina North_Dakota Ohio Oklahoma Oregon Pennsylvania + Rhode_Island South_Carolina South_Dakota Tennessee Texas Utah Vermont + Virginia Washington West_Virginia Wisconsin Wyoming +>; + +say "50 states:"; +.say for anastates @states; + +say "\n54 states:"; +.say for anastates @states, < New_Kory Wen_Kory York_New Kory_New New_Kory >; + +sub anastates (*@states) { + my @s = @states.uniq».subst('_', ' '); + + my @pairs = gather for ^@s -> $i { + for $i ^..^ @s -> $j { + take [ @s[$i], @s[$j] ]; + } + } + + my $equivs = hash @pairs.classify: *.lc.comb.sort.join.trim; + + gather for $equivs.values -> @c { + for ^@c -> $i { + for $i ^..^ @c -> $j { + my $set = set @c[$i].list, @c[$j].list; + take $set.join(', ') if $set == 4; + } + } + } +} diff --git a/Task/State-name-puzzle/Perl/state-name-puzzle.pl b/Task/State-name-puzzle/Perl/state-name-puzzle.pl new file mode 100644 index 0000000000..7ad0972411 --- /dev/null +++ b/Task/State-name-puzzle/Perl/state-name-puzzle.pl @@ -0,0 +1,65 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; + + +sub uniq { + my %uniq; + undef @uniq{ @_ }; + return keys %uniq +} + + +sub puzzle { + my @states = uniq(@_); + + my %pairs; + for my $state1 (@states) { + for my $state2 (@states) { + next if $state1 le $state2; + my $both = join q(), + grep ' ' ne $_, + sort split //, + lc "$state1$state2"; + push @{ $pairs{$both} }, [ $state1, $state2 ]; + } + } + + for my $pair (keys %pairs) { + next if 2 > @{ $pairs{$pair} }; + + for my $pair1 (@{ $pairs{$pair} }) { + for my $pair2 (@{ $pairs{$pair} }) { + next if 4 > uniq(@$pair1, @$pair2) + or $pair1->[0] lt $pair2->[0]; + + say join ' = ', map { join ' + ', @$_ } $pair1, $pair2; + } + } + } +} + +my @states = ( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', + 'California', 'Colorado', 'Connecticut', 'Delaware', + 'Florida', 'Georgia', 'Hawaii', + 'Idaho', 'Illinois', 'Indiana', 'Iowa', + 'Kansas', 'Kentucky', 'Louisiana', + 'Maine', 'Maryland', 'Massachusetts', 'Michigan', + 'Minnesota', 'Mississippi', 'Missouri', 'Montana', + 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', + 'New Mexico', 'New York', 'North Carolina', 'North Dakota', + 'Ohio', 'Oklahoma', 'Oregon', + 'Pennsylvania', 'Rhode Island', + 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', + 'Utah', 'Vermont', 'Virginia', + 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', + ); + +my @fictious = ( 'New Kory', 'Wen Kory', 'York New', 'Kory New', 'New Kory' ); + +say scalar @states, ' states:'; +puzzle(@states); + +say @states + @fictious, ' states:'; +puzzle(@states, @fictious); diff --git a/Task/State-name-puzzle/PicoLisp/state-name-puzzle.l b/Task/State-name-puzzle/PicoLisp/state-name-puzzle.l new file mode 100644 index 0000000000..e58b161aa8 --- /dev/null +++ b/Task/State-name-puzzle/PicoLisp/state-name-puzzle.l @@ -0,0 +1,41 @@ +(setq *States + (group + (mapcar '((Name) (cons (clip (sort (chop (lowc Name)))) Name)) + (quote + "Alabama" "Alaska" "Arizona" "Arkansas" + "California" "Colorado" "Connecticut" + "Delaware" + "Florida" "Georgia" "Hawaii" + "Idaho" "Illinois" "Indiana" "Iowa" + "Kansas" "Kentucky" "Louisiana" + "Maine" "Maryland" "Massachusetts" "Michigan" + "Minnesota" "Mississippi" "Missouri" "Montana" + "Nebraska" "Nevada" "New Hampshire" "New Jersey" + "New Mexico" "New York" "North Carolina" "North Dakota" + "Ohio" "Oklahoma" "Oregon" + "Pennsylvania" "Rhode Island" + "South Carolina" "South Dakota" "Tennessee" "Texas" + "Utah" "Vermont" "Virginia" + "Washington" "West Virginia" "Wisconsin" "Wyoming" + "New Kory" "Wen Kory" "York New" "Kory New" "New Kory" ) ) ) ) + +(extract + '((P) + (when (cddr P) + (mapcar + '((X) + (cons + (cadr (assoc (car X) *States)) + (cadr (assoc (cdr X) *States)) ) ) + (cdr P) ) ) ) + (group + (mapcon + '((X) + (extract + '((Y) + (cons + (sort (conc (copy (caar X)) (copy (car Y)))) + (caar X) + (car Y) ) ) + (cdr X) ) ) + *States ) ) ) diff --git a/Task/State-name-puzzle/Prolog/state-name-puzzle.pro b/Task/State-name-puzzle/Prolog/state-name-puzzle.pro new file mode 100644 index 0000000000..647255bddf --- /dev/null +++ b/Task/State-name-puzzle/Prolog/state-name-puzzle.pro @@ -0,0 +1,70 @@ +state_name_puzzle :- + L = ["Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", + "Delaware", + "Florida", "Georgia", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", + "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", + "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming", + "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"], + + maplist(goedel, L, R), + + % sort remove duplicates + sort(R, RS), + + study(RS). + +study([]). + +study([V-Word|T]) :- + study_1_Word(V-Word, T, T), + study(T). + + +study_1_Word(_, [], _). +study_1_Word(V1-W1, [V2-W2 | T1], T) :- + TT is V1+V2, + study_2_Word(W1, W2, TT, T), + study_1_Word(V1-W1, T1, T). + +study_2_Word(_W1, _W2, _TT, []). + +study_2_Word(W1, W2, TT, [V3-W3 | T]) :- + ( W2 \= W3 -> study_3_Word(W1, W2, TT, V3-W3, T); true), + study_2_Word(W1, W2, TT, T). + +study_3_Word(_W1, _W2, _TT, _V3-_W3, []). + +study_3_Word(W1, W2, TT, V3-W3, [V4-W4|T]) :- + TT1 is V3 + V4, + ( TT1 < TT -> study_3_Word(W1, W2, TT, V3-W3, T) + ; (TT1 = TT -> ( W4 \= W2 -> format('~w & ~w with ~w & ~w~n', [W1, W2, W3, W4]) + ; true), + study_3_Word(W1, W2, TT, V3-W3, T)) + ; true). + +% Compute a Goedel number for the word +goedel(Word, Goedel-A) :- + name(A, Word), + downcase_atom(A, Amin), + atom_codes(Amin, LA), + compute_Goedel(LA, 0, Goedel). + +compute_Goedel([], G, G). + +compute_Goedel([32|T], GC, GF) :- + compute_Goedel(T, GC, GF). + +compute_Goedel([H|T], GC, GF) :- + Ind is H - 97, + GC1 is GC + 26 ** Ind, + compute_Goedel(T, GC1, GF). diff --git a/Task/State-name-puzzle/Python/state-name-puzzle.py b/Task/State-name-puzzle/Python/state-name-puzzle.py new file mode 100644 index 0000000000..d9ef59bc4c --- /dev/null +++ b/Task/State-name-puzzle/Python/state-name-puzzle.py @@ -0,0 +1,26 @@ +from collections import defaultdict + +states = ["Alabama", "Alaska", "Arizona", "Arkansas", +"California", "Colorado", "Connecticut", "Delaware", "Florida", +"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", +"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", +"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", +"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", +"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", +"Oregon", "Pennsylvania", "Rhode Island", "South Carolina", +"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", +"Washington", "West Virginia", "Wisconsin", "Wyoming", +# Uncomment the next line for the fake states. +# "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" +] + +states = sorted(set(states)) + +smap = defaultdict(list) +for i, s1 in enumerate(states[:-1]): + for s2 in states[i + 1:]: + smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2) + +for pairs in sorted(smap.itervalues()): + if len(pairs) > 1: + print " = ".join(pairs) diff --git a/Task/State-name-puzzle/README b/Task/State-name-puzzle/README new file mode 100644 index 0000000000..3b6b04c2e9 --- /dev/null +++ b/Task/State-name-puzzle/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/State_name_puzzle diff --git a/Task/State-name-puzzle/REXX/state-name-puzzle.rexx b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx new file mode 100644 index 0000000000..c80dc257eb --- /dev/null +++ b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx @@ -0,0 +1,88 @@ +/*REXX pgm: state name puzzle, rearrange 2 state's names──►2 new states.*/ +!='Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia,', + 'Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, ', + 'Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico,', + 'New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,', + 'South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming' + +parse arg xtra; !=! ',' xtra /*add optional fictitious ones*/ +@abcU='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; !=space(!) /*ABCs, state list*/ +deads=0; dups=0; L.=0; !orig=!; z=0; @@.= /*initialize stuff*/ + + do de=0 to 1; !=!orig; @.= /*use the original state list.*/ + + do states=0 until !=='' /*parse 'til da cows come home*/ + parse var ! x ',' !; x=space(x) /*remove all blanks from state*/ + if @.x\=='' then do /*state was already specified.*/ + if de then iterate /*don't tell error if 2nd pass*/ + dups=dups+1 /*bump the duplicate counter. */ + say 'ignoring the 2nd naming of the state: ' x + iterate + end + @.x=x /*indicate this state exists. */ + y=space(x,0); upper y; yLen=length(y) + + if de then do + do j=1 for yLen /*see if it's a dead-end state*/ + _=substr(y,j,1) /* _ is some state character. */ + if L._\==1 then iterate /*if count ¬1, state is O.K. */ + say 'removing dead-end state [which has the letter ' _"]: " x + deads=deads+1 /*bump # of dead-ends states. */ + iterate states + end /*j*/ + z=z+1 /*bump counter of the states. */ + #.z=y; ##.z=x /*assign state name; &original*/ + end + else do k=1 for yLen /*inventorize state's letters.*/ + _=substr(y,k,1); L._=L._+1 /*count each letter in state. */ + end /*k*/ + + end /*states*/ + end /*de*/ + +say; do i=1 for z /*list states in order given. */ + say right(i,9) ##.i + end /*i*/ + + say; say z 'state name's(z) "are useable." +if dups \==0 then say dups 'duplicate of a state's(dups) 'ignored.' +if deads\==0 then say deads 'dead-end state's(deads) 'deleted.' +say +sols=0 /*number of solutions found. */ + + do j=1 for z /*◄────────────────────────────────────────────────┐ */ + /*look for mix&match states. │ */ + do k=j+1 to z /* ◄─── state K, state J ►──┘ */ + if #.j<<#.k then JK=#.j || #.k /*proper order.*/ + else JK=#.k || #.j /*state J || K */ + + do m=1 for z; if m==j | m==k then iterate /*no overlaps. */ + if verify(#.m,jk)\==0 then iterate /*is possible? */ + nJK=elider(JK,#.m) /*new JK, after eliding #.m chars.*/ + + do n=m+1 to z; if n==j | n==k then iterate /*no overlaps. */ + if verify(#.n,nJK)\==0 then iterate /*is possible? */ + if elider(nJK,#.n)\=='' then iterate /*leftovers ? */ + if #.m<<#.n then MN=#.m || #.n /*proper order.*/ + else MN=#.n || #.m /*state M || N */ + if @@.JK.MN\=='' | @@.MN.JK\=='' then iterate /*done before? */ + say 'found: ' ##.j',' ##.k " ──► " ##.m',' ##.n + @@.JK.MN=1 /*indicate this solution as found.*/ + sols=sols+1 /*bump the number of solutions. */ + end /*n*/ + end /*m*/ + end /*k*/ + end /*j*/ +say /*show blank line; easier reading*/ +if sols==0 then sols='No' /*use mucher gooder (sic) English*/ +say sols 'solution's(sols) "found." /*display the number of solutions*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────ELIDER─────────────────────────────*/ +elider: parse arg hay,pins /*remove letters (pins) from hay.*/ + do e=1 for length(pins); _=substr(pins,e,1) + p=pos(_,hay); if p==0 then iterate + hay=overlay(' ',hay,p) /*remove a letter.*/ + end /*e*/ +return space(hay,0) /*remove blanks. */ +/*──────────────────────────────────S subroutine────────────────────────*/ +s: if arg(1)==1 then return arg(3);return word(arg(2) 's',1) /*plurals.*/ diff --git a/Task/State-name-puzzle/Racket/state-name-puzzle-1.rkt b/Task/State-name-puzzle/Racket/state-name-puzzle-1.rkt new file mode 100644 index 0000000000..55465e57b6 --- /dev/null +++ b/Task/State-name-puzzle/Racket/state-name-puzzle-1.rkt @@ -0,0 +1,30 @@ +#lang racket +(define states + (list->set + (map string-downcase + '("Alabama" "Alaska" "Arizona" "Arkansas" + "California" "Colorado" "Connecticut" + "Delaware" + "Florida" "Georgia" "Hawaii" + "Idaho" "Illinois" "Indiana" "Iowa" + "Kansas" "Kentucky" "Louisiana" + "Maine" "Maryland" "Massachusetts" "Michigan" + "Minnesota" "Mississippi" "Missouri" "Montana" + "Nebraska""Nevada" "New Hampshire" "New Jersey" + "New Mexico" "New York" "North Carolina" "North Dakota" + "Ohio" "Oklahoma" "Oregon" + "Pennsylvania" "Rhode Island" + "South Carolina" "South Dakota" "Tennessee" "Texas" + "Utah" "Vermont" "Virginia" + "Washington" "West Virginia" "Wisconsin" "Wyoming" + ; "New Kory" "Wen Kory" "York New" "Kory New" "New Kory" + )))) + +(define (canon s t) + (sort (append (string->list s) (string->list t)) char (λ(states) (displayln (~v states (list s1 s2))))])) diff --git a/Task/State-name-puzzle/Racket/state-name-puzzle-2.rkt b/Task/State-name-puzzle/Racket/state-name-puzzle-2.rkt new file mode 100644 index 0000000000..b50be07221 --- /dev/null +++ b/Task/State-name-puzzle/Racket/state-name-puzzle-2.rkt @@ -0,0 +1 @@ +'("north dakota" "south carolina") '("north carolina" "south dakota") diff --git a/Task/State-name-puzzle/Ruby/state-name-puzzle.rb b/Task/State-name-puzzle/Ruby/state-name-puzzle.rb new file mode 100644 index 0000000000..6d09126e47 --- /dev/null +++ b/Task/State-name-puzzle/Ruby/state-name-puzzle.rb @@ -0,0 +1,45 @@ +require 'set' + +# 26 prime numbers +Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, + 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] +States = [ + "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", + "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", + "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", + "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", + "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", + "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", + "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming" +] + +def print_answer(states) + # find goedel numbers for all pairs of states + goedel = lambda {|str| str.chars.map {|c| Primes[c.ord - 65]}.reduce(:*)} + pairs = Hash.new {|h,k| h[k] = Array.new} + map = states.uniq.map {|state| [state, goedel[state.upcase.delete("^A-Z")]]} + map.combination(2) {|(s1,g1), (s2,g2)| pairs[g1 * g2] << [s1, s2]} + + # find pairs without duplicates + result = [] + pairs.values.select {|val| val.length > 1}.each do |list_of_pairs| + list_of_pairs.combination(2) do |pair1, pair2| + if Set[*pair1, *pair2].length == 4 + result << [pair1, pair2] + end + end + end + + # output the results + result.each_with_index do |(pair1, pair2), i| + puts "%d\t%s\t%s" % [i+1, pair1.join(', '), pair2.join(', ')] + end +end + +puts "real states only" +print_answer(States) +puts "" +puts "with fictional states" +print_answer(States + ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]) diff --git a/Task/State-name-puzzle/Scala/state-name-puzzle.scala b/Task/State-name-puzzle/Scala/state-name-puzzle.scala new file mode 100644 index 0000000000..42d5aa5982 --- /dev/null +++ b/Task/State-name-puzzle/Scala/state-name-puzzle.scala @@ -0,0 +1,26 @@ +object StateNamePuzzle extends App { + // Logic: + def disjointPairs(pairs: Seq[Set[String]]) = + for (a <- pairs; b <- pairs; if a.intersect(b).isEmpty) yield Set(a,b) + + def anagramPairs(words: Seq[String]) = + (for (a <- words; b <- words; if a != b) yield Set(a, b)) // all pairs + .groupBy(_.mkString.toLowerCase.replaceAll("[^a-z]", "").sorted) // grouped anagram pairs + .values.map(disjointPairs).flatMap(_.distinct) // unique non-overlapping anagram pairs + + // Test: + val states = List( + "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", + "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", + "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", + "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", + "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", + "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", + "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", + "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming" + ) + + println(anagramPairs(states).map(_.map(_ mkString " + ") mkString " = ") mkString "\n") +} diff --git a/Task/State-name-puzzle/Tcl/state-name-puzzle.tcl b/Task/State-name-puzzle/Tcl/state-name-puzzle.tcl new file mode 100644 index 0000000000..f4a2aec96c --- /dev/null +++ b/Task/State-name-puzzle/Tcl/state-name-puzzle.tcl @@ -0,0 +1,67 @@ +package require Tcl 8.5 +# Gödel number generator +proc goedel s { + set primes { + 2 3 5 7 11 13 17 19 23 29 31 37 41 + 43 47 53 59 61 67 71 73 79 83 89 97 101 + } + set n 1 + foreach c [split [string toupper $s] ""] { + if {![string is alpha $c]} continue + set n [expr {$n * [lindex $primes [expr {[scan $c %c] - 65}]]}] + } + return $n +} +# Calculates the pairs of states +proc groupStates {stateList} { + set stateList [lsort -unique $stateList] + foreach state1 $stateList { + foreach state2 $stateList { + if {$state1 >= $state2} continue + dict lappend group [goedel $state1$state2] [list $state1 $state2] + } + } + foreach g [dict values $group] { + if {[llength $g] > 1} { + foreach p1 $g { + foreach p2 $g { + if {$p1 < $p2 && [unshared $p1 $p2]} { + lappend result [list $p1 $p2] + } + } + } + } + } + return $result +} +proc unshared args { + foreach p $args { + foreach a $p {incr s($a)} + } + expr {[array size s] == [llength $args]*2} +} +# Pretty printer for state name pair lists +proc printPairs {title groups} { + foreach group $groups { + puts "$title Group #[incr count]" + foreach statePair $group { + puts "\t[join $statePair {, }]" + } + } +} + +set realStates { + "Alabama" "Alaska" "Arizona" "Arkansas" "California" "Colorado" + "Connecticut" "Delaware" "Florida" "Georgia" "Hawaii" "Idaho" "Illinois" + "Indiana" "Iowa" "Kansas" "Kentucky" "Louisiana" "Maine" "Maryland" + "Massachusetts" "Michigan" "Minnesota" "Mississippi" "Missouri" "Montana" + "Nebraska" "Nevada" "New Hampshire" "New Jersey" "New Mexico" "New York" + "North Carolina" "North Dakota" "Ohio" "Oklahoma" "Oregon" "Pennsylvania" + "Rhode Island" "South Carolina" "South Dakota" "Tennessee" "Texas" "Utah" + "Vermont" "Virginia" "Washington" "West Virginia" "Wisconsin" "Wyoming" +} +printPairs "Real States" [groupStates $realStates] +set falseStates { + "New Kory" "Wen Kory" "York New" "Kory New" "New Kory" +} +printPairs "Real and False States" [groupStates [concat $realStates $falseStates]] diff --git a/Task/Statistics-Basic/00DESCRIPTION b/Task/Statistics-Basic/00DESCRIPTION new file mode 100644 index 0000000000..cecff76faf --- /dev/null +++ b/Task/Statistics-Basic/00DESCRIPTION @@ -0,0 +1,25 @@ +Statistics is all about large groups of numbers. +When talking about a set of sampled data, most frequently used is their [[wp:Mean|mean value]] and [[wp:Standard_deviation|standard deviation (stddev)]]. +If you have set of data x_i where i = 1, 2, \ldots, n\,\!, the mean is \bar{x}\equiv {1\over n}\sum_i x_i, while the stddev is \sigma\equiv\sqrt{{1\over n}\sum_i \left(x_i - \bar x \right)^2}. + +When examining a large quantity of data, one often uses a [[wp:Histogram|histogram]], which shows the counts of data samples falling into a prechosen set of intervals (or bins). +When plotted, often as bar graphs, it visually indicates how often each data value occurs. + +'''Task''' Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range. +Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev. +Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like. +Show a histogram of any of these sets. +Do you notice some patterns about the standard deviation? + +'''Extra''' Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.) + +;Hint: +For a finite population with equal probabilities at all points, one can derive: + +:\overline{(x - \overline{x})^2} = \overline{x^2} - \overline{x}^2 + +Or, more verbosely: + +: +\frac{1}{N}\sum_{i=1}^N(x_i-\overline{x})^2 = \frac{1}{N} \left(\sum_{i=1}^N x_i^2\right) - \overline{x}^2. + diff --git a/Task/Statistics-Basic/00META.yaml b/Task/Statistics-Basic/00META.yaml new file mode 100644 index 0000000000..aed8ff126a --- /dev/null +++ b/Task/Statistics-Basic/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Mathematics diff --git a/Task/Statistics-Basic/Ada/statistics-basic-1.ada b/Task/Statistics-Basic/Ada/statistics-basic-1.ada new file mode 100644 index 0000000000..d48ed0a579 --- /dev/null +++ b/Task/Statistics-Basic/Ada/statistics-basic-1.ada @@ -0,0 +1,63 @@ +with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random, + Ada.Numerics.Generic_Elementary_Functions; + +procedure Basic_Stat is + + package FRG renames Ada.Numerics.Float_Random; + package TIO renames Ada.Text_IO; + + type Counter is range 0 .. 2**31-1; + type Result_Array is array(Natural range <>) of Counter; + + package FIO is new TIO.Float_IO(Float); + + procedure Put_Histogram(R: Result_Array; Scale, Full: Counter) is + begin + for I in R'Range loop + FIO.Put(Float'Max(0.0, Float(I)/10.0 - 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(".."); + FIO.Put(Float'Min(1.0, Float(I)/10.0 + 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(": "); + for J in 1 .. (R(I)* Scale)/Full loop + Ada.Text_IO.Put("X"); + end loop; + Ada.Text_IO.New_Line; + end loop; + end Put_Histogram; + + procedure Put_Mean_Et_Al(Sample_Size: Counter; + Val_Sum, Square_Sum: Float) is + Mean: constant Float := Val_Sum / Float(Sample_Size); + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + begin + TIO.Put("Mean: "); + FIO.Put(Mean, Fore => 1, Aft => 5, Exp => 0); + TIO.Put(", Standard Deviation: "); + FIO.Put(Math.Sqrt(abs(Square_Sum / Float(Sample_Size) + - (Mean * Mean))), Fore => 1, Aft => 5, Exp => 0); + TIO.New_Line; + end Put_Mean_Et_Al; + + N: Counter := Counter'Value(Ada.Command_Line.Argument(1)); + Gen: FRG.Generator; + Results: Result_Array(0 .. 10) := (others => 0); + X: Float; + Val_Sum, Squ_Sum: Float := 0.0; + +begin + FRG.Reset(Gen); + for I in 1 .. N loop + X := FRG.Random(Gen); + Val_Sum := Val_Sum + X; + Squ_Sum := Squ_Sum + X*X; + declare + Index: Integer := Integer(X*10.0); + begin + Results(Index) := Results(Index) + 1; + end; + end loop; + TIO.Put_Line("After sampling" & Counter'Image(N) & " random numnbers: "); + Put_Histogram(Results, Scale => 600, Full => N); + TIO.New_Line; + Put_Mean_Et_Al(Sample_Size => N, Val_Sum => Val_Sum, Square_Sum => Squ_Sum); +end Basic_Stat; diff --git a/Task/Statistics-Basic/Ada/statistics-basic-2.ada b/Task/Statistics-Basic/Ada/statistics-basic-2.ada new file mode 100644 index 0000000000..407ad5d551 --- /dev/null +++ b/Task/Statistics-Basic/Ada/statistics-basic-2.ada @@ -0,0 +1,77 @@ +with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random, + Ada.Numerics.Generic_Elementary_Functions; + +procedure Long_Basic_Stat is + + package FRG renames Ada.Numerics.Float_Random; + package TIO renames Ada.Text_IO; + + type Counter is range 0 .. 2**63-1; + type Result_Array is array(Natural range <>) of Counter; + type High_Precision is digits 15; + + package FIO is new TIO.Float_IO(Float); + + procedure Put_Histogram(R: Result_Array; Scale, Full: Counter) is + begin + for I in R'Range loop + FIO.Put(Float'Max(0.0, Float(I)/10.0 - 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(".."); + FIO.Put(Float'Min(1.0, Float(I)/10.0 + 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(": "); + for J in 1 .. (R(I)* Scale)/Full loop + Ada.Text_IO.Put("X"); + end loop; + Ada.Text_IO.New_Line; + end loop; + end Put_Histogram; + + procedure Put_Mean_Et_Al(Sample_Size: Counter; + Val_Sum, Square_Sum: Float) is + Mean: constant Float := Val_Sum / Float(Sample_Size); + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + begin + TIO.Put("Mean: "); + FIO.Put(Mean, Fore => 1, Aft => 5, Exp => 0); + TIO.Put(", Standard Deviation: "); + FIO.Put(Math.Sqrt(abs(Square_Sum / Float(Sample_Size) + - (Mean * Mean))), Fore => 1, Aft => 5, Exp => 0); + TIO.New_Line; + end Put_Mean_Et_Al; + + N: Counter := Counter'Value(Ada.Command_Line.Argument(1)); + Gen: FRG.Generator; + Results: Result_Array(0 .. 10) := (others => 0); + X: Float; + Val_Sum, Squ_Sum: High_Precision := 0.0; + +begin + FRG.Reset(Gen); + for Outer in 1 .. 1000 loop + for I in 1 .. N/1000 loop + X := FRG.Random(Gen); + Val_Sum := Val_Sum + High_Precision(X); + Squ_Sum := Squ_Sum + High_Precision(X)*High_Precision(X); + declare + Index: Integer := Integer(X*10.0); + begin + Results(Index) := Results(Index) + 1; + end; + end loop; + if Outer mod 50 = 0 then + TIO.New_Line(1); + TIO.Put_Line(Integer'Image(Outer/10) &"% done; current results:"); + Put_Mean_Et_Al(Sample_Size => (Counter(Outer)*N)/1000, + Val_Sum => Float(Val_Sum), + Square_Sum => Float(Squ_Sum)); + else + Ada.Text_IO.Put("."); + end if; + end loop; + TIO.New_Line(4); + TIO.Put_Line("After sampling" & Counter'Image(N) & " random numnbers: "); + Put_Histogram(Results, Scale => 600, Full => N); + TIO.New_Line; + Put_Mean_Et_Al(Sample_Size => N, + Val_Sum => Float(Val_Sum), Square_Sum => Float(Squ_Sum)); +end Long_Basic_Stat; diff --git a/Task/Statistics-Basic/C/statistics-basic.c b/Task/Statistics-Basic/C/statistics-basic.c new file mode 100644 index 0000000000..8502e174fd --- /dev/null +++ b/Task/Statistics-Basic/C/statistics-basic.c @@ -0,0 +1,102 @@ +#include +#include +#include +#include + +#define n_bins 10 + +double rand01() { return rand() / (RAND_MAX + 1.0); } + +double avg(int count, double *stddev, int *hist) +{ + double x[count]; + double m = 0, s = 0; + + for (int i = 0; i < n_bins; i++) hist[i] = 0; + for (int i = 0; i < count; i++) { + m += (x[i] = rand01()); + hist[(int)(x[i] * n_bins)] ++; + } + + m /= count; + for (int i = 0; i < count; i++) + s += x[i] * x[i]; + *stddev = sqrt(s / count - m * m); + return m; +} + +void hist_plot(int *hist) +{ + int max = 0, step = 1; + double inc = 1.0 / n_bins; + + for (int i = 0; i < n_bins; i++) + if (hist[i] > max) max = hist[i]; + + /* scale if numbers are too big */ + if (max >= 60) step = (max + 59) / 60; + + for (int i = 0; i < n_bins; i++) { + printf("[%5.2g,%5.2g]%5d ", i * inc, (i + 1) * inc, hist[i]); + for (int j = 0; j < hist[i]; j += step) + printf("#"); + printf("\n"); + } +} + +/* record for moving average and stddev. Values kept are sums and sum data^2 + * to avoid excessive precision loss due to divisions, but some loss is inevitable + */ +typedef struct { + uint64_t size; + double sum, x2; + uint64_t hist[n_bins]; +} moving_rec; + +void moving_avg(moving_rec *rec, double *data, int count) +{ + double sum = 0, x2 = 0; + /* not adding data directly to the sum in case both recorded sum and + * count of this batch are large; slightly less likely to lose precision*/ + for (int i = 0; i < count; i++) { + sum += data[i]; + x2 += data[i] * data[i]; + rec->hist[(int)(data[i] * n_bins)]++; + } + + rec->sum += sum; + rec->x2 += x2; + rec->size += count; +} + +int main() +{ + double m, stddev; + int hist[n_bins], samples = 10; + + while (samples <= 10000) { + m = avg(samples, &stddev, hist); + printf("size %5d: %g %g\n", samples, m, stddev); + samples *= 10; + } + + printf("\nHistograph:\n"); + hist_plot(hist); + + printf("\nMoving average:\n N Mean Sigma\n"); + moving_rec rec = { 0, 0, 0, {0} }; + double data[100]; + for (int i = 0; i < 10000; i++) { + for (int j = 0; j < 100; j++) data[j] = rand01(); + + moving_avg(&rec, data, 100); + + if ((i % 1000) == 999) { + printf("%4lluk %f %f\n", + rec.size/1000, + rec.sum / rec.size, + sqrt(rec.x2 * rec.size - rec.sum * rec.sum)/rec.size + ); + } + } +} diff --git a/Task/Statistics-Basic/CoffeeScript/statistics-basic.coffee b/Task/Statistics-Basic/CoffeeScript/statistics-basic.coffee new file mode 100644 index 0000000000..89625a2760 --- /dev/null +++ b/Task/Statistics-Basic/CoffeeScript/statistics-basic.coffee @@ -0,0 +1,36 @@ +generate_statistics = (n) -> + hist = {} + + update_hist = (r) -> + hist[Math.floor 10*r] ||= 0 + hist[Math.floor 10*r] += 1 + + sum = 0 + sum_squares = 0.0 + + for i in [1..n] + r = Math.random() + sum += r + sum_squares += r*r + update_hist r + mean = sum / n + stddev = Math.sqrt((sum_squares / n) - mean*mean) + + [n, mean, stddev, hist] + +display_statistics = (n, mean, stddev, hist) -> + console.log "-- Stats for sample size #{n}" + console.log "mean: #{mean}" + console.log "sdev: #{stddev}" + for x, cnt of hist + bars = repeat "=", Math.floor(cnt*300/n) + console.log "#{x/10}: #{bars} #{cnt}" + +repeat = (c, n) -> + s = '' + s += c for i in [1..n] + s + +for n in [100, 1000, 10000, 1000000] + [n, mean, stddev, hist] = generate_statistics n + display_statistics n, mean, stddev, hist diff --git a/Task/Statistics-Basic/D/statistics-basic.d b/Task/Statistics-Basic/D/statistics-basic.d new file mode 100644 index 0000000000..4fea43d006 --- /dev/null +++ b/Task/Statistics-Basic/D/statistics-basic.d @@ -0,0 +1,45 @@ +import std.stdio, std.algorithm, std.array, std.typecons, + std.range, std.exception; + +auto meanStdDev(R)(R numbers) /*nothrow*/ @safe /*@nogc*/ { + if (numbers.empty) + return tuple(0.0L, 0.0L); + + real sx = 0.0, sxx = 0.0; + ulong n; + foreach (x; numbers) { + sx += x; + sxx += x ^^ 2; + n++; + } + return tuple(sx / n, (n * sxx - sx ^^ 2) ^^ 0.5L / n); +} + +void showHistogram01(R)(R numbers) /*@safe*/ { + enum maxWidth = 50; // N. characters. + ulong[10] bins; + foreach (immutable x; numbers) { + immutable index = cast(size_t)(x * bins.length); + enforce(index >= 0 && index < bins.length); + bins[index]++; + } + immutable real maxFreq = bins.reduce!max; + + foreach (immutable n, immutable i; bins) + writefln(" %3.1f: %s", n / real(bins.length), + replicate("*", cast(int)(i / maxFreq * maxWidth))); + writeln; +} + +version (statistics_basic_main) { + void main() @safe { + import std.random; + + foreach (immutable p; 1 .. 7) { + auto n = iota(10L ^^ p).map!(_ => uniform(0.0L, 1.0L)); + writeln(10L ^^ p, " numbers:"); + writefln(" Mean: %8.6f, SD: %8.6f", n.meanStdDev.tupleof); + n.showHistogram01; + } + } +} diff --git a/Task/Statistics-Basic/Dart/statistics-basic.dart b/Task/Statistics-Basic/Dart/statistics-basic.dart new file mode 100644 index 0000000000..af84ab5fa6 --- /dev/null +++ b/Task/Statistics-Basic/Dart/statistics-basic.dart @@ -0,0 +1,99 @@ +/* Import math library to get: + * 1) Square root function : Math.sqrt(x) + * 2) Power function : Math.pow(base, exponent) + * 3) Random number generator : Math.Random() + */ +import 'dart:math' as Math show sqrt, pow, Random; + +// Returns average/mean of a list of numbers +num mean(List l) => l.reduce((num value,num element)=>value+element)/l.length; + +// Returns standard deviation of a list of numbers +num stdev(List l) => Math.sqrt((1/l.length)*l.map((num x)=>x*x).reduce((num value,num element) => value+element) - Math.pow(mean(l),2)); + +/* CODE TO PRINT THE HISTOGRAM STARTS HERE + * + * Histogram has ten fields, one for every tenth between 0 and 1 + * To do this, we save the histogram as a global variable + * that will hold the number of occurences of each tenth in the sample + */ +List histogram = new List.filled(10,0); + +/* + * METHOD TO CREATE A RANDOM SAMPLE OF n NUMBERS (Returns a list) + * + * While creating each value, this method also increments the + * appropriate index of the histogram + */ +List randomsample(num n){ + List l = new List(n); + histogram = new List.filled(10,0); + num random = new Math.Random(); + for (int i = 0; i < n; i++){ + l[i] = random.nextDouble(); + histogram[conv(l[i])] += 1; + } + return l; +} + +/* + * METHOD TO RETURN A STRING OF n ASTERIXES (yay ASCII art) + */ +String stars(num n){ + String s = ''; + for (int i = 0; i < n; i++){ + s = s + '*'; + } + return s; +} + +/* + * METHOD TO DRAW THE HISTOGRAM + * 1) Get to total for all the values in the histogram + * 2) For every field in the histogram: + * a) Compute the frequency for every field in the histogram + * b) Print the frequency as asterixes + */ +void drawhistogram(){ + int total = histogram.reduce((num element,num value)=>element+value); + double freq; + for (int i = 0; i < 10; i++){ + freq = histogram[i]/total; + print('${i/10} - ${(i+1)/10} : ' + stars(conv(30*freq))); + } +} + +/* HELPER METHOD: + * converts values between 0-1 to integers between 0-9 inclusive + * useful to figure out which random value generated + * corresponds to which field in the histogram + */ +int conv(num i) => (10*i).floor(); + + +/* MAIN FUNCTION + * + * Create 5 histograms and print the mean and standard deviation for each: + * 1) Sample Size = 100 + * 2) Sample Size = 1000 + * 3) Sample Size = 10000 + * 4) Sample Size = 100000 + * 5) Sample Size = 1000000 + * + */ +void main(){ + List l; + num m; + num s; + List sampleSizes = [100,1000,10000,100000,1000000]; + for (int samplesize in sampleSizes){ + print('--------------- Sample size $samplesize ----------------'); + l = randomsample(samplesize); + m = mean(l); + s = stdev(l); + drawhistogram(); + print(''); + print('mean: ${m.toStringAsPrecision(8)} standard deviation: ${s.toStringAsPrecision(8)}'); + print(''); + } +} diff --git a/Task/Statistics-Basic/Fortran/statistics-basic.f b/Task/Statistics-Basic/Fortran/statistics-basic.f new file mode 100644 index 0000000000..e1f5d67140 --- /dev/null +++ b/Task/Statistics-Basic/Fortran/statistics-basic.f @@ -0,0 +1,36 @@ +program basic_stats + implicit none + + integer, parameter :: i64 = selected_int_kind(18) + integer, parameter :: r64 = selected_real_kind(15) + integer(i64), parameter :: samples = 1000000000_i64 + + real(r64) :: r + real(r64) :: mean, stddev + real(r64) :: sumn = 0, sumnsq = 0 + integer(i64) :: n = 0 + integer(i64) :: bin(10) = 0 + integer :: i, ind + + call random_seed + + n = 0 + do while(n <= samples) + call random_number(r) + ind = r * 10 + 1 + bin(ind) = bin(ind) + 1_i64 + sumn = sumn + r + sumnsq = sumnsq + r*r + n = n + 1_i64 + end do + + mean = sumn / n + stddev = sqrt(sumnsq/n - mean*mean) + write(*, "(a, i0)") "sample size = ", samples + write(*, "(a, f17.15)") "Mean : ", mean, + write(*, "(a, f17.15)") "Stddev : ", stddev + do i = 1, 10 + write(*, "(f3.1, a, a)") real(i)/10.0, ": ", repeat("=", int(bin(i)*500/samples)) + end do + +end program diff --git a/Task/Statistics-Basic/Go/statistics-basic-1.go b/Task/Statistics-Basic/Go/statistics-basic-1.go new file mode 100644 index 0000000000..3c37e5eeff --- /dev/null +++ b/Task/Statistics-Basic/Go/statistics-basic-1.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "strings" +) + +func main() { + sample(100) + sample(1000) + sample(10000) +} + +func sample(n int) { + // generate data + d := make([]float64, n) + for i := range d { + d[i] = rand.Float64() + } + // show mean, standard deviation + var sum, ssq float64 + for _, s := range d { + sum += s + ssq += s * s + } + fmt.Println(n, "numbers") + m := sum / float64(n) + fmt.Println("Mean: ", m) + fmt.Println("Stddev:", math.Sqrt(ssq/float64(n)-m*m)) + // show histogram + h := make([]int, 10) + for _, s := range d { + h[int(s*10)]++ + } + for _, c := range h { + fmt.Println(strings.Repeat("*", c*205/int(n))) + } + fmt.Println() +} diff --git a/Task/Statistics-Basic/Go/statistics-basic-2.go b/Task/Statistics-Basic/Go/statistics-basic-2.go new file mode 100644 index 0000000000..8d2ce44a87 --- /dev/null +++ b/Task/Statistics-Basic/Go/statistics-basic-2.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "strings" +) + +func main() { + bigSample(1e7) +} + +func bigSample(n int64) { + sum, ssq, h := reduce(0, n) + // compute final statistics and output as above + fmt.Println(n, "numbers") + m := sum / float64(n) + fmt.Println("Mean: ", m) + fmt.Println("Stddev:", math.Sqrt(ssq/float64(n)-m*m)) + for _, c := range h { + fmt.Println(strings.Repeat("*", c*205/int(n))) + } + fmt.Println() +} + +const threshold = 1e6 + +func reduce(start, end int64) (sum, ssq float64, h []int) { + n := end - start + if n < threshold { + d := getSegment(start, end) + return computeSegment(d) + } + // map to two sub problems + half := (start + end) / 2 + sum1, ssq1, h1 := reduce(start, half) + sum2, ssq2, h2 := reduce(half, end) + // combine results + for i, c := range h2 { + h1[i] += c + } + return sum1 + sum2, ssq1 + ssq2, h1 +} + +func getSegment(start, end int64) []float64 { + d := make([]float64, end-start) + for i := range d { + d[i] = rand.Float64() + } + return d +} + +func computeSegment(d []float64) (sum, ssq float64, h []int) { + for _, s := range d { + sum += s + ssq += s * s + } + h = make([]int, 10) + for _, s := range d { + h[int(s*10)]++ + } + return +} diff --git a/Task/Statistics-Basic/Icon/statistics-basic.icon b/Task/Statistics-Basic/Icon/statistics-basic.icon new file mode 100644 index 0000000000..b5aea4493f --- /dev/null +++ b/Task/Statistics-Basic/Icon/statistics-basic.icon @@ -0,0 +1,26 @@ +procedure main(A) + +W := 50 # avg width for histogram bar +B := 10 # histogram bins +if *A = 0 then put(A,100) # 100 if none specified + +while N := get(A) do { # once per argument + write("\nN=",N) + + N := 0 < integer(N) | next # skip if invalid + + stddev() # reset + m := 0. + H := list(B,0) # Histogram of + every i := 1 to N do { # calc running ... + s := stddev(r := ?0) # ... std dev + m +:= r/N # ... mean + H[integer(*H*r)+1] +:= 1 # ... histogram + } + + write("mean=",m) + write("stddev=",s) + every i := 1 to *H do # show histogram + write(right(real(i)/*H,5)," : ",repl("*",integer(*H*50./N*H[i]))) + } +end diff --git a/Task/Statistics-Basic/J/statistics-basic-1.j b/Task/Statistics-Basic/J/statistics-basic-1.j new file mode 100644 index 0000000000..ff67505f77 --- /dev/null +++ b/Task/Statistics-Basic/J/statistics-basic-1.j @@ -0,0 +1,7 @@ + require'statfns' + (mean,stddev) ?1000#0 +0.484669 0.287482 + (mean,stddev) ?10000#0 +0.503642 0.290777 + (mean,stddev) ?100000#0 +0.499677 0.288726 diff --git a/Task/Statistics-Basic/J/statistics-basic-2.j b/Task/Statistics-Basic/J/statistics-basic-2.j new file mode 100644 index 0000000000..fea7ade0c2 --- /dev/null +++ b/Task/Statistics-Basic/J/statistics-basic-2.j @@ -0,0 +1,3 @@ +histogram=: <: @ (#/.~) @ (i.@#@[ , I.) +require'plot' +plot ((%*1+i.)100) ([;histogram) ?10000#0 diff --git a/Task/Statistics-Basic/J/statistics-basic-3.j b/Task/Statistics-Basic/J/statistics-basic-3.j new file mode 100644 index 0000000000..e919e8043f --- /dev/null +++ b/Task/Statistics-Basic/J/statistics-basic-3.j @@ -0,0 +1,23 @@ +histogram=: <: @ (#/.~) @ (i.@#@[ , I.) + +meanstddevP=:3 :0 + NB. compute mean and std dev of y random numbers + NB. picked from even distribution between 0 and 1 + NB. and display a normalized ascii histogram for this sample + NB. note: should use population mean, not sample mean, for stddev + NB. given the equation specified for this task. + h=.s=.t=. 0 + buckets=. (%~1+i.)10 + for_n.i.<.y%1e6 do. + data=. ?1e6#0 + h=.h+ buckets histogram data + s=.s+ +/ data + t=.t+ +/(data-0.5)^2 + end. + data=. ?(1e6|y)#0 + h=.h+ buckets histogram data + s=.s+ +/ data + t=.t++/(data-0.5)^2 + smoutput (<.300*h%y)#"0'#' + (s%y),%:t%y +) diff --git a/Task/Statistics-Basic/J/statistics-basic-4.j b/Task/Statistics-Basic/J/statistics-basic-4.j new file mode 100644 index 0000000000..9596b8d2d6 --- /dev/null +++ b/Task/Statistics-Basic/J/statistics-basic-4.j @@ -0,0 +1,36 @@ + meanstddevP 1000 +############################# +#################################### +########################### +############################## +################################### +######################## +########################### +############################ +################################ +########################## +0.488441 0.289744 + meanstddevP 10000 +############################## +############################## +############################# +############################# +############################### +############################## +############################ +############################## +############################# +############################# +0.49697 0.289433 + meanstddevP 100000 +############################# +############################## +############################# +############################# +############################# +############################## +############################## +############################## +############################## +############################# +0.500872 0.288241 diff --git a/Task/Statistics-Basic/Liberty-BASIC/statistics-basic.liberty b/Task/Statistics-Basic/Liberty-BASIC/statistics-basic.liberty new file mode 100644 index 0000000000..bfe1b28497 --- /dev/null +++ b/Task/Statistics-Basic/Liberty-BASIC/statistics-basic.liberty @@ -0,0 +1,41 @@ +call sample 100 +call sample 1000 +call sample 10000 + +end + +sub sample n + dim dat( n) + for i =1 to n + dat( i) =rnd( 1) + next i + + '// show mean, standard deviation + sum =0 + sSq =0 + for i =1 to n + sum =sum +dat( i) + sSq =sSq +dat( i)^2 + next i + print n; " data terms used." + + mean =sum / n + print "Mean ="; mean + + print "Stddev ="; ( sSq /n -mean^2)^0.5 + + '// show histogram + nBins =10 + dim bins( nBins) + for i =1 to n + z =int( nBins *dat( i)) + bins( z) =bins( z) +1 + next i + for b =0 to nBins -1 + for j =1 to int( nBins *bins( b)) /n *70) + print "#"; + next j + print + next b + print +end sub diff --git a/Task/Statistics-Basic/MATLAB/statistics-basic.m b/Task/Statistics-Basic/MATLAB/statistics-basic.m new file mode 100644 index 0000000000..b354826da3 --- /dev/null +++ b/Task/Statistics-Basic/MATLAB/statistics-basic.m @@ -0,0 +1,20 @@ + % Initialize + N = 0; S=0; S2 = 0; + binlist = 0:.1:1; + h = zeros(1,length(binlist)); % initialize histogram + + % read data and perform computation + while (1) + % read next sample x + if (no_data_available) break; end; + N = N + 1; + S = S + x; + S2= S2+ x*x; + ix= sum(x < binlist); + h(ix) = h(ix)+1; + end + + % generate output + m = S/N; % mean + sd = sqrt(S2/N-mean*mean); % standard deviation + bar(binlist,h) diff --git a/Task/Statistics-Basic/Mathematica/statistics-basic.math b/Task/Statistics-Basic/Mathematica/statistics-basic.math new file mode 100644 index 0000000000..1ad9a7f7fe --- /dev/null +++ b/Task/Statistics-Basic/Mathematica/statistics-basic.math @@ -0,0 +1,4 @@ +Sample[n_]:= (Print[#//Length," numbers, Mean : ",#//Mean,", StandardDeviation : ",#//StandardDeviation ]; + BarChart[BinCounts[#,{0,1,.1}], Axes->False, BarOrigin->Left])&[(RandomReal[1,#])&[ n ]] + +Sample/@{100,1 000,10 000,1 000 000} diff --git a/Task/Statistics-Basic/PARI-GP/statistics-basic-1.pari b/Task/Statistics-Basic/PARI-GP/statistics-basic-1.pari new file mode 100644 index 0000000000..a151a8d619 --- /dev/null +++ b/Task/Statistics-Basic/PARI-GP/statistics-basic-1.pari @@ -0,0 +1,21 @@ +mean(v)={ + sum(i=1,#v,v[i])/#v +}; +stdev(v,mu="")={ + if(mu=="",mu=mean(v)); + sqrt(sum(i=1,#v,(v[i]-mu)^2))/#v +}; +histogram(v,bins=16,low=0,high=1)={ + my(u=vector(bins),width=(high-low)/bins); + for(i=1,#v,u[(v[i]-low)\width+1]++); + u +}; +show(n)={ + my(v=vector(n,i,random(1.)),mu=mean(v),s=stdev(v,mu),h=histogram(v),sz=ceil(n/50/16)); + for(i=1,16,for(j=1,h[i]\sz,print1("#"));print()); + print("Mean: "mu); + print("Stdev: "s); +}; +show(100); +show(1000); +show(10000); diff --git a/Task/Statistics-Basic/PARI-GP/statistics-basic-2.pari b/Task/Statistics-Basic/PARI-GP/statistics-basic-2.pari new file mode 100644 index 0000000000..2fbe281660 --- /dev/null +++ b/Task/Statistics-Basic/PARI-GP/statistics-basic-2.pari @@ -0,0 +1,4 @@ +rreal()={ + my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296))); \\ Current precision + random(2^pr)*1.>>pr +}; diff --git a/Task/Statistics-Basic/PL-I/statistics-basic.pli b/Task/Statistics-Basic/PL-I/statistics-basic.pli new file mode 100644 index 0000000000..ee66f87e2b --- /dev/null +++ b/Task/Statistics-Basic/PL-I/statistics-basic.pli @@ -0,0 +1,39 @@ + stat: procedure options (main); /* 21 May 2014 */ + +stats: procedure (values, mean, standard_deviation); + declare (values(*), mean, standard_deviation) float; + declare n fixed binary (31) initial ( (hbound(values,1)) ); + + mean = sum(values)/n; + + standard_deviation = sqrt( sum(values - mean)**2 / n); + +end stats; + + declare values (*) float controlled; + declare (mean, stddev) float; + declare bin(0:9) fixed; + declare (i, n) fixed binary (31); + + do n = 100, 1000, 10000, 100000; + allocate values(n); + values = random(); + call stats (values, mean, stddev); + + if n = 100 then + do; + bin = 0; + do i = 1 to 100; + bin(10*values(i)) += 1; + end; + put skip list ('Histogram for 100 values:'); + do i = 0 to 9; /* display histogram */ + put skip list (repeat('.', bin(i)) ); + end; + end; + + put skip list (n || ' values: mean=' || mean, 'stddev=' || stddev); + free values; + end; + +end stat; diff --git a/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 b/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 new file mode 100644 index 0000000000..46725cfd8a --- /dev/null +++ b/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 @@ -0,0 +1,10 @@ +for 100, 1_000, 10_000 -> $N { + say "size: $N"; + my @data = rand xx $N; + printf "mean: %f\n", my $mean = $N R/ [+] @data; + printf "stddev: %f\n", sqrt + $mean**2 R- $N R/ [+] @data »**» 2; + printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N) + for sort *.key, @data.classify: (10 * *).Int / 10; + say; +} diff --git a/Task/Statistics-Basic/Perl/statistics-basic.pl b/Task/Statistics-Basic/Perl/statistics-basic.pl new file mode 100644 index 0000000000..95fef9d54f --- /dev/null +++ b/Task/Statistics-Basic/Perl/statistics-basic.pl @@ -0,0 +1,24 @@ +my @histogram = (0) x 10; +my $sum = 0; +my $sum_squares = 0; +my $n = $ARGV[0]; + +for (1..$n) { + my $current = rand(); + $sum+= $current; + $sum_squares+= $current ** 2; + $histogram[$current * @histogram]+= 1; +} + +my $mean = $sum / $n; + +print "$n numbers\n", + "Mean: $mean\n", + "Stddev: ", sqrt(($sum_squares / $n) - ($mean ** 2)), "\n"; + +for my $i (0..$#histogram) { + printf "%.1f - %.1f : ", $i/@histogram, (1 + $i)/@histogram; + + print "*" x (30 * $histogram[$i] * @histogram/$n); # 30 stars expected per row + print "\n"; +} diff --git a/Task/Statistics-Basic/PicoLisp/statistics-basic-1.l b/Task/Statistics-Basic/PicoLisp/statistics-basic-1.l new file mode 100644 index 0000000000..9a75569c50 --- /dev/null +++ b/Task/Statistics-Basic/PicoLisp/statistics-basic-1.l @@ -0,0 +1,21 @@ +(scl 6) + +(de statistics (Cnt . Prg) + (prinl Cnt " numbers") + (let (Sum 0 Sqr 0 Hist (need 10 NIL 0)) + (do Cnt + (let N (run Prg 1) # Get next number + (inc 'Sum N) + (inc 'Sqr (*/ N N 1.0)) + (inc (nth Hist (inc (/ N 0.1)))) ) ) + (let M (*/ Sum Cnt) + (prinl "Mean: " (round M)) + (prinl "StdDev: " + (round + (sqrt + (- (*/ Sqr Cnt) (*/ M M 1.0)) + 1.0 ) ) ) ) + (for (I . H) Hist + (prin (format I 1) " ") + (do (*/ H 400 Cnt) (prin '=)) + (prinl) ) ) ) diff --git a/Task/Statistics-Basic/PicoLisp/statistics-basic-2.l b/Task/Statistics-Basic/PicoLisp/statistics-basic-2.l new file mode 100644 index 0000000000..a24134c434 --- /dev/null +++ b/Task/Statistics-Basic/PicoLisp/statistics-basic-2.l @@ -0,0 +1,11 @@ +(statistics 100 + (rand 0 (dec 1.0)) ) +(prinl) + +(statistics 10000 + (rand 0 (dec 1.0)) ) +(prinl) + +(statistics 1000000 + (rand 0 (dec 1.0)) ) +(prinl) diff --git a/Task/Statistics-Basic/PureBasic/statistics-basic.purebasic b/Task/Statistics-Basic/PureBasic/statistics-basic.purebasic new file mode 100644 index 0000000000..a16ace185a --- /dev/null +++ b/Task/Statistics-Basic/PureBasic/statistics-basic.purebasic @@ -0,0 +1,56 @@ +Procedure.f randomf() + #RNG_max_resolution = 2147483647 + ProcedureReturn Random(#RNG_max_resolution) / #RNG_max_resolution +EndProcedure + +Procedure sample(n) + Protected i, nBins, binNumber, tickMarks, maxBinValue + Protected.f sum, sumSq, mean + + Dim dat.f(n) + For i = 1 To n + dat(i) = randomf() + Next + + ;show mean, standard deviation + For i = 1 To n + sum + dat(i) + sumSq + dat(i) * dat(i) + Next i + + PrintN(Str(n) + " data terms used.") + mean = sum / n + PrintN("Mean =" + StrF(mean)) + PrintN("Stddev =" + StrF((sumSq / n) - Sqr(mean * mean))) + + ;show histogram + nBins = 10 + Dim bins(nBins) + For i = 1 To n + binNumber = Int(nBins * dat(i)) + bins(binNumber) + 1 + Next + + maxBinValue = 1 + For i = 0 To nBins + If bins(i) > maxBinValue + maxBinValue = bins(i) + EndIf + Next + + #normalizedMaxValue = 70 + For binNumber = 0 To nBins + tickMarks = Int(bins(binNumber) * #normalizedMaxValue / maxBinValue) + PrintN(ReplaceString(Space(tickMarks), " ", "#")) + Next + PrintN("") +EndProcedure + +If OpenConsole() + sample(100) + sample(1000) + sample(10000) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Statistics-Basic/Python/statistics-basic.py b/Task/Statistics-Basic/Python/statistics-basic.py new file mode 100644 index 0000000000..cfcec5be96 --- /dev/null +++ b/Task/Statistics-Basic/Python/statistics-basic.py @@ -0,0 +1,39 @@ +def sd1(numbers): + if numbers: + mean = sum(numbers) / len(numbers) + sd = (sum((n - mean)**2 for n in numbers) / len(numbers))**0.5 + return sd, mean + else: + return 0, 0 + +def sd2(numbers): + if numbers: + sx = sxx = n = 0 + for x in numbers: + sx += x + sxx += x*x + n += 1 + sd = (n * sxx - sx*sx)**0.5 / n + return sd, sx / n + else: + return 0, 0 + +def histogram(numbers): + h = [0] * 10 + maxwidth = 50 # characters + for n in numbers: + h[int(n*10)] += 1 + mx = max(h) + print() + for n, i in enumerate(h): + print('%3.1f: %s' % (n / 10, '+' * int(i / mx * maxwidth))) + print() + +if __name__ == '__main__': + import random + for i in range(1, 6): + n = [random.random() for j in range(10**i)] + print("\n##\n## %i numbers\n##" % 10**i) + print(' Naive method: sd: %8.6f, mean: %8.6f' % sd1(n)) + print(' Second method: sd: %8.6f, mean: %8.6f' % sd2(n)) + histogram(n) diff --git a/Task/Statistics-Basic/README b/Task/Statistics-Basic/README new file mode 100644 index 0000000000..cb16f27197 --- /dev/null +++ b/Task/Statistics-Basic/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Statistics/Basic diff --git a/Task/Statistics-Basic/REXX/statistics-basic.rexx b/Task/Statistics-Basic/REXX/statistics-basic.rexx new file mode 100644 index 0000000000..ecaa3cd304 --- /dev/null +++ b/Task/Statistics-Basic/REXX/statistics-basic.rexx @@ -0,0 +1,38 @@ +/*REXX pgm gens some random #s, shows bin histogram, finds mean & stdDev*/ +numeric digits 20 /*use twenty digits precision, */ +showDigs=digits()%2 /* ··· but only show ten digits.*/ +parse arg size seed . /*allow specification: size, seed*/ +if size=='' | size==',' then size=100 /*if not specified, then use 100.*/ +if datatype(seed,'W') then call random ,,seed /*allow seed for RAND.*/ +#.=0 /*count of numbers in each bin. */ + do j=1 for size /*generate some random numbers. */ + @.j=random(0,99999)/100000 /*express as a fraction.*/ + _=substr(@.j'00',3,1) /*determine which bin it's in, */ + #._=#._+1 /* ··· and bump its count. */ + end /*j*/ + + do k=0 for 10 /*show a histogram of the bins. */ + lr='0.'k ; if k==0 then lr='0 ' /*adjust for low range.*/ + hr='0.'||(k+1); if k==9 then hr='1 ' /* " " high range.*/ + range=lr"──►"hr' ' /*construct the range. */ + barPC=right(strip(left(format(100*#.k/size,,2),5)),5) /*comp %*/ + say range barPC copies('─',format(barPC*1,,0)) /*histo.*/ + end /*k*/ +say +say 'sample size = ' size; say +avg=mean(size) ; say ' mean = ' format(avg,,showDigs) +stddev=stddev(size); say ' stddev = ' format(stddev,,showDigs) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────MEAN subroutine─────────────────────*/ +mean: parse arg N .; $=0; do m=1 for N; $=$+@.m; end /*m*/ +return $/n +/*──────────────────────────────────STDDEV subroutine───────────────────*/ +stddev: parse arg N .; $=0; do s=1 for N; $=$+(@.s-avg)**2; end /*s*/ +return sqrt($/n) +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +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/Statistics-Basic/Racket/statistics-basic.rkt b/Task/Statistics-Basic/Racket/statistics-basic.rkt new file mode 100644 index 0000000000..031092941e --- /dev/null +++ b/Task/Statistics-Basic/Racket/statistics-basic.rkt @@ -0,0 +1,21 @@ +#lang racket +(require math (only-in srfi/27 random-real)) + +(define (histogram n xs Δx) + (define (r x) (~r x #:precision 1 #:min-width 3)) + (define (len count) (exact-floor (/ (* count 200) n))) + (for ([b (bin-samples (range 0 1 Δx) <= xs)]) + (displayln (~a (r (sample-bin-min b)) "-" (r (sample-bin-max b)) ": " + (make-string (len (length (sample-bin-values b))) #\*))))) + +(define (task n) + (define xs (for/list ([_ n]) (random-real))) + (displayln (~a "Number of samples: " n)) + (displayln (~a "Mean: " (mean xs))) + (displayln (~a "Standard deviance: " (stddev xs))) + (histogram n xs 0.1) + (newline)) + +(task 100) +(task 1000) +(task 10000) diff --git a/Task/Statistics-Basic/Ruby/statistics-basic.rb b/Task/Statistics-Basic/Ruby/statistics-basic.rb new file mode 100644 index 0000000000..155977b8a7 --- /dev/null +++ b/Task/Statistics-Basic/Ruby/statistics-basic.rb @@ -0,0 +1,20 @@ +def generate_statistics(n) + sum = sum2 = 0.0 + hist = Array.new(10, 0) + n.times do + r = rand + sum += r + sum2 += r**2 + hist[(10*r).to_i] += 1 + end + mean = sum / n + stddev = Math::sqrt((sum2 / n) - mean**2) + + puts "size: #{n}" + puts "mean: #{mean}" + puts "stddev: #{stddev}" + hist.each_with_index {|x,i| puts "%.1f:%s" % [0.1*i, "=" * (70*x/hist.max)]} + puts +end + +[100, 1000, 10000].each {|n| generate_statistics n} diff --git a/Task/Statistics-Basic/Scala/statistics-basic.scala b/Task/Statistics-Basic/Scala/statistics-basic.scala new file mode 100644 index 0000000000..644b8a0028 --- /dev/null +++ b/Task/Statistics-Basic/Scala/statistics-basic.scala @@ -0,0 +1,21 @@ +def mean(a:Array[Double])=a.sum / a.size +def stddev(a:Array[Double])={ + val sum = a.fold(0.0)((a, b) => a + math.pow(b,2)) + math.sqrt((sum/a.size) - math.pow(mean(a),2)) +} +def hist(a:Array[Double]) = { + val grouped=(SortedMap[Double, Array[Double]]() ++ (a groupBy (x => math.rint(x*10)/10))) + grouped.map(v => (v._1, v._2.size)) +} +def printHist(a:Array[Double])=for((g,v) <- hist(a)){ + println(s"$g: ${"*"*(205*v/a.size)} $v") +} + +for(n <- Seq(100,1000,10000)){ + val a = Array.fill(n)(Random.nextDouble) + println(s"$n numbers") + println(s"Mean: ${mean(a)}") + println(s"StdDev: ${stddev(a)}") + printHist(a) + println +} diff --git a/Task/Statistics-Basic/Tcl/statistics-basic.tcl b/Task/Statistics-Basic/Tcl/statistics-basic.tcl new file mode 100644 index 0000000000..6475a19269 --- /dev/null +++ b/Task/Statistics-Basic/Tcl/statistics-basic.tcl @@ -0,0 +1,27 @@ +package require Tcl 8.5 +proc stats {size} { + set sum 0.0 + set sum2 0.0 + for {set i 0} {$i < $size} {incr i} { + set r [expr {rand()}] + + incr histo([expr {int(floor($r*10))}]) + set sum [expr {$sum + $r}] + set sum2 [expr {$sum2 + $r**2}] + } + set mean [expr {$sum / $size}] + set stddev [expr {sqrt($sum2/$size - $mean**2)}] + puts "$size numbers" + puts "Mean: $mean" + puts "StdDev: $stddev" + foreach i {0 1 2 3 4 5 6 7 8 9} { + # The 205 is a magic factor stolen from the Go solution + puts [string repeat "*" [expr {$histo($i)*205/int($size)}]] + } +} + +stats 100 +puts "" +stats 1000 +puts "" +stats 10000 diff --git a/Task/Stern-Brocot-sequence/00DESCRIPTION b/Task/Stern-Brocot-sequence/00DESCRIPTION new file mode 100644 index 0000000000..6a4d0e7346 --- /dev/null +++ b/Task/Stern-Brocot-sequence/00DESCRIPTION @@ -0,0 +1,35 @@ +For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]]. + +# The first and second members of the sequence are both 1: +#* 1, 1 +# Start by considering the second member of the sequence +# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence: +#* 1, 1, 2 +# Append the considered member of the sequence to the end of the sequence: +#* 1, 1, 2, 1 +# Consider the next member of the series, (the third member i.e. 2) +# GOTO 3 + +Expanding another loop we get: + +7. Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence: +* 1, 1, 2, 1, 3 +8. Append the considered member of the sequence to the end of the sequence: +* 1, 1, 2, 1, 3, 2 +9. Consider the next member of the series, (the fourth member i.e. 1) + +;The task is to: +# Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. +# Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) +# Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. +# Show the (1-based) index of where the number 100 first appears in the sequence. +# Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. +Show your output on the page. + +;Ref: +* [https://www.youtube.com/watch?v=DpwUVExX27E Infinite Fractions - Numberphile] (Video). +* [http://www.ams.org/samplings/feature-column/fcarc-stern-brocot Trees, Teeth, and Time: The mathematics of clock making]. +* [https://oeis.org/A002487 A002487] The On-Line Encyclopedia of Integer Sequences. + +;Related Tasks: +* [[Continued fraction/Arithmetic]] diff --git a/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-1.c b/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-1.c new file mode 100644 index 0000000000..7120128031 --- /dev/null +++ b/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-1.c @@ -0,0 +1,38 @@ +#include + +typedef unsigned int uint; + +/* the sequence, 0-th member is 0 */ +uint f(uint n) +{ + return n < 2 ? n : (n&1) ? f(n/2) + f(n/2 + 1) : f(n/2); +} + +uint gcd(uint a, uint b) +{ + return a ? a < b ? gcd(b%a, a) : gcd(a%b, b) : b; +} + +void find(uint from, uint to) +{ + do { + uint n; + for (n = 1; f(n) != from ; n++); + printf("%3u at Stern #%u.\n", from, n); + } while (++from <= to); +} + +int main(void) +{ + uint n; + for (n = 1; n < 16; n++) printf("%u ", f(n)); + puts("are the first fifteen."); + + find(1, 10); + find(100, 0); + + for (n = 1; n < 1000 && gcd(f(n), f(n+1)) == 1; n++); + printf(n == 1000 ? "All GCDs are 1.\n" : "GCD of #%d and #%d is not 1", n, n+1); + + return 0; +} diff --git a/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-2.c b/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-2.c new file mode 100644 index 0000000000..110e0247ce --- /dev/null +++ b/Task/Stern-Brocot-sequence/C/stern-brocot-sequence-2.c @@ -0,0 +1,10 @@ +uint f(uint n) +{ + uint a = 1, b = 0; + while (n) { + if (n&1) b += a; + else a += b; + n >>= 1; + } + return b; +} diff --git a/Task/Stern-Brocot-sequence/Clojure/stern-brocot-sequence.clj b/Task/Stern-Brocot-sequence/Clojure/stern-brocot-sequence.clj new file mode 100644 index 0000000000..31c4521ea3 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Clojure/stern-brocot-sequence.clj @@ -0,0 +1,18 @@ +;; compute the Nth (1-based) Stern-Brocot number directly +(defn nth-stern-brocot [n] + (if (< n 2) + n + (let [h (quot n 2) h1 (inc h) hth (nth-stern-brocot h)] + (if (zero? (mod n 2)) hth (+ hth (nth-stern-brocot h1)))))) + +;; return a lazy version of the entire Stern-Brocot sequence +(defn stern-brocot + ([] (stern-brocot 1)) + ([n] (cons (nth-stern-brocot n) (lazy-seq (stern-brocot (inc n)))))) + +(printf "Stern-Brocot numbers 1-15: %s%n" + (clojure.string/join ", " (take 15 (stern-brocot)))) + +(dorun (for [n (concat (range 1 11) [100])] + (printf "The first appearance of %3d is at index %4d.%n" + n (inc (first (keep-indexed #(when (= %2 n) %1) (stern-brocot))))))) diff --git a/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-1.d b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-1.d new file mode 100644 index 0000000000..697ef22d62 --- /dev/null +++ b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-1.d @@ -0,0 +1,29 @@ +import std.stdio, std.numeric, std.range, std.algorithm; + +/// Generates members of the stern-brocot series, in order, +/// returning them when the predicate becomes false. +uint[] sternBrocot(bool delegate(in uint[]) pure nothrow @safe @nogc pred=seq => seq.length < 20) +pure nothrow @safe { + typeof(return) sb = [1, 1]; + size_t i = 0; + while (pred(sb)) { + sb ~= [sb[i .. i + 2].sum, sb[i + 1]]; + i++; + } + return sb; +} + +void main() { + enum nFirst = 15; + writefln("The first %d values:\n%s\n", nFirst, + sternBrocot(seq => seq.length < nFirst).take(nFirst)); + + foreach (immutable nOccur; iota(1, 10 + 1).chain(100.only)) + writefln("1-based index of the first occurrence of %3d in the series: %d", + nOccur, sternBrocot(seq => nOccur != seq[$ - 2]).length - 1); + + enum nGcd = 1_000; + auto s = sternBrocot(seq => seq.length < nGcd).take(nGcd); + assert(zip(s, s.dropOne).all!(ss => ss[].gcd == 1), + "A fraction from adjacent terms is reducible."); +} diff --git a/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-2.d b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-2.d new file mode 100644 index 0000000000..e8723e73da --- /dev/null +++ b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-2.d @@ -0,0 +1,18 @@ +import std.stdio, std.algorithm, std.range, std.numeric, queue_usage2; + +struct SternBrocot { + private auto sb = GrowableCircularQueue!uint(1, 1); + enum empty = false; + @property uint front() pure nothrow @safe @nogc { + return sb.front; + } + uint popFront() pure nothrow @safe { + sb.push(sb.front + sb[1]); + sb.push(sb[1]); + return sb.pop; + } +} + +void main() { + SternBrocot().drop(50_000_000).front.writeln; +} diff --git a/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-3.d b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-3.d new file mode 100644 index 0000000000..216f6fcd4f --- /dev/null +++ b/Task/Stern-Brocot-sequence/D/stern-brocot-sequence-3.d @@ -0,0 +1,28 @@ +void main() { + import std.stdio, std.numeric, std.range, std.algorithm, std.bigint, std.conv; + + /// Stern-Brocot sequence, 0-th member is 0. + T sternBrocot(T)(T n) pure nothrow /*safe*/ { + T a = 1, b = 0; + while (n) { + if (n & 1) b += a; + else a += b; + n >>= 1; + } + return b; + } + alias sb = sternBrocot!uint; + + enum nFirst = 15; + writefln("The first %d values:\n%s\n", nFirst, iota(1, nFirst + 1).map!sb); + + foreach (immutable nOccur; iota(1, 10 + 1).chain(100.only)) + writefln("1-based index of the first occurrence of %3d in the series: %d", + nOccur, sequence!q{n}.until!(n => sb(n) == nOccur).walkLength); + + auto s = iota(1, 1_001).map!sb; + assert(s.zip(s.dropOne).all!(ss => ss[].gcd == 1), + "A fraction from adjacent terms is reducible."); + + sternBrocot(10.BigInt ^^ 20_000).text.length.writeln; +} diff --git a/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-1.go b/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-1.go new file mode 100644 index 0000000000..57c475ec12 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-1.go @@ -0,0 +1,48 @@ +package main + +import ( + "fmt" + + "sternbrocot" +) + +func main() { + // Task 1, using the conventional sort of generator that generates + // terms endlessly. + g := sb.Generator() + + // Task 2, demonstrating the generator. + fmt.Println("First 15:") + for i := 1; i <= 15; i++ { + fmt.Printf("%2d: %d\n", i, g()) + } + + // Task 2 again, showing a simpler technique that might or might not be + // considered to "generate" terms. + s := sb.New() + fmt.Println("First 15:", s.FirstN(15)) + + // Tasks 3 and 4. + for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} { + fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x)) + } + + // Task 5. + fmt.Println("1-based indexes: gcd") + for n, f := range s.FirstN(1000)[:999] { + g := gcd(f, (*s)[n+1]) + fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g) + if g != 1 { + panic("oh no!") + return + } + } +} + +// gcd copied from greatest common divisor task +func gcd(x, y int) int { + for y != 0 { + x, y = y, x%y + } + return x +} diff --git a/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-2.go b/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-2.go new file mode 100644 index 0000000000..4fbc20430a --- /dev/null +++ b/Task/Stern-Brocot-sequence/Go/stern-brocot-sequence-2.go @@ -0,0 +1,74 @@ +// SB implements the Stern-Brocot sequence. +// +// Generator() satisfies RC Task 1. For remaining tasks, Generator could be +// used but FirstN(), and Find() are simpler methods for specific stopping +// criteria. FirstN and Find might also be considered to satisfy Task 1, +// in which case Generator would not really be needed. Anyway, there it is. +package sb + +// Seq represents an even number of terms of a Stern-Brocot sequence. +// +// Terms are stored in a slice. Terms start with 1. +// (Specifically, the zeroth term, 0, given in OEIS A002487 is not represented.) +// Term 1 (== 1) is stored at slice index 0. +// +// Methods on Seq rely on Seq always containing an even number of terms. +type Seq []int + +// New returns a Seq with the two base terms. +func New() *Seq { + return &Seq{1, 1} // Step 1 of the RC task. +} + +// TwoMore appends two more terms to p. +// It's the body of the loop in the RC algorithm. +// Generate(), FirstN(), and Find() wrap this body in different ways. +func (p *Seq) TwoMore() { + s := *p + n := len(s) / 2 // Steps 2 and 5 of the RC task. + c := s[n] + *p = append(s, c+s[n-1], c) // Steps 3 and 4 of the RC task. +} + +// Generator returns a generator function that returns successive terms +// (until overflow.) +func Generator() func() int { + n := 0 + p := New() + return func() int { + if len(*p) == n { + p.TwoMore() + } + t := (*p)[n] + n++ + return t + } +} + +// FirstN lazily extends p as needed so that it has at least n terms. +// FirstN then returns a list of the first n terms. +func (p *Seq) FirstN(n int) []int { + for len(*p) < n { + p.TwoMore() + } + return []int((*p)[:n]) +} + +// Find lazily extends p as needed until it contains the value x +// Find then returns the slice index of x in p. +func (p *Seq) Find(x int) int { + for n, f := range *p { + if f == x { + return n + } + } + for { + p.TwoMore() + switch x { + case (*p)[len(*p)-2]: + return len(*p) - 2 + case (*p)[len(*p)-1]: + return len(*p) - 1 + } + } +} diff --git a/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs b/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs new file mode 100644 index 0000000000..d1ba54f1ba --- /dev/null +++ b/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs @@ -0,0 +1,9 @@ +import Data.List + +sb = 1:1: f (tail sb) sb where + f (a:aa) (b:bb) = a+b : a : f aa bb + +main = do + print $ take 15 sb + print [(i,1 + (\(Just i)->i) (elemIndex i sb)) | i <- [1..10]++[100]] + print $ all (\(a,b)->1 == gcd a b) $ take 1000 $ zip sb (tail sb) diff --git a/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-1.j b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-1.j new file mode 100644 index 0000000000..30fc825f71 --- /dev/null +++ b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-1.j @@ -0,0 +1,8 @@ +sternbrocot=:1 :0 + ind=. 0 + seq=. 1 1 + while. -. u seq do. + ind=. ind+1 + seq=. seq, +/\. seq {~ _1 0 +ind + end. +) diff --git a/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-2.j b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-2.j new file mode 100644 index 0000000000..330e8b6fc0 --- /dev/null +++ b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-2.j @@ -0,0 +1,2 @@ + 15{.(15<:#) sternbrocot +1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 diff --git a/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-3.j b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-3.j new file mode 100644 index 0000000000..2ae85a484f --- /dev/null +++ b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-3.j @@ -0,0 +1,2 @@ + 1+(10 e. ]) sternbrocot i.1+i.10 +1 3 5 9 11 33 19 21 35 39 diff --git a/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-4.j b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-4.j new file mode 100644 index 0000000000..98cae8c6ba --- /dev/null +++ b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-4.j @@ -0,0 +1,2 @@ + 1+(100 e. ]) sternbrocot i. 100 +1179 diff --git a/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-5.j b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-5.j new file mode 100644 index 0000000000..c808095b41 --- /dev/null +++ b/Task/Stern-Brocot-sequence/J/stern-brocot-sequence-5.j @@ -0,0 +1,2 @@ + ~.2 +./\ (1000<:#) sternbrocot +1 diff --git a/Task/Stern-Brocot-sequence/Java/stern-brocot-sequence.java b/Task/Stern-Brocot-sequence/Java/stern-brocot-sequence.java new file mode 100644 index 0000000000..4ab6fb0810 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Java/stern-brocot-sequence.java @@ -0,0 +1,34 @@ +import java.math.BigInteger; +import java.util.LinkedList; + +public class SternBrocot { + static LinkedList sequence = new LinkedList(){{ + add(1); add(1); + }}; + + private static void genSeq(int n){ + for(int conIdx = 1; sequence.size() < n; conIdx++){ + int consider = sequence.get(conIdx); + int pre = sequence.get(conIdx - 1); + sequence.add(consider + pre); + sequence.add(consider); + } + + } + + public static void main(String[] args){ + genSeq(1200); + System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); + for(int i = 1; i <= 10; i++){ + System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); + } + + System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); + + boolean failure = false; + for(int i = 0; i < 999; i++){ + failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); + } + System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); + } +} diff --git a/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 b/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 new file mode 100644 index 0000000000..31aff75f51 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 @@ -0,0 +1,12 @@ +constant Stern-Brocot = flat + 1, 1, -> *@a { + @a[$_ - 1] + @a[$_], @a[$_] given ++$; + } ... *; + +say Stern-Brocot[^15]; + +for 1 .. 10, 100 -> $ix { + say "first occurrence of $ix is at index : ", 1 + Stern-Brocot.first-index($ix); +} + +say so 1 == all map ^1000: { [gcd] Stern-Brocot[$_, $_ + 1] } diff --git a/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl b/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl new file mode 100644 index 0000000000..75cccf6949 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl @@ -0,0 +1,36 @@ +use strict; +use warnings; + +sub stern_brocot { + my @list = (1, 1); + sub { + push @list, $list[0] + $list[1], $list[1]; + shift @list; + } +} + +{ + my $generator = stern_brocot; + print join ' ', map &$generator, 1 .. 15; + print "\n"; +} + +for (1 .. 10, 100) { + my $index = 1; + my $generator = stern_brocot; + $index++ until $generator->() == $_; + print "first occurrence of $_ is at index $index\n"; +} + +{ + sub gcd { + my ($u, $v) = @_; + $v ? gcd($v, $u % $v) : abs($u); + } + my $generator = stern_brocot; + my ($a, $b) = ($generator->(), $generator->()); + for (1 .. 1000) { + die "unexpected GCD for $a and $b" unless gcd($a, $b) == 1; + ($a, $b) = ($b, $generator->()); + } +} diff --git a/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-1.py b/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-1.py new file mode 100644 index 0000000000..8c4354d3e6 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-1.py @@ -0,0 +1,36 @@ +def stern_brocot(predicate=lambda series: len(series) < 20): + """\ + Generates members of the stern-brocot series, in order, returning them when the predicate becomes false + + >>> print('The first 10 values:', + stern_brocot(lambda series: len(series) < 10)[:10]) + The first 10 values: [1, 1, 2, 1, 3, 2, 3, 1, 4, 3] + >>> + """ + + sb, i = [1, 1], 0 + while predicate(sb): + sb += [sum(sb[i:i + 2]), sb[i + 1]] + i += 1 + return sb + + +if __name__ == '__main__': + from fractions import gcd + + n_first = 15 + print('The first %i values:\n ' % n_first, + stern_brocot(lambda series: len(series) < n_first)[:n_first]) + print() + n_max = 10 + for n_occur in list(range(1, n_max + 1)) + [100]: + print('1-based index of the first occurrence of %3i in the series:' % n_occur, + stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) + # The following would be much faster. Note that new values always occur at odd indices + # len(stern_brocot(lambda series: n_occur != series[-2])) - 1) + + print() + n_gcd = 1000 + s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] + assert all(gcd(prev, this) == 1 + for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible' diff --git a/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-2.py b/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-2.py new file mode 100644 index 0000000000..2b9f6683dd --- /dev/null +++ b/Task/Stern-Brocot-sequence/Python/stern-brocot-sequence-2.py @@ -0,0 +1,22 @@ +>>> from itertools import takewhile, tee, islice +>>> from collections import deque +>>> from fractions import gcd +>>> +>>> def stern_brocot(): + sb = deque([1, 1]) + while True: + sb += [sb[0] + sb[1], sb[1]] + yield sb.popleft() + + +>>> [s for _, s in zip(range(15), stern_brocot())] +[1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4] +>>> [1 + sum(1 for i in takewhile(lambda x: x != occur, stern_brocot())) + for occur in (list(range(1, 11)) + [100])] +[1, 3, 5, 9, 11, 33, 19, 21, 35, 39, 1179] +>>> prev, this = tee(stern_brocot(), 2) +>>> next(this) +1 +>>> all(gcd(p, t) == 1 for p, t in islice(zip(prev, this), 1000)) +True +>>> diff --git a/Task/Stern-Brocot-sequence/README b/Task/Stern-Brocot-sequence/README new file mode 100644 index 0000000000..fd219f1c9d --- /dev/null +++ b/Task/Stern-Brocot-sequence/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Stern-Brocot_sequence diff --git a/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx b/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx new file mode 100644 index 0000000000..660efe475a --- /dev/null +++ b/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx @@ -0,0 +1,45 @@ +/*REXX pgm gens/shows Stern-Brocot sequence, finds 1-based indices, GCDs*/ +parse arg N idx fix chk . /*get optional argument from C.L.*/ +if N=='' | N==',' then N= 15 /*use the default for N ? */ +if idx=='' | idx==',' then idx= 10 /* " " " " idx ? */ +if fix=='' | fix==',' then fix= 100 /* " " " " fix ? */ +if chk=='' | chk==',' then chk=1000 /* " " " " chk ? */ + /*═══════════════════════════════*/ +say center('the first' N 'numbers in the Stern-Brocot sequence', 70,'═') +a=Stern_Brocot(N) /*invoke function to generate seq*/ +say a /*display sequence to terminal. */ + /*═══════════════════════════════*/ +say center('the 1-based index for the first' idx "integers", 70, '═') +a=Stern_Brocot(-idx) /*invoke function to generate seq*/ + do i=1 for idx + say 'for ' right(i,length(idx))", the index is: " wordpos(i,a) + end /*i*/ + /*═══════════════════════════════*/ +say center('the 1-based index for' fix, 70, '═') +a=Stern_Brocot(-fix) /*invoke function to generate seq*/ +say 'for ' fix", the index is: " wordpos(fix,a) + /*═══════════════════════════════*/ +say center('checking if all two consecutive members have a GCD=1', 70,'═') +a=Stern_Brocot(chk) /*invoke function to generate seq*/ + do c=1 for chk-1; if gcd(subword(a,c,2))==1 then iterate + say 'GCD check failed at member' c"."; exit 13 + end /*c*/ +say '───── All ' chk " two consecutive members have a GCD of unity." +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GCD subroutine──────────────────────*/ +gcd: procedure; $=; do i=1 for arg(); $=$ arg(i); end /*arg list*/ +parse var $ x z .; if x=0 then x=z /*handle special 0 case.*/ +x=abs(x) + do j=2 to words($); y=abs(word($,j)); if y=0 then iterate + do until _==0; _=x//y; x=y; y=_; end /*◄──heavy lifting*/ + end /*j*/ +return x +/*──────────────────────────────────STERN_BROCOT subroutine.────────────*/ +Stern_Brocot: parse arg h 1 f; if h<0 then h=1e9; else f=0; f=abs(f) +$=1 1 + do k=2 until words($)>=h; _=word($,k); $=$ (_+word($,k-1)) _ + if f==0 then iterate; if wordpos(f,$)\==0 then leave + end /*until*/ + +if f==0 then return subword($,1,h) + return $ diff --git a/Task/Stern-Brocot-sequence/Racket/stern-brocot-sequence.rkt b/Task/Stern-Brocot-sequence/Racket/stern-brocot-sequence.rkt new file mode 100644 index 0000000000..f8d56e7e39 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Racket/stern-brocot-sequence.rkt @@ -0,0 +1,38 @@ +#lang racket +;; OEIS Definition +;; A002487 +;; Stern's diatomic series +;; (or Stern-Brocot sequence): +;; a(0) = 0, a(1) = 1; +;; for n > 0: +;; a(2*n) = a(n), +;; a(2*n+1) = a(n) + a(n+1). +(define A002487 + (let ((memo (make-hash '((0 . 0) (1 . 1))))) + (lambda (n) + (hash-ref! memo n + (lambda () + (define n/2 (quotient n 2)) + (+ (A002487 n/2) (if (even? n) 0 (A002487 (add1 n/2))))))))) + +(define Stern-Brocot A002487) + +(displayln "Show the first fifteen members of the sequence. +(This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)") +(for/list ((i (in-range 1 (add1 15)))) (Stern-Brocot i)) + +(displayln "Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.") +(for ((n (in-range 1 (add1 10)))) + (for/first ((i (in-naturals 1)) + #:when (= n (Stern-Brocot i))) + (printf "~a first found at a(~a)~%" n i))) + +(displayln "Show the (1-based) index of where the number 100 first appears in the sequence.") +(for/first ((i (in-naturals 1)) #:when (= 100 (Stern-Brocot i))) i) + +(displayln "Check that the greatest common divisor of all the two consecutive members of the +series up to the 1000th member, is always one.") +(unless + (for/first ((i (in-range 1 1000)) + #:unless (= 1 (gcd (Stern-Brocot i) (Stern-Brocot (add1 i))))) #t) + (display "\tdidn't find gcd > (or otherwise ≠) 1")) diff --git a/Task/Stern-Brocot-sequence/Ruby/stern-brocot-sequence.rb b/Task/Stern-Brocot-sequence/Ruby/stern-brocot-sequence.rb new file mode 100644 index 0000000000..0c2ab5e14f --- /dev/null +++ b/Task/Stern-Brocot-sequence/Ruby/stern-brocot-sequence.rb @@ -0,0 +1,20 @@ +def sb + return enum_for :sb unless block_given? + a=[1,1] + 0.step do |i| + yield a[i] + a << a[i]+a[i+1] << a[i+1] + end +end + +puts "First 15: #{sb.first(15)}" + +[*1..10,100].each do |n| + puts "#{n} first appears at #{sb.find_index(n)+1}." +end + +if sb.take(1000).each_cons(2).map { |a,b| a.gcd(b) }.all? { |n| n==1 } + puts "All GCD's are 1" +else + puts "Whoops, not all GCD's are 1!" +end diff --git a/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb b/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb new file mode 100644 index 0000000000..e9f69e83f3 --- /dev/null +++ b/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb @@ -0,0 +1,40 @@ +sb = Array(1,1) +i = 1 'considered +j = 2 'precedent +n = 0 'loop counter +Do + ReDim Preserve sb(UBound(sb) + 1) + sb(UBound(sb)) = sb(UBound(sb) - i) + sb(UBound(sb) - j) + ReDim Preserve sb(UBound(sb) + 1) + sb(UBound(sb)) = sb(UBound(sb) - j) + i = i + 1 + j = j + 1 + n = n + 1 +Loop Until n = 2000 + +WScript.Echo "First 15: " & DisplayElements(15) + +For k = 1 To 10 + WScript.Echo "The first instance of " & k & " is in #" & ShowFirstInstance(k) & "." +Next + +WScript.Echo "The first instance of " & 100 & " is in #" & ShowFirstInstance(100) & "." + +Function DisplayElements(n) + For i = 0 To n - 1 + If i < n - 1 Then + DisplayElements = DisplayElements & sb(i) & ", " + Else + DisplayElements = DisplayElements & sb(i) + End If + Next +End Function + +Function ShowFirstInstance(n) + For i = 0 To UBound(sb) + If sb(i) = n Then + ShowFirstInstance = i + 1 + Exit For + End If + Next +End Function diff --git a/Task/String-append/00DESCRIPTION b/Task/String-append/00DESCRIPTION new file mode 100644 index 0000000000..a76f63c2cc --- /dev/null +++ b/Task/String-append/00DESCRIPTION @@ -0,0 +1,6 @@ +{{basic data operation}} [[Category:Simple]] +Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. +For this task, create a string variable equal to any text value. +Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. + +Show the contents of the variable after the append operation. diff --git a/Task/String-append/00META.yaml b/Task/String-append/00META.yaml new file mode 100644 index 0000000000..77b7285952 --- /dev/null +++ b/Task/String-append/00META.yaml @@ -0,0 +1,5 @@ +--- +category: +- String manipulation +- String manipulation +note: Basic language learning diff --git a/Task/String-append/ALGOL-68/string-append.alg b/Task/String-append/ALGOL-68/string-append.alg new file mode 100644 index 0000000000..cafdabab6e --- /dev/null +++ b/Task/String-append/ALGOL-68/string-append.alg @@ -0,0 +1,6 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +STRING str := "12345678"; +str +:= "9!"; +print(str) diff --git a/Task/String-append/AWK/string-append.awk b/Task/String-append/AWK/string-append.awk new file mode 100644 index 0000000000..459d749dcf --- /dev/null +++ b/Task/String-append/AWK/string-append.awk @@ -0,0 +1,7 @@ +# syntax: GAWK -f STRING_APPEND.AWK +BEGIN { + s = "foo" + s = s "bar" + print(s) + exit(0) +} diff --git a/Task/String-append/AutoHotkey/string-append.ahk b/Task/String-append/AutoHotkey/string-append.ahk new file mode 100644 index 0000000000..4d2ce08086 --- /dev/null +++ b/Task/String-append/AutoHotkey/string-append.ahk @@ -0,0 +1,3 @@ +s := "Hello, " +s .= "world." +MsgBox % s diff --git a/Task/String-append/BASIC/string-append-1.basic b/Task/String-append/BASIC/string-append-1.basic new file mode 100644 index 0000000000..92e45036a5 --- /dev/null +++ b/Task/String-append/BASIC/string-append-1.basic @@ -0,0 +1,3 @@ +S$ = "Hello" +S$ = S$ + " World!" +PRINT S$ diff --git a/Task/String-append/BASIC/string-append-2.basic b/Task/String-append/BASIC/string-append-2.basic new file mode 100644 index 0000000000..435497f444 --- /dev/null +++ b/Task/String-append/BASIC/string-append-2.basic @@ -0,0 +1,4 @@ + S$="Hello" + S$+=" World!" + PRINT S$ + END diff --git a/Task/String-append/C++/string-append.cpp b/Task/String-append/C++/string-append.cpp new file mode 100644 index 0000000000..58fc16bebf --- /dev/null +++ b/Task/String-append/C++/string-append.cpp @@ -0,0 +1,9 @@ +#include +#include + +int main( ) { + std::string greeting( "Hello" ) ; + greeting.append( " , world!" ) ; + std::cout << greeting << std::endl ; + return 0 ; +} diff --git a/Task/String-append/C/string-append.c b/Task/String-append/C/string-append.c new file mode 100644 index 0000000000..85db5b9c97 --- /dev/null +++ b/Task/String-append/C/string-append.c @@ -0,0 +1,25 @@ +#include +#include + +int main() +{ + char str[24]="Good Morning"; + char *cstr=" to all"; + char *cstr2=" !!!"; + int x=0; + //failure when space allocated to str is insufficient. + + if(sizeof(str)>strlen(str)+strlen(cstr)+strlen(cstr2)) + { + /* 1st method*/ + strcat(str,cstr); + + /*2nd method*/ + x=strlen(str); + sprintf(&str[x],"%s",cstr2); + + printf("%s\n",str); + + } + return 0; +} diff --git a/Task/String-append/Clojure/string-append-1.clj b/Task/String-append/Clojure/string-append-1.clj new file mode 100644 index 0000000000..b790c55a1c --- /dev/null +++ b/Task/String-append/Clojure/string-append-1.clj @@ -0,0 +1,8 @@ +user=> (def s "app") +#'user/s +user=> s +"app" +user=> (def s (str s "end")) +#'user/s +user=> s +"append" diff --git a/Task/String-append/Clojure/string-append-2.clj b/Task/String-append/Clojure/string-append-2.clj new file mode 100644 index 0000000000..b58d17c853 --- /dev/null +++ b/Task/String-append/Clojure/string-append-2.clj @@ -0,0 +1,2 @@ +user=> (let [s "ap", s (str s "pend")] s) +"append" diff --git a/Task/String-append/Common-Lisp/string-append.lisp b/Task/String-append/Common-Lisp/string-append.lisp new file mode 100644 index 0000000000..cfa6efc7e7 --- /dev/null +++ b/Task/String-append/Common-Lisp/string-append.lisp @@ -0,0 +1,8 @@ +(defmacro concatenatef (s &rest strs) + "Append additional strings to the first string in-place." + `(setf ,s (concatenate 'string ,s ,@strs))) +(defvar *str* "foo") +(concatenatef *str* "bar") +(format T "~a~%" *str*) +(concatenatef *str* "baz" "abc" "def") +(format T "~a~%" *str*) diff --git a/Task/String-append/D/string-append.d b/Task/String-append/D/string-append.d new file mode 100644 index 0000000000..afb7a0a89e --- /dev/null +++ b/Task/String-append/D/string-append.d @@ -0,0 +1,7 @@ +import std.stdio; + +void main() { + string s = "Hello"; + s ~= " world!"; + writeln(s); +} diff --git a/Task/String-append/Euphoria/string-append.euphoria b/Task/String-append/Euphoria/string-append.euphoria new file mode 100644 index 0000000000..2e8a5be0f0 --- /dev/null +++ b/Task/String-append/Euphoria/string-append.euphoria @@ -0,0 +1,7 @@ +sequence string = "String" + +printf(1,"%s\n",{string}) + +string &= " is now longer\n" + +printf(1,"%s",{string}) diff --git a/Task/String-append/Go/string-append.go b/Task/String-append/Go/string-append.go new file mode 100644 index 0000000000..f9461a8ab5 --- /dev/null +++ b/Task/String-append/Go/string-append.go @@ -0,0 +1,2 @@ +s := "foo" +s += "bar" diff --git a/Task/String-append/Haskell/string-append.hs b/Task/String-append/Haskell/string-append.hs new file mode 100644 index 0000000000..57dd0da9cc --- /dev/null +++ b/Task/String-append/Haskell/string-append.hs @@ -0,0 +1 @@ +main = putStrLn ("Hello" ++ "World") diff --git a/Task/String-append/Icon/string-append.icon b/Task/String-append/Icon/string-append.icon new file mode 100644 index 0000000000..5ac96d4551 --- /dev/null +++ b/Task/String-append/Icon/string-append.icon @@ -0,0 +1,5 @@ +procedure main() + s := "foo" + s ||:= "bar" + write(s) +end diff --git a/Task/String-append/J/string-append.j b/Task/String-append/J/string-append.j new file mode 100644 index 0000000000..b90e92307d --- /dev/null +++ b/Task/String-append/J/string-append.j @@ -0,0 +1,6 @@ + s=: 'new' + s +new + s=: s,' value' NB. append is in-place + s +new value diff --git a/Task/String-append/Java/string-append.java b/Task/String-append/Java/string-append.java new file mode 100644 index 0000000000..49450aeef8 --- /dev/null +++ b/Task/String-append/Java/string-append.java @@ -0,0 +1,8 @@ +String sa = "Hello"; +sa += ", World!"; +System.out.println(sa); + +StringBuilder ba = new StringBuilder(); +ba.append("Hello"); +ba.append(", World!"); +System.out.println(ba.toString()); diff --git a/Task/String-append/JavaScript/string-append.js b/Task/String-append/JavaScript/string-append.js new file mode 100644 index 0000000000..cfb9ef9266 --- /dev/null +++ b/Task/String-append/JavaScript/string-append.js @@ -0,0 +1,8 @@ +var s1 = "Hello"; +s1 += ", World!"; +print(s1); + +var s2 = "Goodbye"; +// concat() returns the strings together, but doesn't edit existing string +// concat can also have multiple parameters +print(s2.concat(", World!")); diff --git a/Task/String-append/Julia/string-append.julia b/Task/String-append/Julia/string-append.julia new file mode 100644 index 0000000000..878c7f5de2 --- /dev/null +++ b/Task/String-append/Julia/string-append.julia @@ -0,0 +1,2 @@ +s = "Hello" +s *= ", world!" diff --git a/Task/String-append/Mathematica/string-append.math b/Task/String-append/Mathematica/string-append.math new file mode 100644 index 0000000000..337ab4c6a5 --- /dev/null +++ b/Task/String-append/Mathematica/string-append.math @@ -0,0 +1,4 @@ +(* mutable strings are not supported *) +s1 = "testing"; +s1 = s1 <> " 123"; +s1 diff --git a/Task/String-append/NetRexx/string-append.netrexx b/Task/String-append/NetRexx/string-append.netrexx new file mode 100644 index 0000000000..2146e85aca --- /dev/null +++ b/Task/String-append/NetRexx/string-append.netrexx @@ -0,0 +1,3 @@ +s_ = 'Hello' +s_ = s_', world!' +say s_ diff --git a/Task/String-append/NewLISP/string-append.newlisp b/Task/String-append/NewLISP/string-append.newlisp new file mode 100644 index 0000000000..482c19f2eb --- /dev/null +++ b/Task/String-append/NewLISP/string-append.newlisp @@ -0,0 +1,3 @@ +(setq str "foo") +(push "bar" str -1) +(println str) diff --git a/Task/String-append/OCaml/string-append.ocaml b/Task/String-append/OCaml/string-append.ocaml new file mode 100644 index 0000000000..cc27e745ad --- /dev/null +++ b/Task/String-append/OCaml/string-append.ocaml @@ -0,0 +1,5 @@ +let () = + let s = Buffer.create 17 in + Buffer.add_string s "Bonjour"; + Buffer.add_string s " tout le monde!"; + print_endline (Buffer.contents s) diff --git a/Task/String-append/Objeck/string-append.objeck b/Task/String-append/Objeck/string-append.objeck new file mode 100644 index 0000000000..51425b2456 --- /dev/null +++ b/Task/String-append/Objeck/string-append.objeck @@ -0,0 +1,7 @@ +class Append { + function : Main(args : String[]) ~ Nil { + x := "foo"; + x->Append("bar"); + x->PrintLine(); + } +} diff --git a/Task/String-append/PARI-GP/string-append.pari b/Task/String-append/PARI-GP/string-append.pari new file mode 100644 index 0000000000..5116cd91f7 --- /dev/null +++ b/Task/String-append/PARI-GP/string-append.pari @@ -0,0 +1,2 @@ +s = "Hello"; +s = Str(s, ", world!") diff --git a/Task/String-append/PL-I/string-append.pli b/Task/String-append/PL-I/string-append.pli new file mode 100644 index 0000000000..04d013ba43 --- /dev/null +++ b/Task/String-append/PL-I/string-append.pli @@ -0,0 +1,6 @@ +Cat: procedure options (main); + declare s character (100) varying; + s = 'dust '; + s ||= 'bowl'; + put (s); +end Cat; diff --git a/Task/String-append/Pascal/string-append.pascal b/Task/String-append/Pascal/string-append.pascal new file mode 100644 index 0000000000..37f9cc5615 --- /dev/null +++ b/Task/String-append/Pascal/string-append.pascal @@ -0,0 +1,17 @@ +program StringAppend; +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + Classes + { you can add units after this }; + +var + s: String = 'Hello'; +begin + s += ' World !'; + WriteLn(S); + ReadLn; +end. diff --git a/Task/String-append/Perl-6/string-append.pl6 b/Task/String-append/Perl-6/string-append.pl6 new file mode 100644 index 0000000000..54e32d0069 --- /dev/null +++ b/Task/String-append/Perl-6/string-append.pl6 @@ -0,0 +1,3 @@ +my $str = "foo"; +$str ~= "bar"; +say $str; diff --git a/Task/String-append/Perl/string-append.pl b/Task/String-append/Perl/string-append.pl new file mode 100644 index 0000000000..57d1b6e33e --- /dev/null +++ b/Task/String-append/Perl/string-append.pl @@ -0,0 +1,3 @@ +my $str = 'Foo'; +$str .= 'bar'; +print $str; diff --git a/Task/String-append/PicoLisp/string-append.l b/Task/String-append/PicoLisp/string-append.l new file mode 100644 index 0000000000..c4b30daa6e --- /dev/null +++ b/Task/String-append/PicoLisp/string-append.l @@ -0,0 +1,3 @@ +(setq Str1 "12345678") +(setq Str1 (pack Str1 "9!")) +(println Str1) diff --git a/Task/String-append/PureBasic/string-append.purebasic b/Task/String-append/PureBasic/string-append.purebasic new file mode 100644 index 0000000000..8e9d65024b --- /dev/null +++ b/Task/String-append/PureBasic/string-append.purebasic @@ -0,0 +1,9 @@ +S$ = "Hello" +S$ = S$ + " Wo" ;by referencing the string twice +S$ + "rld!" ;by referencing the string once +If OpenConsole() + PrintN(S$) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/String-append/Python/string-append.py b/Task/String-append/Python/string-append.py new file mode 100644 index 0000000000..eb36818b48 --- /dev/null +++ b/Task/String-append/Python/string-append.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- # + +str = "12345678"; +str += "9!"; +print(str) diff --git a/Task/String-append/README b/Task/String-append/README new file mode 100644 index 0000000000..38b8ce1cad --- /dev/null +++ b/Task/String-append/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/String_append diff --git a/Task/String-append/REXX/string-append-1.rexx b/Task/String-append/REXX/string-append-1.rexx new file mode 100644 index 0000000000..c04948e9a4 --- /dev/null +++ b/Task/String-append/REXX/string-append-1.rexx @@ -0,0 +1,3 @@ +s='he' +s=s'llo world!' +Say s diff --git a/Task/String-append/REXX/string-append-2.rexx b/Task/String-append/REXX/string-append-2.rexx new file mode 100644 index 0000000000..e018abef4e --- /dev/null +++ b/Task/String-append/REXX/string-append-2.rexx @@ -0,0 +1,3 @@ +s="He" +s=s || 'llo, World!' /*same as: s=s||'llo, World!' */ +say s diff --git a/Task/String-append/Racket/string-append.rkt b/Task/String-append/Racket/string-append.rkt new file mode 100644 index 0000000000..90b0c69dcb --- /dev/null +++ b/Task/String-append/Racket/string-append.rkt @@ -0,0 +1,12 @@ +;there is no built-in way to set! append in racket +(define mystr "foo") +(set! mystr (string-append mystr " bar")) +(displayln mystr) + +;but you can create a quick macro to solve that problem +(define-syntax-rule (set-append! str value) + (set! str (string-append str value))) + +(define mymacrostr "foo") +(set-append! mymacrostr " bar") +(displayln mystr) diff --git a/Task/String-append/Ruby/string-append.rb b/Task/String-append/Ruby/string-append.rb new file mode 100644 index 0000000000..79065fcdce --- /dev/null +++ b/Task/String-append/Ruby/string-append.rb @@ -0,0 +1,4 @@ +s = "Hello wo" +s += "rld" # new string object +s << "!" # mutates in place, same object +puts s diff --git a/Task/String-append/Scala/string-append.scala b/Task/String-append/Scala/string-append.scala new file mode 100644 index 0000000000..0e7fd1821d --- /dev/null +++ b/Task/String-append/Scala/string-append.scala @@ -0,0 +1,8 @@ + var d = "Hello" // Mutables are discouraged //> d : String = Hello + d += ", World!" // var contains a totally new re-instantiationed String + + val s = "Hello" // Immutables are recommended //> s : String = Hello + val s1 = s + s //> s1 : String = HelloHello + val f2 = () => " !" //Function assigned to variable + //> f2 : () => String = + println(s1 + f2()); //> HelloHello ! diff --git a/Task/String-append/Seed7/string-append.seed7 b/Task/String-append/Seed7/string-append.seed7 new file mode 100644 index 0000000000..7a1bb7182c --- /dev/null +++ b/Task/String-append/Seed7/string-append.seed7 @@ -0,0 +1,9 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: str is "12345678"; + begin + str &:= "9!"; + writeln(str); + end func; diff --git a/Task/String-append/Tcl/string-append.tcl b/Task/String-append/Tcl/string-append.tcl new file mode 100644 index 0000000000..e92aaa4584 --- /dev/null +++ b/Task/String-append/Tcl/string-append.tcl @@ -0,0 +1,4 @@ +set s "he" +set s "${s}llo wo"; # The braces distinguish varname from text to concatenate +append s "rld" +puts $s diff --git a/Task/String-append/VBA/string-append.vba b/Task/String-append/VBA/string-append.vba new file mode 100644 index 0000000000..5c103025a7 --- /dev/null +++ b/Task/String-append/VBA/string-append.vba @@ -0,0 +1,6 @@ +Function StringAppend() +Dim s As String +s = "foo" +s = s & "bar" +Debug.Print s +End Function diff --git a/Task/Character-matching/00DESCRIPTION b/Task/String-matching/00DESCRIPTION similarity index 100% rename from Task/Character-matching/00DESCRIPTION rename to Task/String-matching/00DESCRIPTION diff --git a/Task/Character-matching/00META.yaml b/Task/String-matching/00META.yaml similarity index 100% rename from Task/Character-matching/00META.yaml rename to Task/String-matching/00META.yaml diff --git a/Task/Character-matching/ALGOL-68/character-matching.alg b/Task/String-matching/ALGOL-68/string-matching.alg similarity index 100% rename from Task/Character-matching/ALGOL-68/character-matching.alg rename to Task/String-matching/ALGOL-68/string-matching.alg diff --git a/Task/String-matching/AWK/string-matching.awk b/Task/String-matching/AWK/string-matching.awk new file mode 100644 index 0000000000..b11ad04419 --- /dev/null +++ b/Task/String-matching/AWK/string-matching.awk @@ -0,0 +1,20 @@ +#!/usr/bin/awk -f +{ + if ($1 ~ "^"$2) { + print $1" begins with "$2; + } else { + print $1" does not begin with "$2; + } + + if ($1 ~ $2) { + print $1" contains "$2; + } else { + print $1" does not contain "$2; + } + + if ($1 ~ $2"$") { + print $1" ends with "$2; + } else { + print $1" does not end with "$2; + } +} diff --git a/Task/Character-matching/Ada/character-matching.ada b/Task/String-matching/Ada/string-matching.ada similarity index 100% rename from Task/Character-matching/Ada/character-matching.ada rename to Task/String-matching/Ada/string-matching.ada diff --git a/Task/String-matching/Aime/string-matching.aime b/Task/String-matching/Aime/string-matching.aime new file mode 100644 index 0000000000..272fd0ed81 --- /dev/null +++ b/Task/String-matching/Aime/string-matching.aime @@ -0,0 +1,23 @@ +text s, t; +data b; + +s = "Bangkok"; +t = "Bang"; + +b_cast(b, s); + +o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, t) == 0, + b_seek(b, t) != -1, + b_seek(b, t) != -1 && b_seek(b, t) + length(t) == length(s)); + +t = "ok"; + +o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, t) == 0, + b_seek(b, t) != -1, + b_seek(b, t) != -1 && b_seek(b, t) + length(t) == length(s)); + +t = "Summer"; + +o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b_seek(b, t) == 0, + b_seek(b, t) != -1, + b_seek(b, t) != -1 && b_seek(b, t) + length(t) == length(s)); diff --git a/Task/Character-matching/AutoHotkey/character-matching.ahk b/Task/String-matching/AutoHotkey/string-matching.ahk similarity index 100% rename from Task/Character-matching/AutoHotkey/character-matching.ahk rename to Task/String-matching/AutoHotkey/string-matching.ahk diff --git a/Task/Character-matching/AutoIt/character-matching.autoit b/Task/String-matching/AutoIt/string-matching.autoit similarity index 100% rename from Task/Character-matching/AutoIt/character-matching.autoit rename to Task/String-matching/AutoIt/string-matching.autoit diff --git a/Task/Character-matching/BASIC/character-matching.basic b/Task/String-matching/BASIC/string-matching-1.basic similarity index 100% rename from Task/Character-matching/BASIC/character-matching.basic rename to Task/String-matching/BASIC/string-matching-1.basic diff --git a/Task/String-matching/BASIC/string-matching-2.basic b/Task/String-matching/BASIC/string-matching-2.basic new file mode 100644 index 0000000000..ff40022c8e --- /dev/null +++ b/Task/String-matching/BASIC/string-matching-2.basic @@ -0,0 +1,18 @@ +10 A$ = "THIS, THAT, AND THE OTHER THING" +20 S$ = "TH" +30 DEF FN S(P) = MID$(A$, P, LEN(S$)) = S$ +40 PRINT A$ : PRINT + +110 S$(1) = "STARTS" +120 S$(0) = "DOES NOT START" +130 PRINT S$(FN S(1))" WITH "S$ : PRINT + +210 R$ = "" : FOR I = 1 TO LEN(A$) - LEN(S$) : IF FN S(I) THEN R$ = R$ + STR$(I) + " " +220 NEXT I +230 IF LEN(R$) = 0 THEN PRINT "DOES NOT CONTAIN "S$ +240 IF LEN(R$) THEN PRINT "CONTAINS "S$" LOCATED AT POSITION "R$ +250 PRINT + +310 E$(1) = "ENDS" +320 E$(0) = "DOES NOT END" +330 PRINT E$(FN S(LEN(A$) - LEN(S$) + 1))" WITH "S$ diff --git a/Task/Character-matching/BBC-BASIC/character-matching.bbc b/Task/String-matching/BBC-BASIC/string-matching.bbc similarity index 100% rename from Task/Character-matching/BBC-BASIC/character-matching.bbc rename to Task/String-matching/BBC-BASIC/string-matching.bbc diff --git a/Task/Character-matching/Bracmat/character-matching.bracmat b/Task/String-matching/Bracmat/string-matching.bracmat similarity index 100% rename from Task/Character-matching/Bracmat/character-matching.bracmat rename to Task/String-matching/Bracmat/string-matching.bracmat diff --git a/Task/Character-matching/C++/character-matching.cpp b/Task/String-matching/C++/string-matching.cpp similarity index 100% rename from Task/Character-matching/C++/character-matching.cpp rename to Task/String-matching/C++/string-matching.cpp diff --git a/Task/Character-matching/C/character-matching-1.c b/Task/String-matching/C/string-matching-1.c similarity index 100% rename from Task/Character-matching/C/character-matching-1.c rename to Task/String-matching/C/string-matching-1.c diff --git a/Task/Character-matching/C/character-matching-2.c b/Task/String-matching/C/string-matching-2.c similarity index 100% rename from Task/Character-matching/C/character-matching-2.c rename to Task/String-matching/C/string-matching-2.c diff --git a/Task/Character-matching/Clojure/character-matching.clj b/Task/String-matching/Clojure/string-matching.clj similarity index 100% rename from Task/Character-matching/Clojure/character-matching.clj rename to Task/String-matching/Clojure/string-matching.clj diff --git a/Task/Character-matching/CoffeeScript/character-matching.coffee b/Task/String-matching/CoffeeScript/string-matching.coffee similarity index 100% rename from Task/Character-matching/CoffeeScript/character-matching.coffee rename to Task/String-matching/CoffeeScript/string-matching.coffee diff --git a/Task/String-matching/Common-Lisp/string-matching.lisp b/Task/String-matching/Common-Lisp/string-matching.lisp new file mode 100644 index 0000000000..878e106aa5 --- /dev/null +++ b/Task/String-matching/Common-Lisp/string-matching.lisp @@ -0,0 +1,28 @@ +(defun starts-with-p (str1 str2) + "Determine whether `str1` starts with `str2`" + (let ((p (search str2 str1))) + (and p (= 0 p)))) + +(print (starts-with-p "foobar" "foo")) ; T +(print (starts-with-p "foobar" "bar")) ; NIL + +(defun ends-with-p (str1 str2) + "Determine whether `str1` ends with `str2`" + (let ((p (mismatch str2 str1 :from-end T))) + (or (not p) (= 0 p)))) + +(print (ends-with-p "foobar" "foo")) ; NIL +(print (ends-with-p "foobar" "bar")) ; T + +(defun containsp (str1 str2) + "Determine whether `str1` contains `str2`. + Instead of just returning T, return a list of starting locations + for every occurence of `str2` in `str1`" + (unless (string-equal str2 "") + (loop for p = (search str2 str1) then (search str2 str1 :start2 (1+ p)) + while p + collect p))) + +(print (containsp "foobar" "oba")) ; (2) +(print (containsp "ababaBa" "ba")) ; (1 3) +(print (containsp "foobar" "x")) ; NIL diff --git a/Task/String-matching/Component-Pascal/string-matching.component b/Task/String-matching/Component-Pascal/string-matching.component new file mode 100644 index 0000000000..05f4479a15 --- /dev/null +++ b/Task/String-matching/Component-Pascal/string-matching.component @@ -0,0 +1,113 @@ +MODULE StringMatch; +IMPORT StdLog,Strings; +CONST + strSize = 1024; + patSize = 256; + +TYPE + Matcher* = POINTER TO LIMITED RECORD + str: ARRAY strSize OF CHAR; + pat: ARRAY patSize OF CHAR; + pos: INTEGER + END; + +PROCEDURE NewMatcher*(IN str: ARRAY OF CHAR): Matcher; +VAR + m: Matcher; +BEGIN + NEW(m);m.str := str$;m.pos:= 0; + RETURN m +END NewMatcher; + +PROCEDURE (m: Matcher) Match*(IN pat: ARRAY OF CHAR): INTEGER,NEW; +VAR + pos: INTEGER; +BEGIN + m.pat := pat$; + pos := m.pos; + Strings.Find(m.str,m.pat,pos,m.pos); + RETURN m.pos +END Match; + +PROCEDURE (m: Matcher) Next*(): INTEGER, NEW; +VAR + pos: INTEGER; +BEGIN + pos := m.pos + LEN(m.pat$); + Strings.Find(m.str,m.pat,pos,m.pos); + RETURN m.pos; +END Next; + +(* Some Helper functions based on Strings module *) +PROCEDURE StartsWith(IN str: ARRAY OF CHAR;IN pat: ARRAY OF CHAR): BOOLEAN; +VAR + pos: INTEGER; +BEGIN + Strings.Find(str,pat,0,pos); + RETURN pos = 0 +END StartsWith; + +PROCEDURE Contains(IN str: ARRAY OF CHAR;IN pat: ARRAY OF CHAR; OUT pos: INTEGER): BOOLEAN; +BEGIN + Strings.Find(str,pat,0,pos); + RETURN pos >= 0 +END Contains; + +PROCEDURE EndsWith(IN str: ARRAY OF CHAR;IN pat: ARRAY OF CHAR): BOOLEAN; +VAR + pos: INTEGER; +BEGIN + Strings.Find(str,pat,0,pos); + RETURN pos + LEN(pat$) = LEN(str$) +END EndsWith; + +PROCEDURE Do*; +CONST + aStr = "abcdefghijklmnopqrstuvwxyz"; +VAR + pat: ARRAY 128 OF CHAR; + res: BOOLEAN; + at: INTEGER; + m: Matcher; +BEGIN + (* StartsWith *) + pat := "abc"; + StdLog.String(aStr + " startsWith " + pat + " :>");StdLog.Bool(StartsWith(aStr,pat));StdLog.Ln; + pat := "cba"; + StdLog.String(aStr + " startsWith " + pat + " :>");StdLog.Bool(StartsWith(aStr,pat));StdLog.Ln; + pat := "def"; + StdLog.String(aStr + " startsWith " + pat + " :>");StdLog.Bool(StartsWith(aStr,pat));StdLog.Ln; + StdLog.Ln; + (* Contains *) + pat := 'def'; + StdLog.String(aStr + " contains " + pat + " :>");StdLog.Bool(Contains(aStr,pat,at)); + StdLog.String(" at: ");StdLog.Int(at);StdLog.Ln; + pat := 'efd'; + StdLog.String(aStr + " contains " + pat + " :>");StdLog.Bool(Contains(aStr,pat,at)); + StdLog.String(" at: ");StdLog.Int(at);StdLog.Ln; + pat := 'abc'; + StdLog.String(aStr + " contains " + pat + " :>");StdLog.Bool(Contains(aStr,pat,at)); + StdLog.String(" at: ");StdLog.Int(at);StdLog.Ln; + pat := 'xyz'; + StdLog.String(aStr + " contains " + pat + " :>");StdLog.Bool(Contains(aStr,pat,at)); + StdLog.String(" at: ");StdLog.Int(at);StdLog.Ln; + StdLog.Ln; + (* EndsWith *) + pat := 'xyz'; + StdLog.String(aStr + " endsWith " + pat + " :>");StdLog.Bool(EndsWith(aStr,pat));StdLog.Ln; + pat := 'zyx'; + StdLog.String(aStr + " endsWith " + pat + " :>");StdLog.Bool(EndsWith(aStr,pat));StdLog.Ln; + pat := 'abc'; + StdLog.String(aStr + " endsWith " + pat + " :>");StdLog.Bool(EndsWith(aStr,pat));StdLog.Ln; + pat:= 'def'; + StdLog.String(aStr + " endsWith " + pat + " :>");StdLog.Bool(EndsWith(aStr,pat));StdLog.Ln; + StdLog.Ln; + + m := NewMatcher("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); + StdLog.String("Matching 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' against 'abc':> "); + StdLog.Ln; + StdLog.String("Match at: ");StdLog.Int(m.Match("abc"));StdLog.Ln; + StdLog.String("Match at: ");StdLog.Int(m.Next());StdLog.Ln; + StdLog.String("Match at: ");StdLog.Int(m.Next());StdLog.Ln +END Do; +END StringMatch. diff --git a/Task/String-matching/D/string-matching.d b/Task/String-matching/D/string-matching.d new file mode 100644 index 0000000000..0a05ba7ed1 --- /dev/null +++ b/Task/String-matching/D/string-matching.d @@ -0,0 +1,16 @@ +void main() { + import std.stdio; + import std.algorithm: startsWith, endsWith, find, countUntil; + + "abcd".startsWith("ab").writeln; // true + "abcd".endsWith("zn").writeln; // false + "abab".find("bb").writeln; // empty array (no match) + "abcd".find("bc").writeln; // "bcd" (substring start + // at match) + "abab".countUntil("bb").writeln; // -1 (no match) + "abab".countUntil("ba").writeln; // 1 (index of 1st match) + + // std.algorithm.startsWith also works on arrays and ranges: + [1, 2, 3].countUntil(3).writeln; // 2 + [1, 2, 3].countUntil([2, 3]).writeln; // 1 +} diff --git a/Task/Character-matching/Delphi/character-matching.delphi b/Task/String-matching/Delphi/string-matching.delphi similarity index 100% rename from Task/Character-matching/Delphi/character-matching.delphi rename to Task/String-matching/Delphi/string-matching.delphi diff --git a/Task/Character-matching/E/character-matching.e b/Task/String-matching/E/string-matching.e similarity index 100% rename from Task/Character-matching/E/character-matching.e rename to Task/String-matching/E/string-matching.e diff --git a/Task/String-matching/Elena/string-matching.elena b/Task/String-matching/Elena/string-matching.elena new file mode 100644 index 0000000000..53708bf35f --- /dev/null +++ b/Task/String-matching/Elena/string-matching.elena @@ -0,0 +1,22 @@ +#define system'routines. +#define extensions. + +// --- Program --- + +#symbol program = +[ + literalControl starting:"hello" &with:"hel" ? + [ + consoleEx writeLine:"hello starts with hel". + ]. + + literalControl ending:"hello" &with:"llo" ? + [ + consoleEx writeLine:"hello ends with llo". + ]. + + literalControl contain:"el" &in:"hello" ? + [ + consoleEx writeLine:"hello contains el". + ]. +]. diff --git a/Task/String-matching/Elixir/string-matching.elixir b/Task/String-matching/Elixir/string-matching.elixir new file mode 100644 index 0000000000..1a1deaa6b7 --- /dev/null +++ b/Task/String-matching/Elixir/string-matching.elixir @@ -0,0 +1,18 @@ +s1 = "abcd" +s2 = "adab" +s3 = "ab" + +String.starts_with?(s1, s3) +# => true +String.starts_with?(s2, s3) +# => false + +String.ends_with?(s1, s3) +# => false +String.ends_with?(s2, s3) +# => true + +String.contains?(s1, s3) +# => true +String.contains?(s2, s3) +# => true diff --git a/Task/Character-matching/Erlang/character-matching.erl b/Task/String-matching/Erlang/string-matching.erl similarity index 100% rename from Task/Character-matching/Erlang/character-matching.erl rename to Task/String-matching/Erlang/string-matching.erl diff --git a/Task/Character-matching/Euphoria/character-matching.euphoria b/Task/String-matching/Euphoria/string-matching.euphoria similarity index 100% rename from Task/Character-matching/Euphoria/character-matching.euphoria rename to Task/String-matching/Euphoria/string-matching.euphoria diff --git a/Task/Character-matching/FBSL/character-matching.fbsl b/Task/String-matching/FBSL/string-matching.fbsl similarity index 100% rename from Task/Character-matching/FBSL/character-matching.fbsl rename to Task/String-matching/FBSL/string-matching.fbsl diff --git a/Task/Character-matching/Fantom/character-matching.fantom b/Task/String-matching/Fantom/string-matching.fantom similarity index 100% rename from Task/Character-matching/Fantom/character-matching.fantom rename to Task/String-matching/Fantom/string-matching.fantom diff --git a/Task/Character-matching/Forth/character-matching.fth b/Task/String-matching/Forth/string-matching.fth similarity index 100% rename from Task/Character-matching/Forth/character-matching.fth rename to Task/String-matching/Forth/string-matching.fth diff --git a/Task/Character-matching/GML/character-matching.gml b/Task/String-matching/GML/string-matching.gml similarity index 100% rename from Task/Character-matching/GML/character-matching.gml rename to Task/String-matching/GML/string-matching.gml diff --git a/Task/Character-matching/Go/character-matching.go b/Task/String-matching/Go/string-matching.go similarity index 100% rename from Task/Character-matching/Go/character-matching.go rename to Task/String-matching/Go/string-matching.go diff --git a/Task/String-matching/Groovy/string-matching.groovy b/Task/String-matching/Groovy/string-matching.groovy new file mode 100644 index 0000000000..74a5f4a568 --- /dev/null +++ b/Task/String-matching/Groovy/string-matching.groovy @@ -0,0 +1,23 @@ +assert "abcd".startsWith("ab") +assert ! "abcd".startsWith("zn") +assert "abcd".endsWith("cd") +assert ! "abcd".endsWith("zn") +assert "abab".contains("ba") +assert ! "abab".contains("bb") + + +assert "abab".indexOf("bb") == -1 // not found flag +assert "abab".indexOf("ab") == 0 + +def indicesOf = { string, substring -> + if (!string) { return [] } + def indices = [-1] + while (true) { + indices << string.indexOf(substring, indices.last()+1) + if (indices.last() == -1) break + } + indices[1..<(indices.size()-1)] +} +assert indicesOf("abab", "ab") == [0, 2] +assert indicesOf("abab", "ba") == [1] +assert indicesOf("abab", "xy") == [] diff --git a/Task/Character-matching/Haskell/character-matching-1.hs b/Task/String-matching/Haskell/string-matching-1.hs similarity index 100% rename from Task/Character-matching/Haskell/character-matching-1.hs rename to Task/String-matching/Haskell/string-matching-1.hs diff --git a/Task/Character-matching/Haskell/character-matching-2.hs b/Task/String-matching/Haskell/string-matching-2.hs similarity index 100% rename from Task/Character-matching/Haskell/character-matching-2.hs rename to Task/String-matching/Haskell/string-matching-2.hs diff --git a/Task/Character-matching/J/character-matching-1.j b/Task/String-matching/J/string-matching-1.j similarity index 100% rename from Task/Character-matching/J/character-matching-1.j rename to Task/String-matching/J/string-matching-1.j diff --git a/Task/Character-matching/J/character-matching-2.j b/Task/String-matching/J/string-matching-2.j similarity index 100% rename from Task/Character-matching/J/character-matching-2.j rename to Task/String-matching/J/string-matching-2.j diff --git a/Task/Character-matching/J/character-matching-3.j b/Task/String-matching/J/string-matching-3.j similarity index 100% rename from Task/Character-matching/J/character-matching-3.j rename to Task/String-matching/J/string-matching-3.j diff --git a/Task/Character-matching/Java/character-matching.java b/Task/String-matching/Java/string-matching.java similarity index 100% rename from Task/Character-matching/Java/character-matching.java rename to Task/String-matching/Java/string-matching.java diff --git a/Task/Character-matching/JavaScript/character-matching.js b/Task/String-matching/JavaScript/string-matching.js similarity index 100% rename from Task/Character-matching/JavaScript/character-matching.js rename to Task/String-matching/JavaScript/string-matching.js diff --git a/Task/Character-matching/Julia/character-matching.julia b/Task/String-matching/Julia/string-matching.julia similarity index 100% rename from Task/Character-matching/Julia/character-matching.julia rename to Task/String-matching/Julia/string-matching.julia diff --git a/Task/Character-matching/K/character-matching-1.k b/Task/String-matching/K/string-matching-1.k similarity index 100% rename from Task/Character-matching/K/character-matching-1.k rename to Task/String-matching/K/string-matching-1.k diff --git a/Task/Character-matching/K/character-matching-2.k b/Task/String-matching/K/string-matching-2.k similarity index 100% rename from Task/Character-matching/K/character-matching-2.k rename to Task/String-matching/K/string-matching-2.k diff --git a/Task/Character-matching/Lang5/character-matching.lang5 b/Task/String-matching/Lang5/string-matching.lang5 similarity index 100% rename from Task/Character-matching/Lang5/character-matching.lang5 rename to Task/String-matching/Lang5/string-matching.lang5 diff --git a/Task/Character-matching/Liberty-BASIC/character-matching.liberty b/Task/String-matching/Liberty-BASIC/string-matching.liberty similarity index 100% rename from Task/Character-matching/Liberty-BASIC/character-matching.liberty rename to Task/String-matching/Liberty-BASIC/string-matching.liberty diff --git a/Task/Character-matching/Logo/character-matching.logo b/Task/String-matching/Logo/string-matching.logo similarity index 100% rename from Task/Character-matching/Logo/character-matching.logo rename to Task/String-matching/Logo/string-matching.logo diff --git a/Task/Character-matching/Lua/character-matching.lua b/Task/String-matching/Lua/string-matching.lua similarity index 100% rename from Task/Character-matching/Lua/character-matching.lua rename to Task/String-matching/Lua/string-matching.lua diff --git a/Task/Character-matching/MATLAB/character-matching.m b/Task/String-matching/MATLAB/string-matching.m similarity index 100% rename from Task/Character-matching/MATLAB/character-matching.m rename to Task/String-matching/MATLAB/string-matching.m diff --git a/Task/Character-matching/Maple/character-matching.maple b/Task/String-matching/Maple/string-matching.maple similarity index 100% rename from Task/Character-matching/Maple/character-matching.maple rename to Task/String-matching/Maple/string-matching.maple diff --git a/Task/Character-matching/Mathematica/character-matching.math b/Task/String-matching/Mathematica/string-matching.math similarity index 100% rename from Task/Character-matching/Mathematica/character-matching.math rename to Task/String-matching/Mathematica/string-matching.math diff --git a/Task/Character-matching/NetRexx/character-matching.netrexx b/Task/String-matching/NetRexx/string-matching.netrexx similarity index 100% rename from Task/Character-matching/NetRexx/character-matching.netrexx rename to Task/String-matching/NetRexx/string-matching.netrexx diff --git a/Task/String-matching/NewLISP/string-matching.newlisp b/Task/String-matching/NewLISP/string-matching.newlisp new file mode 100644 index 0000000000..15935e4438 --- /dev/null +++ b/Task/String-matching/NewLISP/string-matching.newlisp @@ -0,0 +1,18 @@ +(setq str "abcdefbcghi") + +;; test if str starts with "ab" +(starts-with str "ab") + +;; find "bc" inside str +(find "bc" str) + +;; test if str ends with "ghi" +(ends-with str "ghi") + +;; find all positions of pattern inside str +(define (find-all-pos pattern str) + (let ((idx -1) (pos '())) + (while (setq idx (find pattern str 0 (+ idx 1))) + (push idx pos -1)))) + +(find-all-pos "bc" str) diff --git a/Task/Character-matching/OCaml/character-matching-1.ocaml b/Task/String-matching/OCaml/string-matching-1.ocaml similarity index 100% rename from Task/Character-matching/OCaml/character-matching-1.ocaml rename to Task/String-matching/OCaml/string-matching-1.ocaml diff --git a/Task/Character-matching/OCaml/character-matching-2.ocaml b/Task/String-matching/OCaml/string-matching-2.ocaml similarity index 100% rename from Task/Character-matching/OCaml/character-matching-2.ocaml rename to Task/String-matching/OCaml/string-matching-2.ocaml diff --git a/Task/Character-matching/OCaml/character-matching-3.ocaml b/Task/String-matching/OCaml/string-matching-3.ocaml similarity index 100% rename from Task/Character-matching/OCaml/character-matching-3.ocaml rename to Task/String-matching/OCaml/string-matching-3.ocaml diff --git a/Task/Character-matching/OCaml/character-matching-4.ocaml b/Task/String-matching/OCaml/string-matching-4.ocaml similarity index 100% rename from Task/Character-matching/OCaml/character-matching-4.ocaml rename to Task/String-matching/OCaml/string-matching-4.ocaml diff --git a/Task/Character-matching/OCaml/character-matching-5.ocaml b/Task/String-matching/OCaml/string-matching-5.ocaml similarity index 100% rename from Task/Character-matching/OCaml/character-matching-5.ocaml rename to Task/String-matching/OCaml/string-matching-5.ocaml diff --git a/Task/Character-matching/Objeck/character-matching.objeck b/Task/String-matching/Objeck/string-matching.objeck similarity index 100% rename from Task/Character-matching/Objeck/character-matching.objeck rename to Task/String-matching/Objeck/string-matching.objeck diff --git a/Task/Character-matching/Objective-C/character-matching.m b/Task/String-matching/Objective-C/string-matching.m similarity index 100% rename from Task/Character-matching/Objective-C/character-matching.m rename to Task/String-matching/Objective-C/string-matching.m diff --git a/Task/Character-matching/OxygenBasic/character-matching.oxy b/Task/String-matching/OxygenBasic/string-matching.oxy similarity index 100% rename from Task/Character-matching/OxygenBasic/character-matching.oxy rename to Task/String-matching/OxygenBasic/string-matching.oxy diff --git a/Task/Character-matching/PARI-GP/character-matching.pari b/Task/String-matching/PARI-GP/string-matching.pari similarity index 100% rename from Task/Character-matching/PARI-GP/character-matching.pari rename to Task/String-matching/PARI-GP/string-matching.pari diff --git a/Task/Character-matching/PHP/character-matching-1.php b/Task/String-matching/PHP/string-matching-1.php similarity index 100% rename from Task/Character-matching/PHP/character-matching-1.php rename to Task/String-matching/PHP/string-matching-1.php diff --git a/Task/Character-matching/PHP/character-matching-2.php b/Task/String-matching/PHP/string-matching-2.php similarity index 100% rename from Task/Character-matching/PHP/character-matching-2.php rename to Task/String-matching/PHP/string-matching-2.php diff --git a/Task/Character-matching/PL-I/character-matching-1.pli b/Task/String-matching/PL-I/string-matching-1.pli similarity index 100% rename from Task/Character-matching/PL-I/character-matching-1.pli rename to Task/String-matching/PL-I/string-matching-1.pli diff --git a/Task/Character-matching/PL-I/character-matching-2.pli b/Task/String-matching/PL-I/string-matching-2.pli similarity index 100% rename from Task/Character-matching/PL-I/character-matching-2.pli rename to Task/String-matching/PL-I/string-matching-2.pli diff --git a/Task/Character-matching/Perl-6/character-matching.pl6 b/Task/String-matching/Perl-6/string-matching.pl6 similarity index 100% rename from Task/Character-matching/Perl-6/character-matching.pl6 rename to Task/String-matching/Perl-6/string-matching.pl6 diff --git a/Task/String-matching/Perl/string-matching-1.pl b/Task/String-matching/Perl/string-matching-1.pl new file mode 100644 index 0000000000..b6c22ae517 --- /dev/null +++ b/Task/String-matching/Perl/string-matching-1.pl @@ -0,0 +1,3 @@ +$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2 +$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2 +$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-2.pl b/Task/String-matching/Perl/string-matching-2.pl new file mode 100644 index 0000000000..9cca1fc290 --- /dev/null +++ b/Task/String-matching/Perl/string-matching-2.pl @@ -0,0 +1,3 @@ +index($str1, $str2) == 0 # true if $str1 starts with $str2 +index($str1, $str2) != -1 # true if $str1 contains $str2 +rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-3.pl b/Task/String-matching/Perl/string-matching-3.pl new file mode 100644 index 0000000000..9c4bb1f632 --- /dev/null +++ b/Task/String-matching/Perl/string-matching-3.pl @@ -0,0 +1,2 @@ +substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2 +substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-4.pl b/Task/String-matching/Perl/string-matching-4.pl new file mode 100644 index 0000000000..a076cd02f1 --- /dev/null +++ b/Task/String-matching/Perl/string-matching-4.pl @@ -0,0 +1 @@ +print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex diff --git a/Task/String-matching/Perl/string-matching-5.pl b/Task/String-matching/Perl/string-matching-5.pl new file mode 100644 index 0000000000..a3dcea4868 --- /dev/null +++ b/Task/String-matching/Perl/string-matching-5.pl @@ -0,0 +1 @@ +my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index diff --git a/Task/Character-matching/PicoLisp/character-matching.l b/Task/String-matching/PicoLisp/string-matching.l similarity index 100% rename from Task/Character-matching/PicoLisp/character-matching.l rename to Task/String-matching/PicoLisp/string-matching.l diff --git a/Task/Character-matching/PowerShell/character-matching.psh b/Task/String-matching/PowerShell/string-matching.psh similarity index 100% rename from Task/Character-matching/PowerShell/character-matching.psh rename to Task/String-matching/PowerShell/string-matching.psh diff --git a/Task/Character-matching/PureBasic/character-matching-1.purebasic b/Task/String-matching/PureBasic/string-matching-1.purebasic similarity index 100% rename from Task/Character-matching/PureBasic/character-matching-1.purebasic rename to Task/String-matching/PureBasic/string-matching-1.purebasic diff --git a/Task/Character-matching/PureBasic/character-matching-2.purebasic b/Task/String-matching/PureBasic/string-matching-2.purebasic similarity index 100% rename from Task/Character-matching/PureBasic/character-matching-2.purebasic rename to Task/String-matching/PureBasic/string-matching-2.purebasic diff --git a/Task/Character-matching/PureBasic/character-matching-3.purebasic b/Task/String-matching/PureBasic/string-matching-3.purebasic similarity index 100% rename from Task/Character-matching/PureBasic/character-matching-3.purebasic rename to Task/String-matching/PureBasic/string-matching-3.purebasic diff --git a/Task/Character-matching/Python/character-matching.py b/Task/String-matching/Python/string-matching.py similarity index 100% rename from Task/Character-matching/Python/character-matching.py rename to Task/String-matching/Python/string-matching.py diff --git a/Task/String-matching/README b/Task/String-matching/README new file mode 100644 index 0000000000..5ab5b88807 --- /dev/null +++ b/Task/String-matching/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/String_matching diff --git a/Task/String-matching/REXX/string-matching.rexx b/Task/String-matching/REXX/string-matching.rexx new file mode 100644 index 0000000000..380bb91287 --- /dev/null +++ b/Task/String-matching/REXX/string-matching.rexx @@ -0,0 +1,33 @@ +/*REXX program demonstrates some basic character string testing. */ +parse arg a b /*obtain A and B from the C.L. */ +say 'string A = ' a /*display string A to terminal.*/ +say 'string B = ' b /* " " B " " */ +say +if left(A,length(b))==b then say 'string A starts with string B' + else say "string A doesn't start with string B" +say + /*another method, however a wee bit obtuse. */ +/*¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬ +if compare(a,b)==length(b) then say 'string A starts with string B' + else say "string A doesn't start with string B" +¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬*/ + /* [↑] above is a big comment. */ +p=pos(b,a) +if p==0 then say "string A doesn't contain string B" + else say 'string A contains string B (starting in position' p")" +say +if right(A,length(b))==b then say 'string A ends with string B' + else say "string A doesn't end with string B" +say +Ps=''; p=0; do until p==0 + p=pos(b, a, p+1) + if p\==0 then Ps = Ps',' p + end /*until ···*/ +Ps=space(strip(Ps, 'L', ",")) +times=words(Ps) +if times==0 then say "string A doesn't contain string B" + else say 'string A contains string B ', + times 'time'left('s',times>1), + "(at position"left('s', times>1) Ps')' + + /*stick a fork in it, we're done.*/ diff --git a/Task/Character-matching/Racket/character-matching.rkt b/Task/String-matching/Racket/string-matching.rkt similarity index 100% rename from Task/Character-matching/Racket/character-matching.rkt rename to Task/String-matching/Racket/string-matching.rkt diff --git a/Task/Character-matching/Retro/character-matching.retro b/Task/String-matching/Retro/string-matching.retro similarity index 100% rename from Task/Character-matching/Retro/character-matching.retro rename to Task/String-matching/Retro/string-matching.retro diff --git a/Task/Character-matching/Ruby/character-matching.rb b/Task/String-matching/Ruby/string-matching.rb similarity index 100% rename from Task/Character-matching/Ruby/character-matching.rb rename to Task/String-matching/Ruby/string-matching.rb diff --git a/Task/Character-matching/Run-BASIC/character-matching.run b/Task/String-matching/Run-BASIC/string-matching.run similarity index 100% rename from Task/Character-matching/Run-BASIC/character-matching.run rename to Task/String-matching/Run-BASIC/string-matching.run diff --git a/Task/Character-matching/Scala/character-matching.scala b/Task/String-matching/Scala/string-matching.scala similarity index 100% rename from Task/Character-matching/Scala/character-matching.scala rename to Task/String-matching/Scala/string-matching.scala diff --git a/Task/Character-matching/Seed7/character-matching.seed7 b/Task/String-matching/Seed7/string-matching.seed7 similarity index 100% rename from Task/Character-matching/Seed7/character-matching.seed7 rename to Task/String-matching/Seed7/string-matching.seed7 diff --git a/Task/Character-matching/Smalltalk/character-matching.st b/Task/String-matching/Smalltalk/string-matching.st similarity index 100% rename from Task/Character-matching/Smalltalk/character-matching.st rename to Task/String-matching/Smalltalk/string-matching.st diff --git a/Task/Character-matching/Standard-ML/character-matching.ml b/Task/String-matching/Standard-ML/string-matching.ml similarity index 100% rename from Task/Character-matching/Standard-ML/character-matching.ml rename to Task/String-matching/Standard-ML/string-matching.ml diff --git a/Task/Character-matching/TUSCRIPT/character-matching.tu b/Task/String-matching/TUSCRIPT/string-matching.tu similarity index 100% rename from Task/Character-matching/TUSCRIPT/character-matching.tu rename to Task/String-matching/TUSCRIPT/string-matching.tu diff --git a/Task/String-matching/TXR/string-matching-1.txr b/Task/String-matching/TXR/string-matching-1.txr new file mode 100644 index 0000000000..14770bd036 --- /dev/null +++ b/Task/String-matching/TXR/string-matching-1.txr @@ -0,0 +1,18 @@ +@(do + (tree-case *args* + ((big small) + (cond + ((< (length big) (length small)) + (put-line `@big is shorter than @small`)) + ((str= big small) + (put-line `@big and @small are equal`)) + ((match-str big small) + (put-line `@small is a prefix of @big`)) + ((match-str big small -1) + (put-line `@small is a suffix of @big`)) + (t (let ((pos (search-str big small))) + (if pos + (put-line `@small occurs in @big at position @pos`) + (put-line `@small does not occur in @big`)))))) + (otherwise + (put-line `usage: @(ldiff *full-args* *args*) `)))) diff --git a/Task/Character-matching/TXR/character-matching.txr b/Task/String-matching/TXR/string-matching-2.txr similarity index 100% rename from Task/Character-matching/TXR/character-matching.txr rename to Task/String-matching/TXR/string-matching-2.txr diff --git a/Task/Character-matching/Tcl/character-matching-1.tcl b/Task/String-matching/Tcl/string-matching-1.tcl similarity index 100% rename from Task/Character-matching/Tcl/character-matching-1.tcl rename to Task/String-matching/Tcl/string-matching-1.tcl diff --git a/Task/Character-matching/Tcl/character-matching-2.tcl b/Task/String-matching/Tcl/string-matching-2.tcl similarity index 100% rename from Task/Character-matching/Tcl/character-matching-2.tcl rename to Task/String-matching/Tcl/string-matching-2.tcl diff --git a/Task/Character-matching/Tcl/character-matching-3.tcl b/Task/String-matching/Tcl/string-matching-3.tcl similarity index 100% rename from Task/Character-matching/Tcl/character-matching-3.tcl rename to Task/String-matching/Tcl/string-matching-3.tcl diff --git a/Task/Character-matching/Tcl/character-matching-4.tcl b/Task/String-matching/Tcl/string-matching-4.tcl similarity index 100% rename from Task/Character-matching/Tcl/character-matching-4.tcl rename to Task/String-matching/Tcl/string-matching-4.tcl diff --git a/Task/Character-matching/XPL0/character-matching.xpl0 b/Task/String-matching/XPL0/string-matching.xpl0 similarity index 100% rename from Task/Character-matching/XPL0/character-matching.xpl0 rename to Task/String-matching/XPL0/string-matching.xpl0 diff --git a/Task/String-prepend/00DESCRIPTION b/Task/String-prepend/00DESCRIPTION new file mode 100644 index 0000000000..6046bfb11e --- /dev/null +++ b/Task/String-prepend/00DESCRIPTION @@ -0,0 +1,9 @@ + {{basic data operation}} +[[Category:String manipulation]] [[Category: String manipulation]] [[Category:Simple]] +{{omit from|bc|No string operations in bc}} +{{omit from|dc|No string operations in dc}} +Create a string variable equal to any text value. +Prepend the string variable with another string literal. +If your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions. + +To illustrate the operation, show the content of the variable. diff --git a/Task/String-prepend/00META.yaml b/Task/String-prepend/00META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/String-prepend/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/String-prepend/ALGOL-68/string-prepend.alg b/Task/String-prepend/ALGOL-68/string-prepend.alg new file mode 100644 index 0000000000..a3c626f6eb --- /dev/null +++ b/Task/String-prepend/ALGOL-68/string-prepend.alg @@ -0,0 +1,6 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +STRING str := "12345678"; +"0" +=: str; +print(str) diff --git a/Task/String-prepend/AWK/string-prepend.awk b/Task/String-prepend/AWK/string-prepend.awk new file mode 100644 index 0000000000..e106ee7a1f --- /dev/null +++ b/Task/String-prepend/AWK/string-prepend.awk @@ -0,0 +1,7 @@ +# syntax: GAWK -f STRING_PREPEND.AWK +BEGIN { + s = "bar" + s = "foo" s + print(s) + exit(0) +} diff --git a/Task/String-prepend/AutoHotkey/string-prepend.ahk b/Task/String-prepend/AutoHotkey/string-prepend.ahk new file mode 100644 index 0000000000..3404c90d3c --- /dev/null +++ b/Task/String-prepend/AutoHotkey/string-prepend.ahk @@ -0,0 +1,3 @@ +s := "foo" +s := s "bar" +Msgbox % s diff --git a/Task/String-prepend/BASIC/string-prepend.basic b/Task/String-prepend/BASIC/string-prepend.basic new file mode 100644 index 0000000000..2aa10ff4ab --- /dev/null +++ b/Task/String-prepend/BASIC/string-prepend.basic @@ -0,0 +1,3 @@ +S$ = " World!" +S$ = "Hello" + S$ +PRINT S$ diff --git a/Task/String-prepend/Bracmat/string-prepend.bracmat b/Task/String-prepend/Bracmat/string-prepend.bracmat new file mode 100644 index 0000000000..5eda6d9156 --- /dev/null +++ b/Task/String-prepend/Bracmat/string-prepend.bracmat @@ -0,0 +1,3 @@ + World!:?string +& str$("Hello " !string):?string +& out$!string diff --git a/Task/String-prepend/C++/string-prepend.cpp b/Task/String-prepend/C++/string-prepend.cpp new file mode 100644 index 0000000000..5158fc5d6c --- /dev/null +++ b/Task/String-prepend/C++/string-prepend.cpp @@ -0,0 +1,13 @@ +include +#include +#include +#include + +int main( ) { + std::vector myStrings { "prepended to" , "my string" } ; + std::string prepended = std::accumulate( myStrings.begin( ) , + myStrings.end( ) , std::string( "" ) , []( std::string a , + std::string b ) { return a + b ; } ) ; + std::cout << prepended << std::endl ; + return 0 ; +} diff --git a/Task/String-prepend/C-sharp/string-prepend.cs b/Task/String-prepend/C-sharp/string-prepend.cs new file mode 100644 index 0000000000..8880dbd7f4 --- /dev/null +++ b/Task/String-prepend/C-sharp/string-prepend.cs @@ -0,0 +1,15 @@ +using System; + +namespace PrependString +{ + class Program + { + static void Main(string[] args) + { + string str = "World"; + str = "Hello " + str; + Console.WriteLine(str); + Console.ReadKey(); + } + } +} diff --git a/Task/String-prepend/C/string-prepend.c b/Task/String-prepend/C/string-prepend.c new file mode 100644 index 0000000000..24fbf27e41 --- /dev/null +++ b/Task/String-prepend/C/string-prepend.c @@ -0,0 +1,14 @@ +#include +#include +#include + +int main() +{ + char str[100]="my String"; + char *cstr="Changed "; + char *dup; + sprintf(str,"%s%s",cstr,(dup=strdup(str))); + free(dup); + printf("%s\n",str); + return 0; +} diff --git a/Task/String-prepend/COBOL/string-prepend.cobol b/Task/String-prepend/COBOL/string-prepend.cobol new file mode 100644 index 0000000000..36409a5ec4 --- /dev/null +++ b/Task/String-prepend/COBOL/string-prepend.cobol @@ -0,0 +1,12 @@ + >>SOURCE FREE +PROGRAM-ID. prepend. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 str PIC X(30) VALUE "world!". + +PROCEDURE DIVISION. + MOVE FUNCTION CONCATENATE("Hello, ", str) TO str + DISPLAY str + . +END PROGRAM prepend. diff --git a/Task/String-prepend/Clojure/string-prepend.clj b/Task/String-prepend/Clojure/string-prepend.clj new file mode 100644 index 0000000000..8258bd7657 --- /dev/null +++ b/Task/String-prepend/Clojure/string-prepend.clj @@ -0,0 +1,5 @@ +(def s (ref "World")) +(dosync (alter s #(str "Hello " %))) + +user=> @s +"Hello World" diff --git a/Task/String-prepend/Common-Lisp/string-prepend.lisp b/Task/String-prepend/Common-Lisp/string-prepend.lisp new file mode 100644 index 0000000000..5efc4ce469 --- /dev/null +++ b/Task/String-prepend/Common-Lisp/string-prepend.lisp @@ -0,0 +1,7 @@ +(defmacro prependf (s &rest strs) + "Prepend the given string variable with additional strings. The string variable is modified in-place." + `(setf ,s (concatenate 'string ,@strs ,s))) + +(defvar *str* "foo") +(prependf *str* "bar") +(format T "~a~%" *str*) diff --git a/Task/String-prepend/D/string-prepend.d b/Task/String-prepend/D/string-prepend.d new file mode 100644 index 0000000000..508c706ac4 --- /dev/null +++ b/Task/String-prepend/D/string-prepend.d @@ -0,0 +1,7 @@ +import std.stdio; + +void main() { + string s = "world!"; + s = "Hello " ~ s; + writeln(s); +} diff --git a/Task/String-prepend/Deja-Vu/string-prepend.djv b/Task/String-prepend/Deja-Vu/string-prepend.djv new file mode 100644 index 0000000000..c6ddd6aa1c --- /dev/null +++ b/Task/String-prepend/Deja-Vu/string-prepend.djv @@ -0,0 +1,3 @@ +local :s "world!" +set :s concat( "Hello " s) +!print s diff --git a/Task/String-prepend/Factor/string-prepend.factor b/Task/String-prepend/Factor/string-prepend.factor new file mode 100644 index 0000000000..6899e6190f --- /dev/null +++ b/Task/String-prepend/Factor/string-prepend.factor @@ -0,0 +1,2 @@ +"world" +"Hello " prepend diff --git a/Task/String-prepend/Go/string-prepend.go b/Task/String-prepend/Go/string-prepend.go new file mode 100644 index 0000000000..48354680e9 --- /dev/null +++ b/Task/String-prepend/Go/string-prepend.go @@ -0,0 +1,2 @@ +s := "world!" +s = "Hello, " + s diff --git a/Task/String-prepend/Haskell/string-prepend.hs b/Task/String-prepend/Haskell/string-prepend.hs new file mode 100644 index 0000000000..95a6d9c2cd --- /dev/null +++ b/Task/String-prepend/Haskell/string-prepend.hs @@ -0,0 +1,2 @@ +Prelude> let f = (++" World!") +Prelude> f "Hello" diff --git a/Task/String-prepend/Icon/string-prepend.icon b/Task/String-prepend/Icon/string-prepend.icon new file mode 100644 index 0000000000..97f14baa50 --- /dev/null +++ b/Task/String-prepend/Icon/string-prepend.icon @@ -0,0 +1,2 @@ +s := "world!" +s := "Hello, " || s diff --git a/Task/String-prepend/J/string-prepend.j b/Task/String-prepend/J/string-prepend.j new file mode 100644 index 0000000000..853c109d55 --- /dev/null +++ b/Task/String-prepend/J/string-prepend.j @@ -0,0 +1,6 @@ + s=: 'value' + s +value + s=: 'new ',s + s +new value diff --git a/Task/String-prepend/Java/string-prepend.java b/Task/String-prepend/Java/string-prepend.java new file mode 100644 index 0000000000..23680e1c3f --- /dev/null +++ b/Task/String-prepend/Java/string-prepend.java @@ -0,0 +1,7 @@ +public class Prepend { + + public static void main(String[] args) { + String s = "world!"; + System.out.println("Hello " + s); + } +} diff --git a/Task/String-prepend/Julia/string-prepend.julia b/Task/String-prepend/Julia/string-prepend.julia new file mode 100644 index 0000000000..d8f7a8d430 --- /dev/null +++ b/Task/String-prepend/Julia/string-prepend.julia @@ -0,0 +1,2 @@ +s = "world!" +s = "Hello " * s diff --git a/Task/String-prepend/Lua/string-prepend-1.lua b/Task/String-prepend/Lua/string-prepend-1.lua new file mode 100644 index 0000000000..34b61c684f --- /dev/null +++ b/Task/String-prepend/Lua/string-prepend-1.lua @@ -0,0 +1,3 @@ +s = "12345678" +s = "0" .. s +print(s) diff --git a/Task/String-prepend/Lua/string-prepend-2.lua b/Task/String-prepend/Lua/string-prepend-2.lua new file mode 100644 index 0000000000..b2f2fa91ac --- /dev/null +++ b/Task/String-prepend/Lua/string-prepend-2.lua @@ -0,0 +1,3 @@ +s = "12345678" +s = string.format("%s%s", "0", s) +print(s) diff --git a/Task/String-prepend/Lua/string-prepend-3.lua b/Task/String-prepend/Lua/string-prepend-3.lua new file mode 100644 index 0000000000..131bdf8cc4 --- /dev/null +++ b/Task/String-prepend/Lua/string-prepend-3.lua @@ -0,0 +1,3 @@ +s = "12345678" +s = table.concat({"0", s}) +print(s) diff --git a/Task/String-prepend/Mathematica/string-prepend.math b/Task/String-prepend/Mathematica/string-prepend.math new file mode 100644 index 0000000000..cd3135d802 --- /dev/null +++ b/Task/String-prepend/Mathematica/string-prepend.math @@ -0,0 +1,2 @@ +a = "any text value"; +a = "another string literal" <> a (* using concatenation (no built-in prepend) *) diff --git a/Task/String-prepend/Mercury/string-prepend.mercury b/Task/String-prepend/Mercury/string-prepend.mercury new file mode 100644 index 0000000000..6353e81651 --- /dev/null +++ b/Task/String-prepend/Mercury/string-prepend.mercury @@ -0,0 +1,9 @@ +:- module string_prepend. +:- interface. +:- import_module io. +:- pred main(io::di, io::uo) is det. +:- implementation. +:- import_module string. +main(!IO) :- + S = "World!\n", + io.write_string("Hello " ++ S, !IO). diff --git a/Task/String-prepend/NetRexx/string-prepend.netrexx b/Task/String-prepend/NetRexx/string-prepend.netrexx new file mode 100644 index 0000000000..222f1596c2 --- /dev/null +++ b/Task/String-prepend/NetRexx/string-prepend.netrexx @@ -0,0 +1,3 @@ +s_ = 'world!' +s_ = 'Hello, 's_ +say s_ diff --git a/Task/String-prepend/NewLISP/string-prepend.newlisp b/Task/String-prepend/NewLISP/string-prepend.newlisp new file mode 100644 index 0000000000..f554a030a6 --- /dev/null +++ b/Task/String-prepend/NewLISP/string-prepend.newlisp @@ -0,0 +1,3 @@ +(setq str "bar") +(push "foo" str) +(println str) diff --git a/Task/String-prepend/PARI-GP/string-prepend.pari b/Task/String-prepend/PARI-GP/string-prepend.pari new file mode 100644 index 0000000000..4cd6b8832c --- /dev/null +++ b/Task/String-prepend/PARI-GP/string-prepend.pari @@ -0,0 +1,2 @@ +s = "world!"; +s = Str("Hello, ", s) diff --git a/Task/String-prepend/PL-I/string-prepend.pli b/Task/String-prepend/PL-I/string-prepend.pli new file mode 100644 index 0000000000..6af716808f --- /dev/null +++ b/Task/String-prepend/PL-I/string-prepend.pli @@ -0,0 +1,6 @@ +Pre_Cat: procedure options (main); /* 2 November 2013 */ + declare s character (100) varying; + s = ' bowl'; + s = 'dust' || s; + put (s); +end Pre_Cat; diff --git a/Task/String-prepend/Pascal/string-prepend.pascal b/Task/String-prepend/Pascal/string-prepend.pascal new file mode 100644 index 0000000000..024729abee --- /dev/null +++ b/Task/String-prepend/Pascal/string-prepend.pascal @@ -0,0 +1,17 @@ +program StringPrepend; +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + Classes + { you can add units after this }; + +var + s: String = ' World !'; +begin + s := 'Hello' + s; + WriteLn(S); + ReadLn; +end. diff --git a/Task/String-prepend/Perl-6/string-prepend.pl6 b/Task/String-prepend/Perl-6/string-prepend.pl6 new file mode 100644 index 0000000000..7d9827b6f0 --- /dev/null +++ b/Task/String-prepend/Perl-6/string-prepend.pl6 @@ -0,0 +1,24 @@ +# explicit concatentation +$_ = 'byte'; +$_ = 'kilo' ~ $_; +.say; + +# interpolation as concatenation +$_ = 'buck'; +$_ = "mega$_"; +.say; + +# lvalue substr +$_ = 'bit'; +substr-rw($_,0,0) = 'nano'; +.say; + +# regex substitution +$_ = 'fortnight'; +s[^] = 'micro'; +.say; + +# reversed append assignment +$_ = 'cooper'; +$_ [R~]= 'mini'; +.say; diff --git a/Task/String-prepend/Perl/string-prepend.pl b/Task/String-prepend/Perl/string-prepend.pl new file mode 100644 index 0000000000..6f9d50f5d2 --- /dev/null +++ b/Task/String-prepend/Perl/string-prepend.pl @@ -0,0 +1,3 @@ +my $str = 'bar'; +substr $str, 0, 0, 'Foo'; +print $str; diff --git a/Task/String-prepend/PicoLisp/string-prepend.l b/Task/String-prepend/PicoLisp/string-prepend.l new file mode 100644 index 0000000000..cd1d5a7027 --- /dev/null +++ b/Task/String-prepend/PicoLisp/string-prepend.l @@ -0,0 +1,3 @@ +(setq Str1 "12345678!") +(setq Str1 (pack "0" Str1)) +(println Str1) diff --git a/Task/String-prepend/Prolog/string-prepend-1.pro b/Task/String-prepend/Prolog/string-prepend-1.pro new file mode 100644 index 0000000000..e5905c17a4 --- /dev/null +++ b/Task/String-prepend/Prolog/string-prepend-1.pro @@ -0,0 +1,12 @@ +:- op(200, xfx, user:(=+)). + +%% +Prepend =+ +Chars +% +% Will destructively update Chars +% So that Chars = Prepend prefixed to Chars. +% eazar001 in ##prolog helped refine this approach. + +[X|Xs] =+ Chars :- + append(Xs, Chars, Rest), + nb_setarg(2, Chars, Rest), + nb_setarg(1, Chars, X). diff --git a/Task/String-prepend/Prolog/string-prepend-2.pro b/Task/String-prepend/Prolog/string-prepend-2.pro new file mode 100644 index 0000000000..169c27295c --- /dev/null +++ b/Task/String-prepend/Prolog/string-prepend-2.pro @@ -0,0 +1,2 @@ +?- Str = `World!`, `Hello, ` =+ Str. +Str = "Hello, World!". diff --git a/Task/String-prepend/PureBasic/string-prepend.purebasic b/Task/String-prepend/PureBasic/string-prepend.purebasic new file mode 100644 index 0000000000..86e5116ba8 --- /dev/null +++ b/Task/String-prepend/PureBasic/string-prepend.purebasic @@ -0,0 +1,8 @@ +S$ = " World!" +S$ = "Hello" + S$ +If OpenConsole() + PrintN(S$) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/String-prepend/Python/string-prepend.py b/Task/String-prepend/Python/string-prepend.py new file mode 100644 index 0000000000..b81e0ee058 --- /dev/null +++ b/Task/String-prepend/Python/string-prepend.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +s = "12345678" +s = "0" + s # by concatenation +print(s) diff --git a/Task/String-prepend/README b/Task/String-prepend/README new file mode 100644 index 0000000000..52f4100c80 --- /dev/null +++ b/Task/String-prepend/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/String_prepend diff --git a/Task/String-prepend/REXX/string-prepend.rexx b/Task/String-prepend/REXX/string-prepend.rexx new file mode 100644 index 0000000000..37f7389f81 --- /dev/null +++ b/Task/String-prepend/REXX/string-prepend.rexx @@ -0,0 +1,17 @@ + /*──────────────── using literal abuttal. */ + /*──────────────── this won't work as the first */ + /*──────────────── variable name is X or B */ +zz='llo world!' +zz='he'zz +say zz + + /*──────────────── using literal concatenation. */ +gg = "llo world!" +gg = 'he' || gg +say gg + + /*──────────────── using variable concatenation.*/ +aString = 'llo world!' +bString = "he" +aString = bString || aString +say aString diff --git a/Task/String-prepend/Racket/string-prepend.rkt b/Task/String-prepend/Racket/string-prepend.rkt new file mode 100644 index 0000000000..6994e56d94 --- /dev/null +++ b/Task/String-prepend/Racket/string-prepend.rkt @@ -0,0 +1,12 @@ +;there is no built-in way to set! prepend in racket +(define str "foo") +(set! str (string-append "bar " str)) +(displayln str) + +;but you can create a quick macro to solve that problem +(define-syntax-rule (set-prepend! str value) + (set! str (string-append value str))) + +(define macrostr " bar") +(set-prepend! macrostr "foo") +(displayln macrostr) diff --git a/Task/String-prepend/Ruby/string-prepend.rb b/Task/String-prepend/Ruby/string-prepend.rb new file mode 100644 index 0000000000..c08e240229 --- /dev/null +++ b/Task/String-prepend/Ruby/string-prepend.rb @@ -0,0 +1,3 @@ +str = "llo world" +str.prepend("He") +p str #=> "Hello world" diff --git a/Task/String-prepend/Scala/string-prepend.scala b/Task/String-prepend/Scala/string-prepend.scala new file mode 100644 index 0000000000..bd28c693be --- /dev/null +++ b/Task/String-prepend/Scala/string-prepend.scala @@ -0,0 +1,5 @@ + val s = "World" // Immutables are recommended //> s : String = World + val f2 = () => ", " //Function assigned to variable + //> f2 : () => String = + val s1 = "Hello" + f2() + s //> s1 : String = Hello, World + println(s1); //> Hello, World diff --git a/Task/String-prepend/Seed7/string-prepend.seed7 b/Task/String-prepend/Seed7/string-prepend.seed7 new file mode 100644 index 0000000000..482af73062 --- /dev/null +++ b/Task/String-prepend/Seed7/string-prepend.seed7 @@ -0,0 +1,9 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: s is "world!"; + begin + s := "Hello " & s; + writeln(s); + end func; diff --git a/Task/String-prepend/Tcl/string-prepend.tcl b/Task/String-prepend/Tcl/string-prepend.tcl new file mode 100644 index 0000000000..1b918ea81e --- /dev/null +++ b/Task/String-prepend/Tcl/string-prepend.tcl @@ -0,0 +1,3 @@ +set s "llo world" +set s "he$s" +puts $s diff --git a/Task/String-prepend/VBA/string-prepend.vba b/Task/String-prepend/VBA/string-prepend.vba new file mode 100644 index 0000000000..49da93544e --- /dev/null +++ b/Task/String-prepend/VBA/string-prepend.vba @@ -0,0 +1,6 @@ +Function StringPrepend() +Dim s As String +s = "bar" +s = "foo" & s +Debug.Print s +End Function diff --git a/Task/Sum-multiples-of-3-and-5/00DESCRIPTION b/Task/Sum-multiples-of-3-and-5/00DESCRIPTION new file mode 100644 index 0000000000..12e6194065 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/00DESCRIPTION @@ -0,0 +1,9 @@ +The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. Show output for ''n'' = 1000. + +'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher. + +== {{header|APL}} == +⎕IO←0 +{+/((0=3|a)∨0=5|a)/a←⍳⍵} 1000[http://ngn.github.io/apl/web/index.html#code=%7B+/%28%280%3D3%7Ca%29%u22280%3D5%7Ca%29/a%u2190%u2373%u2375%7D%201000,run=1 run] +{{out}} +
233168
diff --git a/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-1.awk b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-1.awk new file mode 100644 index 0000000000..75cdcbacad --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-1.awk @@ -0,0 +1,9 @@ +#!/usr/bin/awk -f +{ + n = $1-1; + print sum(n,3)+sum(n,5)-sum(n,15); +} +function sum(n,d) { + m = int(n/d); + return (d*m*(m+1)/2); +} diff --git a/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-2.awk b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-2.awk new file mode 100644 index 0000000000..38da00452d --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-2.awk @@ -0,0 +1,13 @@ +Declare function mulsum35(n as integer) as integer +Function mulsum35(n as integer) as integer + Dim s as integer + For i as integer = 1 to n - 1 + If (i mod 3 = 0) or (i mod 5 = 0) then + s += i + End if + Next i + Return s +End Function +Print mulsum35(1000) +Sleep +End diff --git a/Task/Sum-multiples-of-3-and-5/AutoHotkey/sum-multiples-of-3-and-5.ahk b/Task/Sum-multiples-of-3-and-5/AutoHotkey/sum-multiples-of-3-and-5.ahk new file mode 100644 index 0000000000..5151878666 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/AutoHotkey/sum-multiples-of-3-and-5.ahk @@ -0,0 +1,35 @@ +n := 1000 + +msgbox % "Sum is " . Sum3_5(n) . " for n = " . n +msgbox % "Sum is " . Sum3_5_b(n) . " for n = " . n + +;Standard simple Implementation. +Sum3_5(n) { + sum := 0 + loop % n-1 { + if (!Mod(a_index,3) || !Mod(a_index,5)) + sum:=sum+A_index + } + return sum +} + +;Translated from the C++ version. +Sum3_5_b( i ) { + sum := 0, a := 0 + while (a < 28) + { + if (!Mod(a,3) || !Mod(a,5)) + { + sum += a + s := 30 + while (s < i) + { + if (a+s < i) + sum += (a+s) + s+=30 + } + } + a+=1 + } + return sum +} diff --git a/Task/Sum-multiples-of-3-and-5/C++/sum-multiples-of-3-and-5.cpp b/Task/Sum-multiples-of-3-and-5/C++/sum-multiples-of-3-and-5.cpp new file mode 100644 index 0000000000..2dd23c9d79 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/C++/sum-multiples-of-3-and-5.cpp @@ -0,0 +1,42 @@ +#include + +//-------------------------------------------------------------------------------------------------- +typedef unsigned long long bigInt; + +using namespace std; +//-------------------------------------------------------------------------------------------------- +class m35 +{ +public: + void doIt( bigInt i ) + { + bigInt sum = 0; + for( bigInt a = 1; a < i; a++ ) + if( !( a % 3 ) || !( a % 5 ) ) sum += a; + + cout << "Sum is " << sum << " for n = " << i << endl << endl; + } + + // this method uses less than half iterations than the first one + void doIt_b( bigInt i ) + { + bigInt sum = 0; + for( bigInt a = 0; a < 28; a++ ) + { + if( !( a % 3 ) || !( a % 5 ) ) + { + sum += a; + for( bigInt s = 30; s < i; s += 30 ) + if( a + s < i ) sum += ( a + s ); + + } + } + cout << "Sum is " << sum << " for n = " << i << endl << endl; + } +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + m35 m; m.doIt( 1000 ); + return system( "pause" ); +} diff --git a/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-1.c b/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-1.c new file mode 100644 index 0000000000..b90bb13693 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-1.c @@ -0,0 +1,24 @@ +#include +#include + +unsigned long long sum35(unsigned long long limit) +{ + unsigned long long sum = 0; + for (unsigned long long i = 0; i < limit; i++) + if (!(i % 3) || !(i % 5)) + sum += i; + return sum; +} + +int main(int argc, char **argv) +{ + unsigned long long limit; + + if (argc == 2) + limit = strtoull(argv[1], NULL, 10); + else + limit = 1000; + + printf("%lld\n", sum35(limit)); + return 0; +} diff --git a/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-2.c b/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-2.c new file mode 100644 index 0000000000..e2c364204d --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/C/sum-multiples-of-3-and-5-2.c @@ -0,0 +1,53 @@ +#include +#include + +void sum_multiples(mpz_t result, const mpz_t limit, const unsigned f) +{ + mpz_t m; + mpz_init(m); + mpz_sub_ui(m, limit, 1); + mpz_fdiv_q_ui(m, m, f); + + mpz_init_set(result, m); + mpz_add_ui(result, result, 1); + mpz_mul(result, result, m); + mpz_mul_ui(result, result, f); + mpz_fdiv_q_2exp(result, result, 1); + + mpz_clear(m); +} + +int main(int argc, char **argv) +{ + mpf_t temp; + mpz_t limit; + + if (argc == 2) + { + mpf_init_set_str(temp, argv[1], 10); + mpz_init(limit); + mpz_set_f(limit, temp); + mpf_clear(temp); + } + else + mpz_init_set_str(limit, "1000000000000000000000", 10); + + mpz_t temp_sum; + mpz_t sum35; + + mpz_init(temp_sum); + sum_multiples(temp_sum, limit, 3); + mpz_init_set(sum35, temp_sum); + sum_multiples(temp_sum, limit, 5); + mpz_add(sum35, sum35, temp_sum); + sum_multiples(temp_sum, limit, 15); + mpz_sub(sum35, sum35, temp_sum); + + mpz_out_str(stdout, 10, sum35); + puts(""); + + mpz_clear(temp_sum); + mpz_clear(sum35); + mpz_clear(limit); + return 0; +} diff --git a/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-1.cobol b/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-1.cobol new file mode 100644 index 0000000000..a6b71775e3 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-1.cobol @@ -0,0 +1,23 @@ +Identification division. +Program-id. three-five-sum. + +Data division. +Working-storage section. +01 ws-the-limit pic 9(18) value 1000. +01 ws-the-number pic 9(18). +01 ws-the-sum pic 9(18). +01 ws-sum-out pic z(18). + +Procedure division. +Main-program. + Perform Do-sum + varying ws-the-number from 1 by 1 + until ws-the-number = ws-the-limit. + Move ws-the-sum to ws-sum-out. + Display "Sum = " ws-sum-out. + End-run. + +Do-sum. + If function mod(ws-the-number, 3) = zero + or function mod(ws-the-number, 5) = zero + then add ws-the-number to ws-the-sum. diff --git a/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-2.cobol b/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-2.cobol new file mode 100644 index 0000000000..d6517b7eb4 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-2.cobol @@ -0,0 +1,47 @@ +Identification division. +Program-id. three-five-sum-fast. + +Data division. +Working-storage section. +01 ws-num pic 9(18) value 1000000000. +01 ws-n5 pic 9(18). +01 ws-n3 pic 9(18). +01 ws-n15 pic 9(18). +01 ws-sum pic 9(18). +01 ws-out. + 02 ws-out-num pic z(18). + 02 filler pic x(3) value " = ". + 02 ws-out-sum pic z(18). + +Procedure division. +Main-program. + Perform + call "tri-sum" using ws-num 3 by reference ws-n3 + call "tri-sum" using ws-num 5 by reference ws-n5 + call "tri-sum" using ws-num 15 by reference ws-n15 + end-perform. + Compute ws-sum = ws-n3 + ws-n5 - ws-n15. + Move ws-sum to ws-out-sum. + Move ws-num to ws-out-num. + Display ws-out. + + + +Identification division. +Program-id. tri-sum. + +Data division. +Working-storage section. +01 ws-n1 pic 9(18). +01 ws-n2 pic 9(18). + +Linkage section. +77 ls-num pic 9(18). +77 ls-fac pic 9(18). +77 ls-ret pic 9(18). + +Procedure division using ls-num, ls-fac, ls-ret. + Compute ws-n1 = (ls-num - 1) / ls-fac. + Compute ws-n2 = ws-n1 + 1. + Compute ls-ret = ls-fac * ws-n1 * ws-n2 / 2. + goback. diff --git a/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-1.clj b/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-1.clj new file mode 100644 index 0000000000..fa1cb31f07 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-1.clj @@ -0,0 +1,6 @@ +(defn sum-mults [n & mults] + (let [pred (apply some-fn + (map #(fn [x] (zero? (mod x %))) mults))] + (->> (range n) (filter pred) (reduce +)))) + +(println (sum-mults 1000 3 5)) diff --git a/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-2.clj b/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-2.clj new file mode 100644 index 0000000000..e1298bb707 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Clojure/sum-multiples-of-3-and-5-2.clj @@ -0,0 +1,6 @@ +(defn sum-mul [n f] + (let [n1 (/' (inc' n) f)] + (*' f n1 (inc' n1) 1/2) + +(def sum-35 #(-> % (sum-mul 3) (+ (sum-mul % 5)) (- (sum-mul % 15)))) +(println (sum-35 1000000000)) diff --git a/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-1.lisp b/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-1.lisp new file mode 100644 index 0000000000..0c04b89820 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-1.lisp @@ -0,0 +1,4 @@ +(defun sum-3-5-slow (limit) + (loop for x below limit + when (or (zerop (rem x 3)) (zerop (rem x 5))) + sum x)) diff --git a/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-2.lisp b/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-2.lisp new file mode 100644 index 0000000000..be894d09e1 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Common-Lisp/sum-multiples-of-3-and-5-2.lisp @@ -0,0 +1,6 @@ +(defun sum-3-5-fast (limit) + (flet ((triangular (n) (truncate (* n (1+ n)) 2))) + (let ((n (1- limit))) ; Sum multiples *below* the limit + (- (+ (* 3 (triangular (truncate n 3))) + (* 5 (triangular (truncate n 5)))) + (* 15 (triangular (truncate n 15))))))) diff --git a/Task/Sum-multiples-of-3-and-5/Component-Pascal/sum-multiples-of-3-and-5.component b/Task/Sum-multiples-of-3-and-5/Component-Pascal/sum-multiples-of-3-and-5.component new file mode 100644 index 0000000000..cb328c9bde --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Component-Pascal/sum-multiples-of-3-and-5.component @@ -0,0 +1,26 @@ +MODULE Sum3_5; +IMPORT StdLog, Strings, Args; + +PROCEDURE DoSum(n: INTEGER):INTEGER; +VAR + i,sum: INTEGER; +BEGIN + sum := 0;i := 0; + WHILE (i < n) DO + IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN INC(sum,i) END; + INC(i) + END; + RETURN sum +END DoSum; + +PROCEDURE Compute*; +VAR + params: Args.Params; + i,n,res: INTEGER; +BEGIN + Args.Get(params); + Strings.StringToInt(params.args[0],n,res); + StdLog.String("Sum: ");StdLog.Int(DoSum(n)); StdLog.Ln +END Compute; + +END Sum3_5. diff --git a/Task/Sum-multiples-of-3-and-5/D/sum-multiples-of-3-and-5.d b/Task/Sum-multiples-of-3-and-5/D/sum-multiples-of-3-and-5.d new file mode 100644 index 0000000000..1f048cb9b9 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/D/sum-multiples-of-3-and-5.d @@ -0,0 +1,15 @@ +import std.stdio, std.bigint; + +BigInt sum35(in BigInt n) pure nothrow { + static BigInt sumMul(in BigInt n, in int f) pure nothrow { + immutable n1 = (n - 1) / f; + return f * n1 * (n1 + 1) / 2; + } + + return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15); +} + +void main() { + 1000.BigInt.sum35.writeln; + (10.BigInt ^^ 20).sum35.writeln; +} diff --git a/Task/Sum-multiples-of-3-and-5/Deja-Vu/sum-multiples-of-3-and-5.djv b/Task/Sum-multiples-of-3-and-5/Deja-Vu/sum-multiples-of-3-and-5.djv new file mode 100644 index 0000000000..6a03528a55 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Deja-Vu/sum-multiples-of-3-and-5.djv @@ -0,0 +1,7 @@ +sum-divisible n: + 0 + for i range 1 -- n: + if or = 0 % i 3 = 0 % i 5: + + i + +!. sum-divisible 1000 diff --git a/Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi b/Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi new file mode 100644 index 0000000000..59f7ddc419 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi @@ -0,0 +1,22 @@ +program sum35; + +{$APPTYPE CONSOLE} + +var + sum: integer; + i: integer; + +function isMultipleOf(aNumber, aDivisor: integer): boolean; +begin + result := aNumber mod aDivisor = 0 +end; + +begin + sum := 0; + for i := 3 to 999 do + begin + if isMultipleOf(i, 3) or isMultipleOf(i, 5) then + sum := sum + i; + end; + writeln(sum); +end. diff --git a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e new file mode 100644 index 0000000000..feeaa57930 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e @@ -0,0 +1,27 @@ +class + SUM_MULTIPLES_OF_THREE_AND_FIVE + +feature + is_multiple(x,y: INTEGER):BOOLEAN + local + do + RESULT:= x\\y=0 + end + + sum_multiples(n: INTEGER): INTEGER + local + i,sum: INTEGER + do + from + i:= 1 + until + i=n + loop + if is_multiple(i,3) or is_multiple(i,5) then + sum:= sum+i + end + i:= i+1 + end + Result:= sum + end +end diff --git a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e new file mode 100644 index 0000000000..56db06a880 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e @@ -0,0 +1,15 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + make + local + do + create sum + io.put_integer(sum.sum_multiples (1000)) + end + sum: SUM_MULTIPLES_OF_THREE_AND_FIVE +end diff --git a/Task/Sum-multiples-of-3-and-5/Erlang/sum-multiples-of-3-and-5.erl b/Task/Sum-multiples-of-3-and-5/Erlang/sum-multiples-of-3-and-5.erl new file mode 100644 index 0000000000..07b185a935 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Erlang/sum-multiples-of-3-and-5.erl @@ -0,0 +1,8 @@ +sum_3_5(X) when is_number(X) -> sum_3_5(erlang:round(X)-1, 0). +sum_3_5(X, Total) when X < 3 -> Total; +sum_3_5(X, Total) when X rem 3 =:= 0 orelse X rem 5 =:= 0 -> + sum_3_5(X-1, Total+X); +sum_3_5(X, Total) -> + sum_3_5(X-1, Total). + +io:format("~B~n", [sum_3_5(1000)]). diff --git a/Task/Sum-multiples-of-3-and-5/FBSL/sum-multiples-of-3-and-5.fbsl b/Task/Sum-multiples-of-3-and-5/FBSL/sum-multiples-of-3-and-5.fbsl new file mode 100644 index 0000000000..83de12311c --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/FBSL/sum-multiples-of-3-and-5.fbsl @@ -0,0 +1,14 @@ +#APPTYPE CONSOLE + +FUNCTION sumOfThreeFiveMultiples(n AS INTEGER) + DIM sum AS INTEGER + FOR DIM i = 1 TO n - 1 + IF (NOT (i MOD 3)) OR (NOT (i MOD 5)) THEN + INCR(sum, i) + END IF + NEXT + RETURN sum +END FUNCTION + +PRINT sumOfThreeFiveMultiples(1000) +PAUSE diff --git a/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-1.fth b/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-1.fth new file mode 100644 index 0000000000..22decc5ac2 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-1.fth @@ -0,0 +1,12 @@ +: main ( n -- ) + 0 swap + 3 do + i 3 mod 0= if + i + + else i 5 mod 0= if + i + + then then + loop + . ; + +1000 main \ 233168 ok diff --git a/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-2.fth b/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-2.fth new file mode 100644 index 0000000000..6b4160d722 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Forth/sum-multiples-of-3-and-5-2.fth @@ -0,0 +1,42 @@ +: third 2 pick ; + +: >dtriangular ( n -- d ) + dup 1+ m* d2/ ; + +: sumdiv ( n m -- d ) + dup >r / >dtriangular r> 1 m*/ ; + +: sumdiv_3,5 ( n -- n ) + dup 3 sumdiv third 5 sumdiv d+ rot 15 sumdiv d- ; + +: euler1 ( -- n ) + 999 sumdiv_3,5 drop ; + +: euler1tower ( -- ) + 1 \ power of 10 + 19 0 DO + cr dup 19 .r space dup 1- sumdiv_3,5 d. + 10 * + LOOP drop ; + +euler1 . 233168 ok +euler1tower + 1 0 + 10 23 + 100 2318 + 1000 233168 + 10000 23331668 + 100000 2333316668 + 1000000 233333166668 + 10000000 23333331666668 + 100000000 2333333316666668 + 1000000000 233333333166666668 + 10000000000 23333333331666666668 + 100000000000 2333333333316666666668 + 1000000000000 233333333333166666666668 + 10000000000000 23333333333331666666666668 + 100000000000000 2333333333333316666666666668 + 1000000000000000 233333333333333166666666666668 + 10000000000000000 23333333333333331666666666666668 + 100000000000000000 2333333333333333316666666666666668 +1000000000000000000 233333333333333333166666666666666668 ok diff --git a/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-1.go b/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-1.go new file mode 100644 index 0000000000..9926ac1d87 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-1.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + fmt.Println(s35(1000)) +} + +func s35(i int) int { + i-- + sum2 := func(d int) int { + n := i / d + return d * n * (n + 1) + } + return (sum2(3) + sum2(5) - sum2(15)) / 2 +} diff --git a/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-2.go b/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-2.go new file mode 100644 index 0000000000..2d8944a9e1 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Go/sum-multiples-of-3-and-5-2.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "math/big" +) + +var ( + b1 = big.NewInt(1) + b3 = big.NewInt(3) + b5 = big.NewInt(5) + b10 = big.NewInt(10) + b15 = big.NewInt(15) + b20 = big.NewInt(20) +) + +func main() { + fmt.Println(s35(new(big.Int).Exp(b10, b3, nil))) + fmt.Println(s35(new(big.Int).Exp(b10, b20, nil))) +} + +func s35(i *big.Int) *big.Int { + j := new(big.Int).Sub(i, b1) + sum2 := func(d *big.Int) *big.Int { + n := new(big.Int).Quo(j, d) + p := new(big.Int).Add(n, b1) + return p.Mul(d, p.Mul(p, n)) + } + s := sum2(b3) + return s.Rsh(s.Sub(s.Add(s, sum2(b5)), sum2(b15)), 1) +} diff --git a/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-1.groovy b/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-1.groovy new file mode 100644 index 0000000000..8efd4eeae5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-1.groovy @@ -0,0 +1,2 @@ +def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 } +def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) } diff --git a/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-2.groovy b/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-2.groovy new file mode 100644 index 0000000000..2ac876f3f5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Groovy/sum-multiples-of-3-and-5-2.groovy @@ -0,0 +1,4 @@ +[(1000): 233168, (10e20): 233333333333333333333166666666666666666668].each { arg, value -> + println "Checking $arg == $value" + assert sum35(arg) == value +} diff --git a/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs b/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs new file mode 100644 index 0000000000..30ae9f0f6b --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs @@ -0,0 +1,18 @@ +import Data.List (nub) + +sumMul n f = f * n1 * (n1 + 1) `div` 2 where n1 = (n - 1) `div` f +sum35 n = sumMul n 3 + sumMul n 5 - sumMul n 15 + +-- below are for variable length inputs +pairLCM [] = [] +pairLCM (x:xs) = map (lcm x) xs ++ pairLCM xs + +sumMulS _ [] = 0 +sumMulS n s = sum (map (sumMul n) ss) - sumMulS n (pairLCM ss) + where ss = nub s + +main = do + print $ sum35 1000 + print $ sum35 100000000000000000000000000000000 + print $ sumMulS 1000 [3,5] + print $ sumMulS 10000000 [2,3,5,7,11,13] diff --git a/Task/Sum-multiples-of-3-and-5/Icon/sum-multiples-of-3-and-5.icon b/Task/Sum-multiples-of-3-and-5/Icon/sum-multiples-of-3-and-5.icon new file mode 100644 index 0000000000..c0e92f53df --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Icon/sum-multiples-of-3-and-5.icon @@ -0,0 +1,8 @@ +procedure main(A) + n := (integer(A[1]) | 1000)-1 + write(sum(n,3)+sum(n,5)-sum(n,15)) +end + +procedure sum(n,m) + return m*((n/m)*(n/m+1)/2) +end diff --git a/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-1.j b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-1.j new file mode 100644 index 0000000000..48281a33cb --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-1.j @@ -0,0 +1,3 @@ +mp =: $:~ :(+/ .*) NB. matrix product +f =: (mp 0 = [: */ 3 5 |/ ])@:i. +assert 233168 -: f 1000 NB. ****************** THIS IS THE ANSWER FOR 1000 diff --git a/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-2.j b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-2.j new file mode 100644 index 0000000000..7dceb7e4c5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-2.j @@ -0,0 +1,7 @@ +g =: #~ (0 = [: */ 3 5&(|/)) +assert 0 3 5 6 9 10 12 15 18 20 21 24 25 27 30 33 35 36 39 40 42 45 48 -: g i. 50 +assert 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 -: (+ |.)g i. 50 NB. the pattern + +assert (f -: -:@:(+/)@:(+|.)@:g@:i.) 50 NB. half sum of the pattern. + +NB. continue... diff --git a/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-3.j b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-3.j new file mode 100644 index 0000000000..ddda27cacf --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/J/sum-multiples-of-3-and-5-3.j @@ -0,0 +1,25 @@ + first =: 0&{ + last =: first + skip * <.@:(skip %~ <:@:(1&{) - first) + skip =: 2&{ + terms =: >:@:<.@:(skip %~ last - first) + sum_arithmetic_series =: -:@:(terms * first + last) NB. sum_arithmetic_series FIRST LAST SKIP + NB. interval is [FIRST, LAST) + NB. sum_arithmetic_series is more general than required. + + (0,.10 10000 10000000000000000000x)(,"1 0"1 _)3 5 15x NB. demonstration: form input vectors for 10, ten thousand, and 1*10^(many) +0 10 3 +0 10 5 +0 10 15 + +0 10000 3 +0 10000 5 +0 10000 15 + +0 10000000000000000000 3 +0 10000000000000000000 5 +0 10000000000000000000 15 + + + + (0,.10 10000 10000000000000000000x)+`-/"1@:(sum_arithmetic_series"1@:(,"1 0"1 _))3 5 15x +23 23331668 23333333333333333331666666666666666668 diff --git a/Task/Sum-multiples-of-3-and-5/Java/sum-multiples-of-3-and-5.java b/Task/Sum-multiples-of-3-and-5/Java/sum-multiples-of-3-and-5.java new file mode 100644 index 0000000000..a433dc7efd --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Java/sum-multiples-of-3-and-5.java @@ -0,0 +1,12 @@ +class SumMultiples { + public static long getSum(long n) { + long sum = 0; + for (int i = 3; i < n; i++) { + if (i % 3 == 0 || i % 5 == 0) sum += i; + } + return sum; + } + public static void main(String[] args) { + System.out.println(getSum(1000)); + } +} diff --git a/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia new file mode 100644 index 0000000000..f1c7a36c24 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia @@ -0,0 +1 @@ +multsum(n, m, lim) = sum(0:n:lim-1) + sum(0:m:lim-1) - sum(0:lcm(n,m):lim-1) diff --git a/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia new file mode 100644 index 0000000000..5d89a6b64d --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia @@ -0,0 +1,2 @@ +multsum(n, lim) = (occ = div(lim-1, n); div(n*occ*(occ+1), 2)) +multsum(n, m, lim) = multsum(n, lim) + multsum(m, lim) - multsum(lcm(n,m), lim) diff --git a/Task/Sum-multiples-of-3-and-5/Limbo/sum-multiples-of-3-and-5.limbo b/Task/Sum-multiples-of-3-and-5/Limbo/sum-multiples-of-3-and-5.limbo new file mode 100644 index 0000000000..609eec1fdd --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Limbo/sum-multiples-of-3-and-5.limbo @@ -0,0 +1,72 @@ +implement Sum3and5; + +include "sys.m"; sys: Sys; +include "draw.m"; +include "ipints.m"; ipints: IPints; + IPint: import ipints; + +Sum3and5: module { + init: fn(nil: ref Draw->Context, args: list of string); +}; + +ints: array of ref IPint; + +init(nil: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + ipints = load IPints IPints->PATH; + + # We use 1, 2, 3, 5, and 15: + ints = array[16] of ref IPint; + for(i := 0; i < len ints; i++) + ints[i] = IPint.inttoip(i); + + args = tl args; + while(args != nil) { + h := hd args; + args = tl args; + # If it's big enough that the result might not + # fit inside a big, we use the IPint version. + if(len h > 9) { + sys->print("%s\n", isum3to5(IPint.strtoip(h, 10)).iptostr(10)); + } else { + sys->print("%bd\n", sum3to5(big h)); + } + } +} + +triangle(n: big): big +{ + return((n * (n + big 1)) / big 2); +} + +sum_multiples(n: big, limit: big): big +{ + return(n * triangle((limit - big 1) / n)); +} + +sum3to5(limit: big): big +{ + return( + sum_multiples(big 3, limit) + + sum_multiples(big 5, limit) - + sum_multiples(big 15, limit)); +} + +itriangle(n: ref IPint): ref IPint +{ + return n.mul(n.add(ints[1])).div(ints[2]).t0; +} + +isum_multiples(n: ref IPint, limit: ref IPint): ref IPint +{ + return n.mul(itriangle(limit.sub(ints[1]).div(n).t0)); +} + +isum3to5(limit: ref IPint): ref IPint +{ + return( + isum_multiples(ints[3], limit). + add(isum_multiples(ints[5], limit)). + sub(isum_multiples(ints[15], limit))); +} diff --git a/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-1.m b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-1.m new file mode 100644 index 0000000000..b12253972f --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-1.m @@ -0,0 +1 @@ +n=1:999; sum(n(mod(n,3)==0 | mod(n,5)==0)) diff --git a/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-2.m b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-2.m new file mode 100644 index 0000000000..0ca04964a5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-2.m @@ -0,0 +1 @@ +n=1000; sum(0:3:n-1)+sum(0:5:n-1)-sum(0:15:n-1) diff --git a/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-3.m b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-3.m new file mode 100644 index 0000000000..be15974910 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/MATLAB/sum-multiples-of-3-and-5-3.m @@ -0,0 +1,5 @@ +n=999; +n3=floor(n/3); +n5=floor(n/5); +n15=floor(n/15); +(3*n3*(n3+1) + 5*n5*(n5+1) - 15*n15*(n15+1))/2 diff --git a/Task/Sum-multiples-of-3-and-5/Maple/sum-multiples-of-3-and-5.maple b/Task/Sum-multiples-of-3-and-5/Maple/sum-multiples-of-3-and-5.maple new file mode 100644 index 0000000000..2042061175 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Maple/sum-multiples-of-3-and-5.maple @@ -0,0 +1,7 @@ +F := unapply( sum(3*i,i=1..floor((n-1)/3)) + + sum(5*i,i=1..floor((n-1)/5)) + - sum(15*i,i=1..floor((n-1)/15)), n); + +F(1000); + +F(10^20); diff --git a/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-1.math b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-1.math new file mode 100644 index 0000000000..56897bd03c --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-1.math @@ -0,0 +1,5 @@ +sum35[n_] := + Sum[k, {k, 3, n - 1, 3}] + Sum[k, {k, 5, n - 1, 5}] - + Sum[k, {k, 15, n - 1, 15}] + +sum35[1000] diff --git a/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-2.math b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-2.math new file mode 100644 index 0000000000..d32d881d7f --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-2.math @@ -0,0 +1 @@ +sum35[10^20] diff --git a/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-3.math b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-3.math new file mode 100644 index 0000000000..4656f2f61c --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Mathematica/sum-multiples-of-3-and-5-3.math @@ -0,0 +1 @@ + Union @@ Range[0, 999, {3, 5}] // Tr diff --git a/Task/Sum-multiples-of-3-and-5/Maxima/sum-multiples-of-3-and-5.maxima b/Task/Sum-multiples-of-3-and-5/Maxima/sum-multiples-of-3-and-5.maxima new file mode 100644 index 0000000000..d0f82a61ec --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Maxima/sum-multiples-of-3-and-5.maxima @@ -0,0 +1,7 @@ +sumi(n, incr):= block([kmax: quotient(n, incr)], + ''(ev(sum(incr*k, k, 1, kmax), simpsum))); + +sum35(n):=sumi(n, 3) + sumi(n, 5) - sumi(n, 15); + +sum35(1000); +sum35(10^20); diff --git a/Task/Sum-multiples-of-3-and-5/NetRexx/sum-multiples-of-3-and-5.netrexx b/Task/Sum-multiples-of-3-and-5/NetRexx/sum-multiples-of-3-and-5.netrexx new file mode 100644 index 0000000000..29a9228e06 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/NetRexx/sum-multiples-of-3-and-5.netrexx @@ -0,0 +1,77 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +numeric digits 40 + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method summing(maxLimit = 1000) public static + mult = 0 + loop mv = 0 while mv < maxLimit + if mv // 3 = 0 | mv // 5 = 0 then + mult = mult + mv + end mv + return mult + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- translation of perl 6 +method sum_mults(first, limit) public static + last = limit - 1 + last = last - last // first + sum = (last / first) * (first + last) % 2 + return sum + +method sum35(maxLimit) public static + return sum_mults(3, maxLimit) + sum_mults(5, maxLimit) - sum_mults(15, maxLimit) + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + + offset = 30 + incr = 10 + + say 'Limit'.right(offset) || '|' || 'Sum' + say '-'.copies(offset) || '+' || '-'.copies(60) + timing = System.nanoTime + sum = summing() + timing = System.nanoTime - timing + say 1000.format.right(offset)'|'sum + say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s' + say + + say 'Limit'.right(offset) || '|' || 'Sum' + say '-'.copies(offset) || '+' || '-'.copies(60) + tmax = 1e+6 + timing = System.nanoTime + mm = 1 + loop while mm <= tmax + say mm.right(offset)'|'summing(mm) + mm = mm * incr + end + timing = System.nanoTime - timing + say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s' + say + + say 'Limit'.right(offset) || '|' || 'Sum' + say '-'.copies(offset) || '+' || '-'.copies(60) + timing = System.nanoTime + sum = sum35(1000) + timing = System.nanoTime - timing + say 1000.format.right(offset)'|'sum + say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s' + say + + say 'Limit'.right(offset) || '|' || 'Sum' + say '-'.copies(offset) || '+' || '-'.copies(60) + tmax = 1e+27 + timing = System.nanoTime + mm = 1 + loop while mm <= tmax + say mm.right(offset)'|'sum35(mm) + mm = mm * incr + end + timing = System.nanoTime - timing + say 'Elapsed time:' Rexx(timing * 1e-9).format(4, 6)'s' + say + return diff --git a/Task/Sum-multiples-of-3-and-5/PARI-GP/sum-multiples-of-3-and-5.pari b/Task/Sum-multiples-of-3-and-5/PARI-GP/sum-multiples-of-3-and-5.pari new file mode 100644 index 0000000000..1d956c1e61 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/PARI-GP/sum-multiples-of-3-and-5.pari @@ -0,0 +1,4 @@ +ct(n,k)=n=n--\k;k*n*(n+1)/2; +a(n)=ct(n,3)+ct(n,5)-ct(n,15); +a(1000) +a(1e20) diff --git a/Task/Sum-multiples-of-3-and-5/PL-I/sum-multiples-of-3-and-5.pli b/Task/Sum-multiples-of-3-and-5/PL-I/sum-multiples-of-3-and-5.pli new file mode 100644 index 0000000000..9b011d73fd --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/PL-I/sum-multiples-of-3-and-5.pli @@ -0,0 +1,13 @@ +threeor5: procedure options (main); /* 8 June 2014 */ + declare (i, n) fixed(10), sum fixed (31) static initial (0); + + get (n); + put ('The number of multiples of 3 or 5 below ' || trim(n) || ' is'); + + do i = 1 to n-1; + if mod(i, 3) = 0 | mod(i, 5) = 0 then sum = sum + i; + end; + + put edit ( trim(sum) ) (A); + +end threeor5; diff --git a/Task/Sum-multiples-of-3-and-5/Pascal/sum-multiples-of-3-and-5.pascal b/Task/Sum-multiples-of-3-and-5/Pascal/sum-multiples-of-3-and-5.pascal new file mode 100644 index 0000000000..4ad63374e1 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Pascal/sum-multiples-of-3-and-5.pascal @@ -0,0 +1,23 @@ +program Sum3sAnd5s; + +function Multiple(x, y: integer): Boolean; + { Is X a multiple of Y? } + begin + Multiple := (X mod Y) = 0 + end; + +function SumMultiples(n: integer): longint; + { Return the sum of all multiples of 3 or 5. } + var i: integer; sum: longint; + begin + sum := 0; + for i := 1 to pred(n) do + if Multiple(i, 3) or Multiple(i, 5) then + sum := sum + i; + SumMultiples := sum + end; + +begin + { Show sum of all multiples less than 1000. } + writeln(SumMultiples(1000)) +end. diff --git a/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-1.pl6 b/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-1.pl6 new file mode 100644 index 0000000000..528888c512 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-1.pl6 @@ -0,0 +1,3 @@ +sub sum35($n) { [+] grep * %% (3|5), ^$n; } + +say sum35 1000; diff --git a/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-2.pl6 b/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-2.pl6 new file mode 100644 index 0000000000..cfb94c1388 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Perl-6/sum-multiples-of-3-and-5-2.pl6 @@ -0,0 +1,10 @@ +sub sum-mults($first, $limit) { + (my $last = $limit - 1) -= $last % $first; + ($last div $first) * ($first + $last) div 2; +} + +sub sum35(\n) { + sum-mults(3,n) + sum-mults(5,n) - sum-mults(15,n); +} + +say sum35($_) for 1,10,100...10**30; diff --git a/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-1.pl b/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-1.pl new file mode 100644 index 0000000000..2811981751 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-1.pl @@ -0,0 +1,11 @@ +#!/usr/bin/perl +use strict ; +use warnings ; +use List::Util qw( sum ) ; + +sub sum_3_5 { + my $limit = shift ; + return sum grep { $_ % 3 == 0 || $_ % 5 == 0 } ( 1..$limit - 1 ) ; +} + +print "The sum is " . sum_3_5( 1000 ) . " !\n" ; diff --git a/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-2.pl b/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-2.pl new file mode 100644 index 0000000000..a38f6b1b14 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Perl/sum-multiples-of-3-and-5-2.pl @@ -0,0 +1,15 @@ +sub tri +{ + my $n = shift; + return $n*($n+1) / 2; +} + +sub sum +{ + my $n = (shift) - 1; + return (3 * tri($n / 3) + 5 * tri($n / 5) - 15 * tri($n / 15)); +} + +say sum(1e3); +use bigint; # Machine precision was sufficient for the first calculation +say sum(1e20); diff --git a/Task/Sum-multiples-of-3-and-5/PicoLisp/sum-multiples-of-3-and-5.l b/Task/Sum-multiples-of-3-and-5/PicoLisp/sum-multiples-of-3-and-5.l new file mode 100644 index 0000000000..5ac09e45eb --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/PicoLisp/sum-multiples-of-3-and-5.l @@ -0,0 +1,12 @@ +(de sumMul (N F) + (let N1 (/ (dec N) F) + (*/ F N1 (inc N1) 2) ) ) + +(for I 20 + (let N (** 10 I) + (println + (- + (+ (sumMul N 3) (sumMul N 5)) + (sumMul N 15) ) ) ) ) + +(bye) diff --git a/Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5.psh b/Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5.psh new file mode 100644 index 0000000000..4e01fef595 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5.psh @@ -0,0 +1,31 @@ +function Get-SumOfMultiples +{ + Param + ( + [Parameter( + Position=0)] + $Cap = 1000, + + [Parameter( + ValueFromRemainingArguments=$True)] + $Multiplier = (3,5) + ) + + $Multiples = @() + $Sum = 0 + $multiplier | + ForEach-Object { + For($i = 1; $i -lt $Cap; $i ++) + { + If($i % $_ -eq 0) + {$Multiples += $i} + } + } + + $Multiples | + select -Unique | + ForEach-Object { + $Sum += $_ + } + $Sum +} diff --git a/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-1.pro b/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-1.pro new file mode 100644 index 0000000000..09e3f5cb75 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-1.pro @@ -0,0 +1,15 @@ +sum_of_multiples_of_3_and_5_slow(N, TT) :- + sum_of_multiples_of_3_and_5(N, 1, 0, TT). + +sum_of_multiples_of_3_and_5(N, K, S, S) :- + 3 * K >= N. + +sum_of_multiples_of_3_and_5(N, K, C, S) :- + T3 is 3 * K, T3 < N, + C3 is C + T3, + T5 is 5 * K, + ( (T5 < N, K mod 3 =\= 0) + -> C5 is C3 + T5 + ; C5 = C3), + K1 is K+1, + sum_of_multiples_of_3_and_5(N, K1, C5, S). diff --git a/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-2.pro b/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-2.pro new file mode 100644 index 0000000000..4b0b535b88 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Prolog/sum-multiples-of-3-and-5-2.pro @@ -0,0 +1,9 @@ +sum_of_multiples_of_3_and_5_fast(N, TT):- + maplist(compute_sum(N), [3,5,15], [TT3, TT5, TT15]), + TT is TT3 + TT5 - TT15. + +compute_sum(N, N1, Sum) :- + ( N mod N1 =:= 0 + -> N2 is N div N1 - 1 + ; N2 is N div N1), + Sum is N1 * N2 * (N2 + 1) / 2. diff --git a/Task/Sum-multiples-of-3-and-5/Python/sum-multiples-of-3-and-5.py b/Task/Sum-multiples-of-3-and-5/Python/sum-multiples-of-3-and-5.py new file mode 100644 index 0000000000..0b23849288 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Python/sum-multiples-of-3-and-5.py @@ -0,0 +1,32 @@ +def sum35a(n): + 'Direct count' + # note: ranges go to n-1 + return sum(x for x in range(n) if x%3==0 or x%5==0) + +def sum35b(n): + "Count all the 3's; all the 5's; minus double-counted 3*5's" + # note: ranges go to n-1 + return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15)) + +def sum35c(n): + 'Sum the arithmetic progressions: sum3 + sum5 - sum15' + consts = (3, 5, 15) + # Note: stop at n-1 + divs = [(n-1) // c for c in consts] + sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)] + return sums[0] + sums[1] - sums[2] + +#test +for n in range(1001): + sa, sb, sc = sum35a(n), sum35b(n), sum35c(n) + assert sa == sb == sc # python tests aren't like those of c. + +print('For n = %7i -> %i\n' % (n, sc)) + +# Pretty patterns +for p in range(7): + print('For n = %7i -> %i' % (10**p, sum35c(10**p))) + +# Scalability +p = 20 +print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p))) diff --git a/Task/Sum-multiples-of-3-and-5/R/sum-multiples-of-3-and-5.r b/Task/Sum-multiples-of-3-and-5/R/sum-multiples-of-3-and-5.r new file mode 100644 index 0000000000..11e7271563 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/R/sum-multiples-of-3-and-5.r @@ -0,0 +1,3 @@ +m35 = function(n) sum(unique(c( + seq(3, n-1, by = 3), seq(5, n-1, by = 5)))) +m35(1000) # 233168 diff --git a/Task/Sum-multiples-of-3-and-5/README b/Task/Sum-multiples-of-3-and-5/README new file mode 100644 index 0000000000..635655ee4a --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 diff --git a/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-1.rexx b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-1.rexx new file mode 100644 index 0000000000..6e927ebd16 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-1.rexx @@ -0,0 +1,12 @@ +/* REXX *************************************************************** +* 14.05.2013 Walter Pachl +**********************************************************************/ +Say mul35() +exit +mul35: +s=0 +Do i=1 To 999 + If i//3=0 | i//5=0 Then + s=s+i + End +Return s diff --git a/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-2.rexx b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-2.rexx new file mode 100644 index 0000000000..8950cac65c --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-2.rexx @@ -0,0 +1,24 @@ +/* REXX *************************************************************** +* Translation from Perl6->NetRexx->REXX +* 15.05.2013 Walter Pachl +**********************************************************************/ +Numeric Digits 100 +call time 'R' +n=1 +Do i=1 To 30 + Say right(n,30) sum35(n) + n=n*10 + End +Say time('E') 'seconds' +Exit + +sum35: Procedure + Parse Arg maxLimit + return sum_mults(3, maxLimit) + sum_mults(5, maxLimit) - sum_mults(15, maxLimit) + +sum_mults: Procedure + Parse Arg first, limit + last = limit - 1 + last = last - last // first + sum = (last % first) * (first + last) % 2 + return sum diff --git a/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-3.rexx b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-3.rexx new file mode 100644 index 0000000000..901bde1844 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/REXX/sum-multiples-of-3-and-5-3.rexx @@ -0,0 +1,15 @@ +/*REXX pgm sums all integers from 1──>N─1 that're multiples of 3 or 5.*/ +parse arg N t .; if N=='' then N=1000; if t=='' then t=1 +numeric digits 9999; numeric digits max(9,20*length(N*10**t)) +say 'The sum of all positive integers that are a multiple of 3 and 5 are:' +say /* [↓] change the look of nE+nn */ + do t; parse value format(N,2,1,,0) 'E0' with y 'E' _ .; _=_+0 + y=right((m/1)'e'_,5)'-1' /*allows for a bug in some REXXes*/ + if t==1 then y=N-1 /*handle special case of one-time*/ + sum=sumDivisors(N-1,3) + sumDivisors(N-1,5) - sumDivisors(N-1,3*5) + say 'integers from 1 ──►' y " is " sum + N=N*10 /*multiply by ten for next round.*/ + end /*t*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SUMDIVISORS subroutine──────────────*/ +sumDivisors: procedure; parse arg x,d; _=x%d; return d*_*(_+1)%2 diff --git a/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-1.rkt b/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-1.rkt new file mode 100644 index 0000000000..8fbebc3b9b --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-1.rkt @@ -0,0 +1,26 @@ +#lang racket +(require math) + +;;; A naive solution +(define (naive k) + (for/sum ([n (expt 10 k)] + #:when (or (divides? 3 n) (divides? 5 n))) + n)) + +(for/list ([k 7]) (naive k)) + + +;;; Using the formula for an arithmetic sum +(define (arithmetic-sum a1 n Δa) + ; returns a1+a2+...+an + (define an (+ a1 (* (- n 1) Δa))) + (/ (* n (+ a1 an)) 2)) + +(define (analytical k) + (define 10^k (expt 10 k)) + (define (n d) (quotient (- 10^k 1) d)) + (+ (arithmetic-sum 3 (n 3) 3) + (arithmetic-sum 5 (n 5) 5) + (- (arithmetic-sum 15 (n 15) 15)))) + +(for/list ([k 20]) (analytical k)) diff --git a/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-2.rkt b/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-2.rkt new file mode 100644 index 0000000000..ee22ef3307 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Racket/sum-multiples-of-3-and-5-2.rkt @@ -0,0 +1,21 @@ +'(0 23 2318 233168 23331668 2333316668 233333166668) +'(0 + 23 + 2318 + 233168 + 23331668 + 2333316668 + 233333166668 + 23333331666668 + 2333333316666668 + 233333333166666668 + 23333333331666666668 + 2333333333316666666668 + 233333333333166666666668 + 23333333333331666666666668 + 2333333333333316666666666668 + 233333333333333166666666666668 + 23333333333333331666666666666668 + 2333333333333333316666666666666668 + 233333333333333333166666666666666668 + 23333333333333333331666666666666666668) diff --git a/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-1.rb b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-1.rb new file mode 100644 index 0000000000..51d9f49f47 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-1.rb @@ -0,0 +1,4 @@ +def sum35(n) + (1...n).select{|i|i%3==0 or i%5==0}.inject(:+) +end +puts sum35(1000) #=> 233168 diff --git a/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-2.rb b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-2.rb new file mode 100644 index 0000000000..cdc868f7c3 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-2.rb @@ -0,0 +1,13 @@ +# Given two integers n1,n2 return sum of multiples upto n3 +# +# Nigel_Galloway +# August 24th., 2013. +def g(n1, n2, n3) + g1 = n1*n2 + (1..g1).select{|x| x%n1==0 or x%n2==0}.collect{|x| g2=(n3-x)/g1; (x+g1*g2+x)*(g2+1)}.inject{|sum,x| sum+x}/2 +end + +puts g(3,5,999) + +# For extra credit +puts g(3,5,100000000000000000000-1) diff --git a/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-3.rb b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-3.rb new file mode 100644 index 0000000000..fa751b9b2a --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Ruby/sum-multiples-of-3-and-5-3.rb @@ -0,0 +1,12 @@ +def sumMul(n, f) + n1 = (n - 1) / f + f * n1 * (n1 + 1) / 2 +end + +def sum35(n) + sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15) +end + +for i in 1..20 + puts "%2d:%22d %s" % [i, 10**i, sum35(10**i)] +end diff --git a/Task/Sum-multiples-of-3-and-5/Run-BASIC/sum-multiples-of-3-and-5.run b/Task/Sum-multiples-of-3-and-5/Run-BASIC/sum-multiples-of-3-and-5.run new file mode 100644 index 0000000000..7bdc3f0cfb --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Run-BASIC/sum-multiples-of-3-and-5.run @@ -0,0 +1,7 @@ +print multSum35(1000) +end +function multSum35(n) + for i = 1 to n - 1 + If (i mod 3 = 0) or (i mod 5 = 0) then multSum35 = multSum35 + i + next i +end function diff --git a/Task/Sum-multiples-of-3-and-5/Scala/sum-multiples-of-3-and-5.scala b/Task/Sum-multiples-of-3-and-5/Scala/sum-multiples-of-3-and-5.scala new file mode 100644 index 0000000000..d6295be44c --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Scala/sum-multiples-of-3-and-5.scala @@ -0,0 +1,21 @@ +def sum35( max:BigInt ) : BigInt = max match { + + // Simplest solution but limited to Ints only + case j if j < 100000 => (1 until j.toInt).filter( i => i % 3 == 0 || i % 5 == 0 ).sum + + // Using a custom iterator that takes Longs + case j if j < 10e9.toLong => { + def stepBy( step:Long ) : Iterator[Long] = new Iterator[Long] { private var i = step; def hasNext = true; def next() : Long = { val result = i; i = i + step; result } } + stepBy(3).takeWhile( _< j ).sum + stepBy(5).takeWhile( _< j ).sum - stepBy(15).takeWhile( _< j ).sum + } + + // Using the formula for a Triangular number + case j => { + def triangle( i:BigInt ) = i * (i+1) / BigInt(2) + 3 * triangle( (j-1)/3 ) + 5 * triangle( (j-1)/5 ) - 15 * triangle( (j-1)/15 ) + } +} + +{ +for( i <- (0 to 20); n = "1"+"0"*i ) println( (" " * (21 - i)) + n + " => " + (" " * (21 - i)) + sum35(BigInt(n)) ) +} diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss new file mode 100644 index 0000000000..23cd4b1006 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss @@ -0,0 +1 @@ +(fold (lambda (x tot) (+ tot (if (or (zero? (remainder x 3)) (zero? (remainder x 5))) x 0))) 0 (iota 1000)) diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss new file mode 100644 index 0000000000..fd6d320984 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss @@ -0,0 +1,8 @@ +(define (fac35? x) + (or (zero? (remainder x 3)) + (zero? (remainder x 5)))) + +(define (fac35filt x tot) + (+ tot (if (fac35? x) x 0))) + +(fold fac35filt 0 (iota 1000)) diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss new file mode 100644 index 0000000000..a672a614d0 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss @@ -0,0 +1,10 @@ +(define (trisum n fac) + (let* ((n1 (quotient (- n 1) fac)) + (n2 (+ n1 1))) + (quotient (* fac n1 n2) 2))) + +(define (fast35sum n) + (- (+ (trisum n 5) (trisum n 3)) (trisum n 15))) + +(fast35sum 1000) +(fast35sum 100000000000000000000) diff --git a/Task/Sum-multiples-of-3-and-5/Seed7/sum-multiples-of-3-and-5.seed7 b/Task/Sum-multiples-of-3-and-5/Seed7/sum-multiples-of-3-and-5.seed7 new file mode 100644 index 0000000000..6dca07c488 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Seed7/sum-multiples-of-3-and-5.seed7 @@ -0,0 +1,25 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const func bigInteger: sum35 (in bigInteger: n) is func + result + var bigInteger: sum35 is 0_; + local + const func bigInteger: sumMul (in bigInteger: n, in bigInteger: f) is func + result + var bigInteger: sumMul is 0_; + local + var bigInteger: n1 is 0_; + begin + n1 := pred(n) div f; + sumMul := f * n1 * succ(n1) div 2_; + end func; + begin + sum35 := sumMul(n, 3_) + sumMul(n, 5_) - sumMul(n, 15_); + end func; + +const proc: main is func + begin + writeln(sum35(1000_)); + writeln(sum35(10_ ** 20)); + end func; diff --git a/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-1.tcl b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-1.tcl new file mode 100644 index 0000000000..3b6da57588 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-1.tcl @@ -0,0 +1,17 @@ +# Fairly simple version; only counts by 3 and 5, skipping intermediates +proc mul35sum {n} { + for {set total [set threes [set fives 0]]} {$threes<$n||$fives<$n} {} { + if {$threes<$fives} { + incr total $threes + incr threes 3 + } elseif {$threes>$fives} { + incr total $fives + incr fives 5 + } else { + incr total $threes + incr threes 3 + incr fives 5 + } + } + return $total +} diff --git a/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-2.tcl b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-2.tcl new file mode 100644 index 0000000000..c618ace922 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-2.tcl @@ -0,0 +1,9 @@ +# Smart version; no iteration so very scalable! +proc tcl::mathfunc::triangle {n} {expr { + $n * ($n+1) / 2 +}} +# Note that the rounding on integer division is exactly what we need here. +proc sum35 {n} { + incr n -1 + expr {3*triangle($n/3) + 5*triangle($n/5) - 15*triangle($n/15)} +} diff --git a/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-3.tcl b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-3.tcl new file mode 100644 index 0000000000..b0bd937c30 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Tcl/sum-multiples-of-3-and-5-3.tcl @@ -0,0 +1,4 @@ +puts [mul35sum 1000],[sum35 1000] +puts [mul35sum 10000000],[sum35 10000000] +# Just the quick one; waiting for the other would get old quickly... +puts [sum35 100000000000000000000] diff --git a/Task/Sum-multiples-of-3-and-5/XPL0/sum-multiples-of-3-and-5.xpl0 b/Task/Sum-multiples-of-3-and-5/XPL0/sum-multiples-of-3-and-5.xpl0 new file mode 100644 index 0000000000..d1d475eb6f --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/XPL0/sum-multiples-of-3-and-5.xpl0 @@ -0,0 +1,42 @@ +include c:\cxpl\stdlib; + +func Sum1; \Return sum the straightforward way +int N, S; +[S:= 0; +for N:= 1 to 999 do + if rem(N/3)=0 or rem(N/5)=0 then S:= S+N; +return S; +]; + +func Sum2(D); \Return sum of sequence using N*(N+1)/2 +int D; +int Q; +[Q:= (1000-1)/D; +return Q*(Q+1)/2*D; +]; + +func Sum3(D); \Return sum of sequence for really big number +string 0; \don't terminate strings by setting most significant bit +int D; \divisor +int I; +char P(40), Q(40), R(40); \product, quotient, result +[StrNDiv("99999999999999999999", D, Q, 20); \Q:= (1E20-1)/D +for I:= 0 to 17 do R(I):= ^0; \R:= D +R(18):= D/10 +^0; +R(19):= rem(0) +^0; +StrNMul(Q, R, P, 20); \P:= Q*R = Q*D +StrNAdd("00000000000000000001", Q, 20); \Q:= Q+1 +StrNMul(P+20, Q, R, 20); \R:= P*Q = Q*D*(Q+1) +StrNDiv(R, 2, Q, 40); \Q:= P/2 = Q*D*(Q+1)/2 +return Q; \(very temporary location) +]; + +char S(40), T; +[IntOut(0, Sum1); CrLf(0); + IntOut(0, Sum2(3) + Sum2(5) - Sum2(3*5)); CrLf(0); +StrNCopy(Sum3(3), S, 40); +StrNAdd(Sum3(5), S, 40); +T:= Sum3(3*5); +StrNSub(S, T, 40); +TextN(0, T, 40); CrLf(0); +] diff --git a/Task/Textonyms/00DESCRIPTION b/Task/Textonyms/00DESCRIPTION new file mode 100644 index 0000000000..153a1b6dbf --- /dev/null +++ b/Task/Textonyms/00DESCRIPTION @@ -0,0 +1,33 @@ +When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. + +Assuming the digit keys are mapped to letters as follows: + 2 -> ABC + 3 -> DEF + 4 -> GHI + 5 -> JKL + 6 -> MNO + 7 -> PQRS + 8 -> TUV + 9 -> WXYZ + +The task is to write a program that finds textonyms in a list of words such as [[Textonyms/wordlist]] or [http://www.puzzlers.org/pub/wordlists/unixdict.txt]. + +The task should produce a report: + + There are #{0} words in #{1} which can be represented by the digit key mapping. + They require #{2} digit combinations to represent them. + #{3} digit combinations represent Textonyms. + +Where: + #{0} is the number of words in the list which can be represented by the digit key mapping. + #{1} is the URL of the wordlist being used. + #{2} is the number of digit combinations required to represent the words in #{0}. + #{3} is the number of #{2} which represent more than one word. + +At your discretion show a couple of examples of your solution displaying Textonys. e.g. + + 2748424767 -> "Briticisms", "criticisms" + +Extra credit: + +Use a word list and keypad mapping other than English. diff --git a/Task/Textonyms/Go/textonyms.go b/Task/Textonyms/Go/textonyms.go new file mode 100644 index 0000000000..351cc05c50 --- /dev/null +++ b/Task/Textonyms/Go/textonyms.go @@ -0,0 +1,141 @@ +package main + +import ( + "bufio" + "flag" + "fmt" + "io" + "log" + "os" + "strings" + "unicode" +) + +func main() { + log.SetFlags(0) + log.SetPrefix("textonyms: ") + + wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") + flag.Parse() + if flag.NArg() != 0 { + flag.Usage() + os.Exit(2) + } + + t := NewTextonym(phoneMap) + _, err := ReadFromFile(t, *wordlist) + if err != nil { + log.Fatal(err) + } + t.Report(os.Stdout, *wordlist) +} + +// phoneMap is the digit to letter mapping of a typical phone. +var phoneMap = map[byte][]rune{ + '2': []rune("ABC"), + '3': []rune("DEF"), + '4': []rune("GHI"), + '5': []rune("JKL"), + '6': []rune("MNO"), + '7': []rune("PQRS"), + '8': []rune("TUV"), + '9': []rune("WXYZ"), +} + +// ReadFromFile is a generic convience function that allows the use of a +// filename with an io.ReaderFrom and handles errors related to open and +// closing the file. +func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) { + f, err := os.Open(filename) + if err != nil { + return 0, err + } + n, err := r.ReadFrom(f) + if cerr := f.Close(); err == nil && cerr != nil { + err = cerr + } + return n, err +} + +type Textonym struct { + numberMap map[string][]string // map numeric string into words + letterMap map[rune]byte // map letter to digit + count int // total number of words in numberMap + textonyms int // number of numeric strings with >1 words +} + +func NewTextonym(dm map[byte][]rune) *Textonym { + lm := make(map[rune]byte, 26) + for d, ll := range dm { + for _, l := range ll { + lm[l] = d + } + } + return &Textonym{letterMap: lm} +} + +func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) { + t.numberMap = make(map[string][]string) + buf := make([]byte, 0, 32) + sc := bufio.NewScanner(r) + sc.Split(bufio.ScanWords) +scan: + for sc.Scan() { + buf = buf[:0] + word := sc.Text() + + // XXX we only bother approximating the number of bytes + // consumed. This isn't used in the calling code and was + // only included to match the io.ReaderFrom interface. + n += int64(len(word)) + 1 + + for _, r := range word { + d, ok := t.letterMap[unicode.ToUpper(r)] + if !ok { + //log.Printf("ignoring %q\n", word) + continue scan + } + buf = append(buf, d) + } + //log.Printf("scanned %q\n", word) + num := string(buf) + t.numberMap[num] = append(t.numberMap[num], word) + t.count++ + if len(t.numberMap[num]) == 2 { + t.textonyms++ + } + //log.Printf("%q → %v\t→ %v\n", word, num, t.numberMap[num]) + } + return n, sc.Err() +} + +func (t *Textonym) Most() (most int, subset map[string][]string) { + for k, v := range t.numberMap { + switch { + case len(v) > most: + subset = make(map[string][]string) + most = len(v) + fallthrough + case len(v) == most: + subset[k] = v + } + } + return most, subset +} + +func (t *Textonym) Report(w io.Writer, name string) { + // Could be fancy and use text/template package but fmt is sufficient + fmt.Fprintf(w, ` +There are %v words in %q which can be represented by the digit key mapping. +They require %v digit combinations to represent them. +%v digit combinations represent Textonyms. +`, + t.count, name, len(t.numberMap), t.textonyms) + + n, sub := t.Most() + fmt.Fprintln(w, "\nThe numbers mapping to the most words map to", + n, "words each:") + for k, v := range sub { + fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", ")) + } +} diff --git a/Task/Textonyms/J/textonyms-1.j b/Task/Textonyms/J/textonyms-1.j new file mode 100644 index 0000000000..de26c1dfc4 --- /dev/null +++ b/Task/Textonyms/J/textonyms-1.j @@ -0,0 +1,38 @@ +require'regex strings web/gethttp' + +strip=:dyad define + (('(?s)',x);'') rxrplc y +) + +fetch=:monad define + txt=. '.*
' strip '
.*' strip gethttp y + cutopen tolower txt-.' ' +) + +keys=:noun define + 2 abc + 3 def + 4 ghi + 5 jkl + 6 mno + 7 pqrs + 8 tuv + 9 wxyz +) + +reporttext=:noun define +There are #{0} words in #{1} which can be represented by the digit key mapping. +They require #{2} digit combinations to represent them. +#{3} digit combinations represent Textonyms. +) + +report=:dyad define + x rplc (":&.>y),.~('#{',":,'}'"_)&.>i.#y +) + +textonymrpt=:dyad define + 'digits letters'=. |:>;,&.>,&.>/&.>/"1 <;._1;._2 x + valid=. (#~ */@e.&letters&>) fetch y NB. ignore illegals + reps=. {&digits@(letters&i.)&.> valid NB. reps is digit seq + reporttext report (#valid);y;(#~.reps);+/(1<#)/.~reps +) diff --git a/Task/Textonyms/J/textonyms-2.j b/Task/Textonyms/J/textonyms-2.j new file mode 100644 index 0000000000..bfd859029e --- /dev/null +++ b/Task/Textonyms/J/textonyms-2.j @@ -0,0 +1,4 @@ + keys textonymrpt 'http://rosettacode.org/wiki/Textonyms/wordlist' +There are 13085 words in http://rosettacode.org/wiki/Textonyms/wordlist which can be represented by the digit key mapping. +They require 11932 digit combinations to represent them. +661 digit combinations represent Textonyms. diff --git a/Task/Textonyms/J/textonyms-3.j b/Task/Textonyms/J/textonyms-3.j new file mode 100644 index 0000000000..79b036b02c --- /dev/null +++ b/Task/Textonyms/J/textonyms-3.j @@ -0,0 +1,12 @@ + digits +22233344455566677778889999 + letters +abcdefghijklmnopqrstuvwxyz + 5{.valid +┌─┬──┬───┬───┬──┐ +│a│aa│aaa│aam│ab│ +└─┴──┴───┴───┴──┘ + 5{.reps +┌─┬──┬───┬───┬──┐ +│2│22│222│226│22│ +└─┴──┴───┴───┴──┘ diff --git a/Task/Textonyms/J/textonyms-4.j b/Task/Textonyms/J/textonyms-4.j new file mode 100644 index 0000000000..1346a2cd50 --- /dev/null +++ b/Task/Textonyms/J/textonyms-4.j @@ -0,0 +1,4 @@ + keys textonymrpt 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' +There are 24978 words in http://www.puzzlers.org/pub/wordlists/unixdict.txt which can be represnted by the digit key mapping. +They require 22903 digit combinations to represent them. +1473 digit combinations represent Textonyms. diff --git a/Task/Textonyms/Perl-6/textonyms.pl6 b/Task/Textonyms/Perl-6/textonyms.pl6 new file mode 100644 index 0000000000..98941f7c54 --- /dev/null +++ b/Task/Textonyms/Perl-6/textonyms.pl6 @@ -0,0 +1,22 @@ +my $src = 'unixdict.txt'; + +my @words = slurp($src).lines.grep(/ ^ + $ /); + +my @dials = @words.classify: { + .trans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' + => '2223334445556667777888999922233344455566677778889999'); +} + +my @textonyms = @dials.grep(*.value > 1); + +say qq:to 'END'; + There are {+@words} words in $src which can be represented by the digit key mapping. + They require {+@dials} digit combinations to represent them. + {+@textonyms} digit combinations represent Textonyms. + END + +say "Top 5 in ambiguity:"; +say " ",$_ for @textonyms.sort(-*.value)[^5]; + +say "\nTop 5 in length:"; +say " ",$_ for @textonyms.sort(-*.key.chars)[^5]; diff --git a/Task/Textonyms/Perl/textonyms.pl b/Task/Textonyms/Perl/textonyms.pl new file mode 100644 index 0000000000..1247f644c9 --- /dev/null +++ b/Task/Textonyms/Perl/textonyms.pl @@ -0,0 +1,7 @@ +sub find { + my @m = qw/$ $ abc def ghi jkl mno pqrs tvu wxyz/; + (my $r = shift) =~ s{(\d)}{[$m[$1]]}g; + grep /^$r$/i, split ' ', `cat words.txt`; # cats don't run on windows +} + +print join("\n", $_, find($_)), "\n\n" for @ARGV diff --git a/Task/Textonyms/Python/textonyms.py b/Task/Textonyms/Python/textonyms.py new file mode 100644 index 0000000000..69d9dafde0 --- /dev/null +++ b/Task/Textonyms/Python/textonyms.py @@ -0,0 +1,62 @@ +from collections import defaultdict +import urllib.request + +CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} +URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' + + +def getwords(url): + return urllib.request.urlopen(url).read().decode("utf-8").lower().split() + +def mapnum2words(words): + number2words = defaultdict(list) + reject = 0 + for word in words: + try: + number2words[''.join(CH2NUM[ch] for ch in word)].append(word) + except KeyError: + # Reject words with non a-z e.g. '10th' + reject += 1 + return dict(number2words), reject + +def interactiveconversions(): + global inp, ch, num + while True: + inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower() + if inp: + if all(ch in '23456789' for ch in inp): + if inp in num2words: + print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join( + num2words[inp]))) + else: + print(" Number {0} has no textonyms in the dictionary.".format(inp)) + elif all(ch in CH2NUM for ch in inp): + num = ''.join(CH2NUM[ch] for ch in inp) + print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format( + inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num]))) + else: + print(" I don't understand %r" % inp) + else: + print("Thank you") + break + + +if __name__ == '__main__': + words = getwords(URL) + print("Read %i words from %r" % (len(words), URL)) + wordset = set(words) + num2words, reject = mapnum2words(words) + morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1) + maxwordpernum = max(len(values) for values in num2words.values()) + print(""" +There are {0} words in {1} which can be represented by the Textonyms mapping. +They require {2} digit combinations to represent them. +{3} digit combinations represent Textonyms.\ +""".format(len(words) - reject, URL, len(num2words), morethan1word)) + + print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum) + maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum) + for num, wrds in maxwpn: + print(" %s maps to: %s" % (num, ', '.join(wrds))) + + interactiveconversions() diff --git a/Task/Textonyms/README b/Task/Textonyms/README new file mode 100644 index 0000000000..3dcd418f35 --- /dev/null +++ b/Task/Textonyms/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Textonyms diff --git a/Task/Textonyms/REXX/textonyms.rexx b/Task/Textonyms/REXX/textonyms.rexx new file mode 100644 index 0000000000..2189a4e39d --- /dev/null +++ b/Task/Textonyms/REXX/textonyms.rexx @@ -0,0 +1,47 @@ +/*REXX program counts the number of textonyms are in a file (dictionary)*/ +parse arg iFID . /*get optional fileID of the file*/ +if iFID=='' then iFID='UNIXDICT.TXT' /*filename of the word dictionary*/ +@.=0 /*digit combinations placeholder.*/ +!.=; $.= /*sparse array of textonyms;words*/ +alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*supported alphabet to be used. */ +digitKey= 22233344455566677778889999 /*translated alphabet to dig key.*/ +digKey=0; wordCount=0 /*# digit combinations; wordCount*/ +ills=0; dups=0; longest=0; mostus=0 /*illegals; duplicate words; lit.*/ +first=0; last=0; long=0; most=0 /*for: first, last, longest, ··· */ +call linein iFID, 1, 0 /*point to the first char in dict*/ +#=0 /*number of textonyms in the file*/ + /* [↑] ───in case file is open.*/ + do j=1 while lines(iFID)\==0 /*keep reading until exhausted. */ + x=linein(iFID); y=x; upper x /*get a word and uppercase it. */ + if \datatype(x,'U') then do; ills=ills+1; iterate; end /*illegal? */ + if $.x\=='' then do; dups=dups+1; iterate; end /*duplicate?*/ + else $.x=. /*indicate it's a righteous word.*/ + wordCount=wordCount+1 /*bump the word count (for file).*/ + z=translate(x, digitKey, alphabet) /*build translated digit key word*/ + @.z=@.z+1 /*flag the digit key word exists.*/ + !.z=!.z y; _=words(!.z) /*build a list of same digit key.*/ + if _>most then do; mostus=z; most=_; end /*remember mostus digKeys.*/ + if @.z==2 then do; #=#+1 /*bump the count of the textonyms*/ + if first==0 then first=z /*the first textonym found*/ + last=z /* " last " " */ + _=length(!.z) /*length of the digit key.*/ + if _>longest then long=z /*is this the longest ? */ + longest=max(_, longest) /*now, shoot for this len.*/ + end /* [↑] discretionary stuff*/ + if @.z\==1 then iterate /*Does it already exist? Skip it*/ + digKey=digKey+1 /*bump count of digit key words. */ + end /*j*/ + @@=' which can be represented by the digit key mapping.' +say wordCount 'is the number of words in file "'iFID'"' @@ +if ills\==0 then say ills 'word's(ills) "contained illegal characters." +if dups\==0 then say dups "duplicate word"s(dups) 'detected.' +say 'They require' digKey "combination"s(digKey) 'to represent them.' +say # 'digit combination's(#) "represent Textonyms." +say +if first\==0 then say ' first digit key=' !.first +if last\==0 then say ' last digit key=' !.last +if long\==0 then say ' longest digit key=' !.long +if most\==0 then say ' numerous digit key=' !.mostus ' ('most "words)" +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────S subroutine────────────────────────*/ +s: if arg(1)==1 then return ''; return 's' /*a simple pluralizer.*/ diff --git a/Task/Textonyms/Ruby/textonyms.rb b/Task/Textonyms/Ruby/textonyms.rb new file mode 100644 index 0000000000..97e4137762 --- /dev/null +++ b/Task/Textonyms/Ruby/textonyms.rb @@ -0,0 +1,7 @@ +Textonyms = Hash.new {|n, g| n[g] = []} +File.open("Textonyms.txt") do |file| + file.each_line {|line| + Textonyms[(n=line.chomp).gsub(/a|b|c|A|B|C/, '2').gsub(/d|e|f|D|E|F/, '3').gsub(/g|h|i|G|H|I/, '4').gsub(/p|q|r|s|P|Q|R|S/, '7') + .gsub(/j|k|l|J|K|L/, '5').gsub(/m|n|o|M|N|O/, '6').gsub(/t|u|v|T|U|V/, '8').gsub(/w|x|y|z|W|X|Y|Z/, '9')] += [n] + } +end diff --git a/Task/Textonyms/VBScript/textonyms.vb b/Task/Textonyms/VBScript/textonyms.vb new file mode 100644 index 0000000000..65867eb269 --- /dev/null +++ b/Task/Textonyms/VBScript/textonyms.vb @@ -0,0 +1,47 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\unixdict.txt",1) +Set objKeyMap = CreateObject("Scripting.Dictionary") + With objKeyMap + .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" + .Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9" + End With + +'Instantiate or Intialize Counters +TotalWords = 0 +UniqueCombinations = 0 +Set objUniqueWords = CreateObject("Scripting.Dictionary") +Set objMoreThanOneWord = CreateObject("Scripting.Dictionary") + +Do Until objInFile.AtEndOfStream + Word = objInFile.ReadLine + c = 0 + Num = "" + If Word <> "" Then + For i = 1 To Len(Word) + For Each Key In objKeyMap.Keys + If InStr(1,Key,Mid(Word,i,1),1) > 0 Then + Num = Num & objKeyMap.Item(Key) + c = c + 1 + End If + Next + Next + If c = Len(Word) Then + TotalWords = TotalWords + 1 + If objUniqueWords.Exists(Num) = False Then + objUniqueWords.Add Num, "" + UniqueCombinations = UniqueCombinations + 1 + Else + If objMoreThanOneWord.Exists(Num) = False Then + objMoreThanOneWord.Add Num, "" + End If + End If + End If + End If +Loop + +WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_ + "They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_ + objMoreThanOneWord.Count & " digit combinations represent Textonyms." + +objInFile.Close diff --git a/Task/The-ISAAC-Cipher/00DESCRIPTION b/Task/The-ISAAC-Cipher/00DESCRIPTION new file mode 100644 index 0000000000..5d334e0623 --- /dev/null +++ b/Task/The-ISAAC-Cipher/00DESCRIPTION @@ -0,0 +1,56 @@ +ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages. +It is also simple and succinct, using as it does just two 256-word arrays for its state. + +ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed. +To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling). +ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented. + +Your task, should you choose to accept it, is to translate ISAAC's reference +C or Pascal code into your language of choice. +The RNG should then be seeded with the string "this is my secret key" and +finally the message "a Top Secret secret" should be encrypted on that key. +Your program's output ciphertext will be a string of hexadecimal digits. + +Optional: Include a decryption check by re-initializing ISAAC and performing +the same encryption pass on the ciphertext. + +Please use the C or Pascal as a reference guide to these operations. + +Two encryption schemes are possible: +(1) XOR (Vernam) or +(2) Caesar-shift mod 95 (Vigenère). +XOR is the simplest; C-shifting offers greater security. + +You may choose either scheme, or both, but please specify which you used. +Here are the alternative sample outputs for checking purposes: + +
+Message: a Top Secret secret
+Key    : this is my secret key
+XOR    : 1C0636190B1260233B35125F1E1D0E2F4C5422
+MOD    : 734270227D36772A783B4F2A5F206266236978
+XOR dcr: a Top Secret secret
+MOD dcr: a Top Secret secret
+
+ +No official seeding method for ISAAC has been published, but for this task +we may as well just inject the bytes of our key into the randrsl array, +padding with zeroes before mixing, like so: + +
+// zeroise mm array
+FOR i:= 0 TO 255 DO mm[i]:=0;
+// check seed's highest array element
+m := High(seed);
+// inject the seed
+FOR i:= 0 TO 255 DO BEGIN
+	// in case seed[] has less than 256 elements.
+	IF i>m THEN randrsl[i]:=0
+		ELSE randrsl[i]:=seed[i];
+END;
+// initialize ISAAC with seed
+RandInit(true);
+
+ +ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes. +But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose. diff --git a/Task/The-ISAAC-Cipher/00META.yaml b/Task/The-ISAAC-Cipher/00META.yaml new file mode 100644 index 0000000000..fdbbfe89ad --- /dev/null +++ b/Task/The-ISAAC-Cipher/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Encryption diff --git a/Task/The-ISAAC-Cipher/C-sharp/the-isaac-cipher.cs b/Task/The-ISAAC-Cipher/C-sharp/the-isaac-cipher.cs new file mode 100644 index 0000000000..b2da0b6e9e --- /dev/null +++ b/Task/The-ISAAC-Cipher/C-sharp/the-isaac-cipher.cs @@ -0,0 +1,159 @@ +using System; + +namespace cipher { + +static class Cipher { + +// external results +static uint[] randrsl = new uint[256]; +static uint randcnt; +// internal state +static uint[] mm = new uint[256]; +static uint aa=0, bb=0, cc=0; + + +static void isaac() { + uint i,x,y; + cc++; // cc just gets incremented once per 256 results + bb+=cc; // then combined with bb + + for (i=0; i<=255; i++) { + x = mm[i]; + switch (i & 3) { + case 0: aa = aa ^ (aa << 13); break; + case 1: aa = aa ^ (aa >> 6); break; + case 2: aa = aa ^ (aa << 2); break; + case 3: aa = aa ^ (aa >> 16); break; + } + aa = mm[(i+128) & 255] + aa; + y = mm[(x >> 2) & 255] + aa + bb; + mm[i] = y; + bb = mm[(y >> 10) & 255] + x; + randrsl[i]= bb; + } +} + + +// if (flag==TRUE), then use the contents of randrsl[] to initialize mm[]. +static void mix(ref uint a, ref uint b, ref uint c, ref uint d, ref uint e, ref uint f, ref uint g, ref uint h) { + a = a ^ b << 11; d+=a; b+=c; + b = b ^ c >> 2; e+=b; c+=d; + c = c ^ d << 8; f+=c; d+=e; + d = d ^ e >> 16; g+=d; e+=f; + e = e ^ f << 10; h+=e; f+=g; + f = f ^ g >> 4; a+=f; g+=h; + g = g ^ h << 8; b+=g; h+=a; + h = h ^ a >> 9; c+=h; a+=b; +} + + +static void Init(bool flag) { + short i; uint a,b,c,d,e,f,g,h; + + aa=0; bb=0; cc=0; + a=0x9e3779b9; b=a; c=a; d=a; + e=a; f=a; g=a; h=a; + + for (i=0; i<=3; i++) // scramble it + mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h); + + i=0; + do { // fill in mm[] with messy stuff + if (flag) { // use all the information in the seed + a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3]; + e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7]; + } // if flag + + mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h); + mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d; + mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h; + i+=8; + } + while (i<255); + + if (flag) { + // do a second pass to make all of the seed affect all of mm + i=0; + do { + a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3]; + e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7]; + mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h); + mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d; + mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h; + i+=8; + } + while (i<255); + } + isaac(); // fill in the first set of results + randcnt=0; // prepare to use the first set of results +} + + +// Seed ISAAC with a string +static void Seed(string seed, bool flag) { + for (int i=0; i<256; i++) mm[i]=0; + for (int i=0; i<256; i++) randrsl[i]=0; + int m = seed.Length; + for (int i=0; i255) { + isaac(); randcnt=0; + } + return result; +} + + +// Get a random character in printable ASCII range +static byte RandA() { + return (byte)(Random() % 95 + 32); +} + + +// XOR encrypt on random stream. Output: ASCII byte array +static byte[] Vernam(string msg) + { + int n,l; + byte[] v = new byte[msg.Length]; + l = msg.Length; + // XOR message + for (n=0; n +#include +#include +#ifdef _MSC_VER + typedef unsigned __int32 uint32_t; +#else + #include +#endif + +/* a ub4 is an unsigned 4-byte quantity */ +typedef uint32_t ub4; + +/* external results */ +ub4 randrsl[256], randcnt; + +/* internal state */ +static ub4 mm[256]; +static ub4 aa=0, bb=0, cc=0; + +void isaac() +{ + register ub4 i,x,y; + + cc = cc + 1; /* cc just gets incremented once per 256 results */ + bb = bb + cc; /* then combined with bb */ + + for (i=0; i<256; ++i) + { + x = mm[i]; + switch (i%4) + { + case 0: aa = aa^(aa<<13); break; + case 1: aa = aa^(aa>>6); break; + case 2: aa = aa^(aa<<2); break; + case 3: aa = aa^(aa>>16); break; + } + aa = mm[(i+128)%256] + aa; + mm[i] = y = mm[(x>>2)%256] + aa + bb; + randrsl[i] = bb = mm[(y>>10)%256] + x; + } + // not in original readable.c + randcnt = 0; +} + +/* if (flag!=0), then use the contents of randrsl[] to initialize mm[]. */ +#define mix(a,b,c,d,e,f,g,h) \ +{ \ + a^=b<<11; d+=a; b+=c; \ + b^=c>>2; e+=b; c+=d; \ + c^=d<<8; f+=c; d+=e; \ + d^=e>>16; g+=d; e+=f; \ + e^=f<<10; h+=e; f+=g; \ + f^=g>>4; a+=f; g+=h; \ + g^=h<<8; b+=g; h+=a; \ + h^=a>>9; c+=h; a+=b; \ +} + +void randinit(int flag) +{ + register int i; + ub4 a,b,c,d,e,f,g,h; + aa=bb=cc=0; + a=b=c=d=e=f=g=h=0x9e3779b9; /* the golden ratio */ + + for (i=0; i<4; ++i) /* scramble it */ + { + mix(a,b,c,d,e,f,g,h); + } + + for (i=0; i<256; i+=8) /* fill in mm[] with messy stuff */ + { + if (flag) /* use all the information in the seed */ + { + a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3]; + e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7]; + } + mix(a,b,c,d,e,f,g,h); + mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d; + mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h; + } + + if (flag) + { /* do a second pass to make all of the seed affect all of mm */ + for (i=0; i<256; i+=8) + { + a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3]; + e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7]; + mix(a,b,c,d,e,f,g,h); + mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d; + mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h; + } + } + + isaac(); /* fill in the first set of results */ + randcnt=0; /* prepare to use the first set of results */ +} + + +// Get a random 32-bit value 0..MAXINT +ub4 iRandom() +{ + ub4 r = randrsl[randcnt]; + ++randcnt; + if (randcnt >255) { + isaac(); + randcnt = 0; + } + return r; +} + + +// Get a random character in printable ASCII range +char iRandA() +{ + return iRandom() % 95 + 32; +} + + +// Seed ISAAC with a string +void iSeed(char *seed, int flag) +{ + register ub4 i,m; + for (i=0; i<256; i++) mm[i]=0; + m = strlen(seed); + for (i=0; i<256; i++) + { + // in case seed has less than 256 elements + if (i>m) randrsl[i]=0; else randrsl[i] = seed[i]; + } + // initialize ISAAC with seed + randinit(flag); +} + + +// maximum length of message +#define MAXMSG 4096 +#define MOD 95 +#define START 32 +// cipher modes for Caesar +enum ciphermode { + mEncipher, mDecipher, mNone +}; + + +// XOR cipher on random stream. Output: ASCII string +char v[MAXMSG]; +char* Vernam(char *msg) + { + register ub4 i,l; + l = strlen(msg); + // zeroise v + memset(v,'\0',l+1); + // XOR message + for (i=0; i> 6); break; + case 2: aa ^= (aa << 2); break; + case 3: aa ^= (aa >> 16); break; + } + + aa = mm[(i + 128) % $] + aa; + immutable y = mm[(x >> 2) % $] + aa + bb; + bb = mm[(y >> 10) % $] + x; + randResult[i] = bb; + } + + randCount = 0; + } + + + // If flag is true then use the contents of randResult to initialize mm. + private pure nothrow @safe @nogc static void mix(ref uint[8] a) { + alias shifts = TypeTuple!(11, 2, 8, 16, 10, 4, 8, 9); + /*static*/ foreach (immutable i, immutable sh; shifts) { + static if (i % 2 == 0) + a[i] ^= a[(i + 1) % $] << sh; + else + a[i] ^= a[(i + 1) % $] >> sh; + a[(i + 3) % $] += a[i]; + a[(i + 1) % $] += a[(i + 2) % $]; + } + } + + + private void randInit(bool flag)() pure nothrow @safe @nogc { + uint[8] a = 0x9E37_79B9; // The Golden Ratio. + aa = bb = cc = 0; + + // Scramble it. + /*static*/ foreach (immutable i; staticIota!(0, 4)) + mix(a); + + // Fill in mm with messy stuff. Use all the information in the seed. + for (size_t i = 0; i < mm.length; i += 8) { + static if (flag) + a[] += randResult[i .. i + 8]; + mix(a); + mm[i .. i + 8] = a[]; + } + + // Do a second pass to make all of the seed affect all of mm. + static if (flag) { + for (size_t i = 0; i < mm.length; i += 8) { + a[] += mm[i .. i + 8]; + mix(a); + mm[i .. i + 8] = a[]; + } + } + + isaac(); // Fill in the first set of results. + randCount = 0; // Prepare to use the first set of results. + } + + + /// Seed ISAAC with a string. + /// Uses only the first randResult.length ubytes. + public void iSeed(bool flag)(in ubyte[] seed) pure nothrow @safe @nogc { + mm[] = 0; + randResult[] = 0; + + immutable n = min(randResult.length, seed.length); + copy(seed[0 .. n], randResult[0 .. n]); + + randInit!flag(); // Initialize ISAAC with seed. + } + + + /// Get a random uint. + private uint iRandom() pure nothrow @safe @nogc { + immutable result = randResult[randCount]; + + randCount++; + if (randCount > (randResult.length - 1)) { + isaac(); + randCount = 0; + } + + return result; + } + + + /// Get a random character in printable ASCII range. + private ubyte iRandA() pure nothrow @safe @nogc { + return iRandom() % 95 + 32; + } + + + /// XOR encrypt on random stream. + /// buffer must be as large as message or larger. + public ubyte[] vernam(in ubyte[] message, ubyte[] buffer) + pure nothrow @safe @nogc + in { + assert(buffer.length >= message.length); + } out(result) { + assert(result.length == message.length); + } body { + auto v = buffer[0 .. message.length]; + + // XOR message. + foreach (immutable i, immutable msgi; message) + v[i] = (iRandA() ^ msgi); + return v; + } + + + /// XOR encrypt on random stream. + public ubyte[] vernam(in ubyte[] message) pure nothrow @safe { + return vernam(message, new ubyte[message.length]); + } +} + + +void main() { + import std.stdio, std.string; + + immutable message = "a Top Secret secret"; + immutable key = "this is my secret key"; + + writeln("Message : ", message); + writeln("Key : ", key); + + ISAAC cipher; + + // Encrypt. + // iSeed uses only the first ISAAC.randResult.length ubytes. + cipher.iSeed!true(key.representation); + const encrypted = cipher.vernam(message.representation); + + // Output ciphertext as a string of hexadecimal digits. + writefln("Encrypted: %(%02X%)", encrypted); + + // Decrypt. + cipher.iSeed!true(key.representation); + const decrypted = cipher.vernam(encrypted); + + writeln("Decrypted: ", decrypted.assumeUTF); +} diff --git a/Task/The-ISAAC-Cipher/Delphi/the-isaac-cipher.delphi b/Task/The-ISAAC-Cipher/Delphi/the-isaac-cipher.delphi new file mode 100644 index 0000000000..a075c930b8 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Delphi/the-isaac-cipher.delphi @@ -0,0 +1,198 @@ +{$apptype console} +PROGRAM RosettaIsaac; +USES SysUtils; + +// TASK globals +VAR msg : STRING = 'a Top Secret secret'; +VAR key : STRING = 'this is my secret key'; +VAR xctx: STRING = ''; // XOR ciphertext +VAR mctx: STRING = ''; // MOD ciphertext + +// ISAAC globals +// external results +VAR randrsl: ARRAY[0..256] OF CARDINAL; +VAR randcnt: cardinal; +// internal state +VAR mm: ARRAY[0..256] OF CARDINAL; +VAR aa: CARDINAL=0; bb: CARDINAL=0; cc: CARDINAL=0; + + +PROCEDURE Isaac; +VAR i,x,y: CARDINAL; +BEGIN + cc := cc + 1; // cc just gets incremented once per 256 results + bb := bb + cc; // then combined with bb + + FOR i := 0 TO 255 DO BEGIN + x := mm[i]; + CASE (i mod 4) OF + 0: aa := aa xor (aa shl 13); + 1: aa := aa xor (aa shr 6); + 2: aa := aa xor (aa shl 2); + 3: aa := aa xor (aa shr 16); + END; + aa := mm[(i+128) mod 256] + aa; + y := mm[(x shr 2) mod 256] + aa + bb; + mm[i] := y; + bb := mm[(y shr 10) mod 256] + x; + randrsl[i]:= bb; + END; + // this reset was not in original readable.c! + randcnt:=0; // prepare to use the first set of results +END; {Isaac} + + +// if (flag==TRUE), then use the contents of randrsl[] to initialize mm[]. +PROCEDURE mix(VAR a,b,c,d,e,f,g,h: CARDINAL); +BEGIN + a := a xor b shl 11; d:=d+a; b:=b+c; + b := b xor c shr 2; e:=e+b; c:=c+d; + c := c xor d shl 8; f:=f+c; d:=d+e; + d := d xor e shr 16; g:=g+d; e:=e+f; + e := e xor f shl 10; h:=h+e; f:=f+g; + f := f xor g shr 4; a:=a+f; g:=g+h; + g := g xor h shl 8; b:=b+g; h:=h+a; + h := h xor a shr 9; c:=c+h; a:=a+b; +END; {mix} + + +PROCEDURE iRandInit(flag: BOOLEAN); +VAR i,a,b,c,d,e,f,g,h: CARDINAL; +BEGIN + aa:=0; bb:=0; cc:=0; + a:=$9e3779b9; // the golden ratio + + b:=a; c:=a; d:=a; e:=a; f:=a; g:=a; h:=a; + + FOR i := 0 TO 3 DO // scramble it + mix(a,b,c,d,e,f,g,h); + + i:=0; + REPEAT // fill in mm[] with messy stuff + IF flag THEN BEGIN // use all the information in the seed + a:=a+randrsl[i ]; b:=b+randrsl[i+1]; c:=c+randrsl[i+2]; d:=d+randrsl[i+3]; + e:=e+randrsl[i+4]; f:=f+randrsl[i+5]; g:=g+randrsl[i+6]; h:=h+randrsl[i+7]; + END; + + mix(a,b,c,d,e,f,g,h); + mm[i ]:=a; mm[i+1]:=b; mm[i+2]:=c; mm[i+3]:=d; + mm[i+4]:=e; mm[i+5]:=f; mm[i+6]:=g; mm[i+7]:=h; + i:=i+8; + UNTIL i>255; + + IF (flag) THEN BEGIN + // do a second pass to make all of the seed affect all of mm + i:=0; + REPEAT + a:=a+mm[i ]; b:=b+mm[i+1]; c:=c+mm[i+2]; d:=d+mm[i+3]; + e:=e+mm[i+4]; f:=f+mm[i+5]; g:=g+mm[i+6]; h:=h+mm[i+7]; + mix(a,b,c,d,e,f,g,h); + mm[i ]:=a; mm[i+1]:=b; mm[i+2]:=c; mm[i+3]:=d; + mm[i+4]:=e; mm[i+5]:=f; mm[i+6]:=g; mm[i+7]:=h; + i:=i+8; + UNTIL i>255; + END; + isaac(); // fill in the first set of results + randcnt:=0; // prepare to use the first set of results +END; {randinit} + + +{ Seed ISAAC with a given string. + The string can be any size. The first 256 values will be used.} +PROCEDURE iSeed(seed: STRING; flag: BOOLEAN); +VAR i,m: CARDINAL; +BEGIN + FOR i:= 0 TO 255 DO mm[i]:=0; + m := Length(seed)-1; + FOR i:= 0 TO 255 DO BEGIN + // in case seed has less than 256 elements + IF i>m THEN randrsl[i]:=0 + // Pascal strings are 1-based + ELSE randrsl[i]:=ord(seed[i+1]); + END; + // initialize ISAAC with seed + iRandInit(flag); +END; {iSeed} + + +{ Get a random 32-bit value 0..MAXINT } +FUNCTION iRandom : Cardinal; +BEGIN + result := randrsl[randcnt]; + inc(randcnt); + IF (randcnt >255) THEN BEGIN + Isaac(); + randcnt := 0; + END; +END; {iRandom} + + +{ Get a random character in printable ASCII range } +FUNCTION iRandA: BYTE; + BEGIN + result := iRandom mod 95 + 32; + END; + + +{ convert an ASCII string to a hexadecimal string } +FUNCTION ascii2hex(s: STRING): STRING; + VAR i,l: CARDINAL; + BEGIN + result := ''; + l := Length(s); + FOR i := 1 TO l DO + result := result + IntToHex(ord(s[i]),2); + END; + + +{ XOR encrypt on random stream. Output: string of hex chars } +FUNCTION Vernam(msg: STRING): STRING; + VAR i: CARDINAL; + BEGIN + result := ''; + FOR i := 1 to length(msg) DO + result := result + chr(iRandA xor ord(msg[i])); + result := ascii2hex(result); + END; + + +{ Get position of the letter in chosen alphabet } +FUNCTION letternum(letter, start: CHAR): byte; + BEGIN + result := (ord(letter)-ord(start)); + END; + + +{ Caesar-shift a character places: Generalized Vigenere } +FUNCTION Caesar(ch: CHAR; shift, modulo: INTEGER; start: CHAR): CHAR; + VAR n: INTEGER; + BEGIN + n := letternum(ch,start) + shift; + n := n MOD modulo; + result := chr(ord(start)+n); + END; + +{ Vigenere mod 95 encryption. Output: string of hex chars } +FUNCTION Vigenere(msg: STRING): STRING; + VAR i: CARDINAL; + BEGIN + result := ''; + FOR i := 1 to length(msg) DO + result := result + Caesar(msg[i],iRandA,95,' '); + result := ascii2hex(result); + END; + + +BEGIN + // 1) seed ISAAC with the key + iSeed(key,true); + // 2) Vernam XOR encryption + xctx := Vernam(msg); + // 3) MOD encryption + mctx := Vigenere(msg); + // program output + Writeln('Message: ',msg); + Writeln('Key : ',key); + Writeln('XOR : ',xctx); + Writeln('MOD : ',mctx); +END. diff --git a/Task/The-ISAAC-Cipher/Go/the-isaac-cipher.go b/Task/The-ISAAC-Cipher/Go/the-isaac-cipher.go new file mode 100644 index 0000000000..639cebcb81 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Go/the-isaac-cipher.go @@ -0,0 +1,119 @@ +package main + +import "fmt" + +const ( + msg = "a Top Secret secret" + key = "this is my secret key" +) + +func main() { + var z state + z.seed(key) + fmt.Println("Message: ", msg) + fmt.Println("Key : ", key) + fmt.Println("XOR : ", z.vernam(msg)) +} + +type state struct { + aa, bb, cc uint32 + mm [256]uint32 + randrsl [256]uint32 + randcnt int +} + +func (z *state) isaac() { + z.cc++ + z.bb += z.cc + for i, x := range z.mm { + switch i % 4 { + case 0: + z.aa = z.aa ^ z.aa<<13 + case 1: + z.aa = z.aa ^ z.aa>>6 + case 2: + z.aa = z.aa ^ z.aa<<2 + case 3: + z.aa = z.aa ^ z.aa>>16 + } + z.aa += z.mm[(i+128)%256] + y := z.mm[x>>2%256] + z.aa + z.bb + z.mm[i] = y + z.bb = z.mm[y>>10%256] + x + z.randrsl[i] = z.bb + } +} + +func (z *state) randInit() { + const gold = uint32(0x9e3779b9) + a := [8]uint32{gold, gold, gold, gold, gold, gold, gold, gold} + mix1 := func(i int, v uint32) { + a[i] ^= v + a[(i+3)%8] += a[i] + a[(i+1)%8] += a[(i+2)%8] + } + mix := func() { + mix1(0, a[1]<<11) + mix1(1, a[2]>>2) + mix1(2, a[3]<<8) + mix1(3, a[4]>>16) + mix1(4, a[5]<<10) + mix1(5, a[6]>>4) + mix1(6, a[7]<<8) + mix1(7, a[0]>>9) + } + for i := 0; i < 4; i++ { + mix() + } + for i := 0; i < 256; i += 8 { + for j, rj := range z.randrsl[i : i+8] { + a[j] += rj + } + mix() + for j, aj := range a { + z.mm[i+j] = aj + } + } + for i := 0; i < 256; i += 8 { + for j, mj := range z.mm[i : i+8] { + a[j] += mj + } + mix() + for j, aj := range a { + z.mm[i+j] = aj + } + } + z.isaac() +} + +func (z *state) seed(seed string) { + for i, r := range seed { + if i == 256 { + break + } + z.randrsl[i] = uint32(r) + } + z.randInit() +} + +func (z *state) random() (r uint32) { + r = z.randrsl[z.randcnt] + z.randcnt++ + if z.randcnt == 256 { + z.isaac() + z.randcnt = 0 + } + return +} + +func (z *state) randA() byte { + return byte(z.random()%95 + 32) +} + +func (z *state) vernam(msg string) string { + b := []byte(msg) + for i := range b { + b[i] ^= z.randA() + } + return fmt.Sprintf("%X", b) +} diff --git a/Task/The-ISAAC-Cipher/Haskell/the-isaac-cipher.hs b/Task/The-ISAAC-Cipher/Haskell/the-isaac-cipher.hs new file mode 100644 index 0000000000..fb8d429a13 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Haskell/the-isaac-cipher.hs @@ -0,0 +1,127 @@ +import Data.Array +import Data.Bits +import Data.Char +import Data.Word +import Data.List +import Numeric + +type IArray = Array Word32 Word32 + +data IsaacState = IState + { randrsl :: IArray + , randcnt :: Word32 + , mm :: IArray + , aa :: Word32 + , bb :: Word32 + , cc :: Word32 + } + +instance Show IsaacState where + show (IState _ cnt _ a b c) = show cnt ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c + +toHex :: Char -> String +toHex c = showHex (fromEnum c) "" + +hexify :: String -> String +hexify = map toUpper . concatMap toHex + +toNum :: Char -> Word32 +toNum = fromIntegral . fromEnum + +toChar :: Word32 -> Char +toChar = toEnum . fromIntegral + +golden :: Word32 +golden = 0x9e3779b9 + +-- Mix up an ordering of words. +mix :: [Word32] -> [Word32] +mix set = foldl aux set [11, -2, 8, -16, 10, -4, 8, -9] + where + aux [a,b,c,d,e,f,g,h] x = [b + c, c, d + a', e, f, g, h, a'] + where a' = a `xor` (b `shift` x) + +-- Generate the next 256 words. +isaac :: IsaacState -> IsaacState +isaac (IState rsl _ m a b c) = IState rsl' 0 m' a' b' c' + where + c' = c + 1 + (rsl', m', a', b') = foldl aux (rsl, m, a, b) $ zip [0..255] $ cycle [13, -6, 2, -16] + aux (rsl, m, a, b) (i, s) = (rsl', m', a', b') + where x = m ! i + a' = (a `xor` (a `shift` s)) + m ! ((i + 128) `mod` 256) + y = a' + b + m ! ((x `shift` (-2)) `mod` 256) + m' = m // [(i,y)] + b' = x + m' ! ((y `shift` (-10)) `mod` 256) + rsl' = rsl // [(i,b')] + +-- Given a seed value in randrsl, initialize/mixup the state. +randinit :: IsaacState -> Bool -> IsaacState +randinit state flag = isaac (IState randrsl' 0 m 0 0 0) + where + firstSet = (iterate mix $ replicate 8 golden) !! 4 + iter _ _ [] = [] + iter flag set rsl = + let (rslH, rslT) = splitAt 8 rsl + set' = mix $ if flag + then zipWith (+) set rslH + else set + in set' ++ iter flag set' rslT + randrsl' = randrsl state + firstPass = iter flag firstSet $ elems randrsl' + set' = drop (256 - 8) firstPass + secondPass = if flag + then iter True set' firstPass + else firstPass + m = array (0, 255) $ zip [0..] secondPass + +-- Given a string seed, optionaly use it to generate a new state. +seed :: String -> Bool -> IsaacState +seed key flag = + let m = array (0, 255) $ zip [0..255] $ repeat 0 + rsl = m // zip [0..] (map toNum key) + state = IState rsl 0 m 0 0 0 + in randinit state flag + +-- Produce a random word and the next state from the given state. +random :: IsaacState -> (Word32, IsaacState) +random state@(IState rsl cnt m a b c) = + let r = rsl ! cnt + state' = if cnt + 1 > 255 + then isaac $ IState rsl 0 m a b c + else IState rsl (cnt + 1) m a b c + in (r, state') + +-- Produce a stream of random words from the given state. +randoms :: IsaacState -> [Word32] +randoms = unfoldr $ Just . random + +-- Produce a random printable/typable character in the ascii range +-- and the next state from the given state. +randA :: IsaacState -> (Char, IsaacState) +randA state = + let (r, state') = random state + in (toEnum $ fromIntegral $ (r `mod` 95) + 32, state') + +-- Produce a stream of printable characters from the given state. +randAs :: IsaacState -> String +randAs = unfoldr $ Just . randA + +-- Vernam encode/decode a string with the given state. +vernam :: IsaacState -> String -> String +vernam state msg = map toChar $ zipWith xor msg' randAs' + where + msg' = map toNum msg + randAs' = map toNum $ randAs state + +main :: IO () +main = do + let msg = "a Top Secret secret" + key = "this is my secret key" + st = seed key True + ver = vernam st msg + unver = vernam st ver + putStrLn $ "Message: " ++ msg + putStrLn $ "Key : " ++ key + putStrLn $ "XOR : " ++ hexify ver + putStrLn $ "XOR dcr: " ++ unver diff --git a/Task/The-ISAAC-Cipher/Haxe/the-isaac-cipher.haxe b/Task/The-ISAAC-Cipher/Haxe/the-isaac-cipher.haxe new file mode 100644 index 0000000000..87d78283ff --- /dev/null +++ b/Task/The-ISAAC-Cipher/Haxe/the-isaac-cipher.haxe @@ -0,0 +1,161 @@ +package src ; +import haxe.Int32; +import haxe.macro.Expr; +import haxe.ds.Vector; + +typedef Ub4 = Int32; + +enum Ciphermode { + mEncipher; + mDecipher; + mNone; +} + +class Isaac +{ + public var randrsl = new Vector(256); + public var randcnt:Ub4; + + var mm = new Vector(256); + var aa:Ub4 = 0; + var bb:Ub4 = 0; + var cc:Ub4 = 0; + + public function isaac():Void { + var x, y; + cc++; + bb += cc; + for (i in 0...256) { + x = mm[i]; + aa ^= switch (i % 4) {//Haxe unification + case 0: aa << 13; + case 1: aa >>> 6; + case 2: aa << 2; + case 3: aa >>> 16; + default: 0;//never happens + } + aa = mm[(i + 128) % 256] + aa; + mm[i] = y = mm[(x >>> 2) % 256] + aa + bb; + randrsl[i] = bb = mm[(y >>> 10) % 256] + x; + } + } + + macro static function mix(a:ExprOf, b:ExprOf, c:ExprOf, d:ExprOf, + e:ExprOf, f:ExprOf, g:ExprOf, h:ExprOf) { + return macro { + $a ^= $b << 11; $d += $a; $b += $c; + $b ^= $c >>> 2; $e += $b; $c += $d; + $c ^= $d << 8; $f += $c; $d += $e; + $d ^= $e >>> 16; $g += $d; $e += $f; + $e ^= $f << 10; $h += $e; $f += $g; + $f ^= $g >>> 4; $a += $f; $g += $h; + $g ^= $h << 8; $b += $g; $h += $a; + $h ^= $a >>> 9; $c += $h; $a += $b; + }; + } + + public function randinit(flag:Bool):Void { + var a, b, c, d, e, f, g, h, i; + aa = bb = cc = (0:Ub4); + a = b = c = d = e = f = g = h = (0x9e3779b9:Ub4); /* the golden ratio */ + for (i in 0...4) mix(a, b, c, d, e, f, g, h); /* scramble it */ + i = 0; + while (i < 256) { /* fill in mm[] with messy stuff */ + if (flag) { /* use all the information in the seed */ + a += randrsl[i]; b += randrsl[i + 1]; + c += randrsl[i + 2]; d += randrsl[i + 3]; + e += randrsl[i + 4]; f += randrsl[i + 5]; + g += randrsl[i + 6]; h += randrsl[i + 7]; + } + mix(a, b, c, d, e, f, g, h); + mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d; + mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h; + i += 8; + } + if (flag) { /* do a second pass to make all of the seed affect all of mm */ + i = 0; + while (i<256) { + a += mm[i]; b += mm[i + 1]; c += mm[i + 2]; d += mm[i + 3]; + e += mm[i + 4]; f += mm[i + 5]; g += mm[i + 6]; h += mm[i + 7]; + mix(a, b, c, d, e, f, g, h); + mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d; + mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h; + i += 8; + } + } + isaac(); + randcnt = 0; + } + + public function iRandom():Ub4 { + var r = randrsl[randcnt]; + ++randcnt; + if (randcnt > 255) { + isaac(); + randcnt = 0; + } + return r; + } + + public function iRandA():Int32 { + return cast(cast(iRandom(),UInt) % 95 + 32,Int32); + } + + public function iSeed(seed:String, flag:Bool):Void { + var m=seed.length-1; + for (i in 0...256) mm[i] = 0; + for (i in 0...256) if (i > m) randrsl[i] = 0; else randrsl[i] = seed.charCodeAt(i); + randinit(flag); + } + + inline static var modC = 95; + inline static var startC = 32; + + public function vernam (msg:String):String { + var v=""; + for (i in 0...msg.length) v += String.fromCharCode(iRandA() ^ msg.charCodeAt(i)); + return v; + } + + public function caesar(m:Ciphermode, ch:Int32, shift:Int32, + modulo:Int32, start:Int32):String { + var n:Int32; + if (m == mDecipher) n = ch - start - cast(shift,Int32); + else n = ch - start + cast(shift,Int32); + n %= modulo; + if (n < 0) n += modulo; + return String.fromCharCode(start + cast(n,Ub4)); + } + + public function caesarStr(m:Ciphermode, msg:String, modulo:Int32, start:Int32):String { + var c = ""; + for (i in 0...msg.length) + c += caesar(m,msg.charCodeAt(i),iRandA(),modulo,start); + return c; + } + + static public function main():Void { + var msg = "a Top Secret secret"; + var key = "this is my secret key"; + var cIsaac = new Isaac(); + var vctx, vptx, cctx, cptx; + cIsaac.iSeed(key, true); + vctx = cIsaac.vernam(msg); + cctx = cIsaac.caesarStr(mEncipher, msg, modC, startC); + + cIsaac.iSeed(key, true); + vptx = cIsaac.vernam(vctx); + cptx = cIsaac.caesarStr(mDecipher, cctx, modC, startC); + + Sys.println("Message: " + msg); + Sys.println("Key : " + key); + var hex = ""; + for (i in 0...vctx.length) hex += StringTools.hex(vctx.charCodeAt(i), 2); + Sys.println("XOR : " + hex); + Sys.println("XOR dcr: " + vptx); + hex = ""; + for (i in 0...cctx.length) hex += StringTools.hex(cctx.charCodeAt(i), 2); + Sys.println("MOD : " + hex); + Sys.println("MOD dcr: " + cptx); + } +} diff --git a/Task/The-ISAAC-Cipher/Java/the-isaac-cipher.java b/Task/The-ISAAC-Cipher/Java/the-isaac-cipher.java new file mode 100644 index 0000000000..859c14be6a --- /dev/null +++ b/Task/The-ISAAC-Cipher/Java/the-isaac-cipher.java @@ -0,0 +1,225 @@ +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.Random; + + +public class IsaacRandom extends Random { + + private static final long serialVersionUID = 1L; + + private final int[] randResult = new int[256]; // output of last generation + private int valuesUsed; // the number of values already used up from randResult + + // internal generator state + private final int[] mm = new int[256]; + private int aa, bb, cc; + + public IsaacRandom() { + super(0); + init(null); + } + + public IsaacRandom(int[] seed) { + super(0); + setSeed(seed); + } + + public IsaacRandom(String seed) { + super(0); + setSeed(seed); + } + + private void generateMoreResults() { + cc++; + bb += cc; + + for (int i=0; i<256; i++) { + int x = mm[i]; + switch (i&3) { + case 0: + aa = aa^(aa<<13); + break; + case 1: + aa = aa^(aa>>>6); + break; + case 2: + aa = aa^(aa<<2); + break; + case 3: + aa = aa^(aa>>>16); + break; + } + aa = mm[i^128] + aa; + int y = mm[i] = mm[(x>>>2) & 0xFF] + aa + bb; + randResult[i] = bb = mm[(y>>>10) & 0xFF] + x; + } + + valuesUsed = 0; + } + + private static void mix(int[] s) { + s[0]^=s[1]<<11; s[3]+=s[0]; s[1]+=s[2]; + s[1]^=s[2]>>>2; s[4]+=s[1]; s[2]+=s[3]; + s[2]^=s[3]<<8; s[5]+=s[2]; s[3]+=s[4]; + s[3]^=s[4]>>>16; s[6]+=s[3]; s[4]+=s[5]; + s[4]^=s[5]<<10; s[7]+=s[4]; s[5]+=s[6]; + s[5]^=s[6]>>>4; s[0]+=s[5]; s[6]+=s[7]; + s[6]^=s[7]<<8; s[1]+=s[6]; s[7]+=s[0]; + s[7]^=s[0]>>>9; s[2]+=s[7]; s[0]+=s[1]; + } + + private void init(int[] seed) { + if (seed != null && seed.length != 256) { + seed = Arrays.copyOf(seed, 256); + } + aa = bb = cc = 0; + int[] initState = new int[8]; + Arrays.fill(initState, 0x9e3779b9); // the golden ratio + + for (int i=0; i<4; i++) { + mix(initState); + } + + for (int i=0; i<256; i+=8) { + if (seed != null) { + for (int j=0; j<8; j++) { + initState[j] += seed[i+j]; + } + } + mix(initState); + for (int j=0; j<8; j++) { + mm[i+j] = initState[j]; + } + } + + if (seed != null) { + for (int i=0; i<256; i+=8) { + for (int j=0; j<8; j++) { + initState[j] += mm[i+j]; + } + + mix(initState); + + for (int j=0; j<8; j++) { + mm[i+j] = initState[j]; + } + } + } + + valuesUsed = 256; // Make sure generateMoreResults() will be called by the next next() call. + } + + @Override + protected int next(int bits) { + if (valuesUsed == 256) { + generateMoreResults(); + assert(valuesUsed == 0); + } + int value = randResult[valuesUsed]; + valuesUsed++; + return value >>> (32-bits); + } + + @Override + public synchronized void setSeed(long seed) { + super.setSeed(0); + if (mm == null) { + // We're being called from the superclass constructor. We don't have our + // state arrays instantiated yet, and we're going to do proper initialization + // later in our own constructor anyway, so just ignore this call. + return; + } + int[] arraySeed = new int[256]; + arraySeed[0] = (int) (seed & 0xFFFFFFFF); + arraySeed[1] = (int) (seed >>> 32); + init(arraySeed); + } + + public synchronized void setSeed(int[] seed) { + super.setSeed(0); + init(seed); + } + + public synchronized void setSeed(String seed) { + super.setSeed(0); + char[] charSeed = seed.toCharArray(); + int[] intSeed = new int[charSeed.length]; + for (int i=0; i255; + + IF (flag) THEN BEGIN + // do a second pass to make all of the seed affect all of mm + i:=0; + REPEAT + a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3]; + e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7]; + mix(a,b,c,d,e,f,g,h); + mm[i ]:=a; mm[i+1]:=b; mm[i+2]:=c; mm[i+3]:=d; + mm[i+4]:=e; mm[i+5]:=f; mm[i+6]:=g; mm[i+7]:=h; + i+=8; + UNTIL i>255; + END; + isaac(); // fill in the first set of results + randcnt:=0; // prepare to use the first set of results +END; {randinit} + + +{ Seed ISAAC with a given string. + The string can be any size. The first 256 values will be used.} +PROCEDURE iSeed(seed: STRING; flag: BOOLEAN); +VAR i,m: CARDINAL; +BEGIN + FOR i:= 0 TO 255 DO mm[i]:=0; + m := Length(seed)-1; + FOR i:= 0 TO 255 DO BEGIN + // in case seed has less than 256 elements + IF i>m THEN randrsl[i]:=0 + // Pascal strings are 1-based + ELSE randrsl[i]:=ord(seed[i+1]); + END; + // initialize ISAAC with seed + iRandInit(flag); +END; {iSeed} + + +{ Get a random 32-bit value 0..MAXINT } +FUNCTION iRandom : Cardinal; +BEGIN + iRandom := randrsl[randcnt]; + inc(randcnt); + IF (randcnt >255) THEN BEGIN + Isaac(); + randcnt := 0; + END; +END; {iRandom} + + +{ Get a random character in printable ASCII range } +FUNCTION iRandA: BYTE; + BEGIN + iRandA := iRandom mod 95 + 32; + END; + + +{ convert an ASCII string to a hexadecimal string } +FUNCTION ascii2hex(s: STRING): STRING; + VAR i,l: CARDINAL; + BEGIN + ascii2hex := ''; + l := Length(s); + FOR i := 1 TO l DO + ascii2hex += Dec2Numb(ord(s[i]),2,16); + END; + + +{ XOR encrypt on random stream. Output: ASCII string } +FUNCTION Vernam(msg: STRING): STRING; + VAR i: CARDINAL; + BEGIN + Vernam := ''; + FOR i := 1 to length(msg) DO + Vernam += chr(iRandA xor ord(msg[i])); + END; + + +{ Get position of the letter in chosen alphabet } +FUNCTION letternum(letter, start: CHAR): byte; + BEGIN + letternum := (ord(letter)-ord(start)); + END; + + +{ Caesar-shift a character places: Generalized Vigenere } +FUNCTION Caesar(m: iMode; ch: CHAR; shift, modulo: INTEGER; start: CHAR): CHAR; + VAR n: INTEGER; + BEGIN + IF m = iDecrypt THEN shift := -shift; + n := letternum(ch,start) + shift; + n := n MOD modulo; + IF n<0 THEN n += modulo; + Caesar := chr(ord(start)+n); + END; + + +{ Vigenere mod 95 encryption & decryption. Output: ASCII string } +FUNCTION Vigenere(msg: STRING; m: iMode): STRING; + VAR i: CARDINAL; + BEGIN + Vigenere := ''; + FOR i := 1 to length(msg) DO + Vigenere += Caesar(m,msg[i],iRandA,95,' '); + END; + + +BEGIN + // 1) seed ISAAC with the key + iSeed(key,true); + // 2) Encryption + mode := iEncrypt; + // a) XOR (Vernam) + xctx := Vernam(msg); + // b) MOD (Vigenere) + mctx := Vigenere(msg,mode); + // 3) Decryption + mode := iDecrypt; + iSeed(key,true); + // a) XOR (Vernam) + xptx:= Vernam(xctx); + // b) MOD (Vigenere) + mptx:=Vigenere(mctx,mode); + // program output + Writeln('Message: ',msg); + Writeln('Key : ',key); + Writeln('XOR : ',ascii2hex(xctx)); + Writeln('MOD : ',ascii2hex(mctx)); + Writeln('XOR dcr: ',xptx); + Writeln('MOD dcr: ',mptx); +END. diff --git a/Task/The-ISAAC-Cipher/Perl/the-isaac-cipher.pl b/Task/The-ISAAC-Cipher/Perl/the-isaac-cipher.pl new file mode 100644 index 0000000000..a052efd6e2 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Perl/the-isaac-cipher.pl @@ -0,0 +1,31 @@ +use warnings; +use strict; +use Math::Random::ISAAC; + +my $message = "a Top Secret secret"; +my $key = "this is my secret key"; + +my $enc = xor_isaac($key, $message); +my $dec = xor_isaac($key, join "", pack "H*", $enc); + +print "Message: $message\n"; +print "Key : $key\n"; +print "XOR : $enc\n"; +print "XOR dcr: ", join("", pack "H*", $dec), "\n"; + +sub xor_isaac { + my($key, $msg) = @_; + + # Make an ISAAC stream with the desired seed + my $rng = Math::Random::ISAAC->new( map { ord } split "",$key ); + + # Get ISAAC output in the order the task wants + my @iranda = map { $_ % 95 + 32 } # Alpha-tize as the task desires + reverse # MRI gives state from the end + map { $rng->irand } # Get random inputs... + 0..255; # a state chunk at a time + # Encode: + join "", map { sprintf "%02X",$_ } # join hex digits + map { ord($_) ^ shift(@iranda) } # xor it with rand char + split "", $msg; # Take each character +} diff --git a/Task/The-ISAAC-Cipher/PicoLisp/the-isaac-cipher.l b/Task/The-ISAAC-Cipher/PicoLisp/the-isaac-cipher.l new file mode 100644 index 0000000000..01baf38a49 --- /dev/null +++ b/Task/The-ISAAC-Cipher/PicoLisp/the-isaac-cipher.l @@ -0,0 +1,105 @@ +(de add32 @ + (mod32 (pass +)) ) + +(de mod32 (N) + (& N `(hex "FFFFFFFF")) ) + +(de isaac() + (let (Y 0 S (-13 6 -2 16 .)) + (setq *CC (add32 *CC 1)) + (setq *BB (add32 *BB *CC)) + (for (I . X) *MM + (set (nth *MM I) + (setq Y + (add32 + (get *MM (inc (% (>> 2 X) 256))) + (setq *AA + (add32 + (x| *AA (>> (pop 'S) *AA)) + (get *MM (inc (% (+ 127 I) 256))) ) ) + *BB ) ) ) + (set (nth *RR I) + (setq *BB + (add32 + (get *MM (inc (% (>> 10 Y) 256))) + X ) ) ) ) ) ) + +(de mixA() + (let S (-11 2 -8 16 -10 4 -8 9 .) + (for I 8 + (set (nth *A I) + (mod32 + (x| + (get *A I) + (mod32 + (>> + (pop 'S) + (get *A (inc (% I 8))) ) ) ) ) ) + (set (nth *A (inc (% (+ 2 I) 8))) + (add32 + (get *A (inc (% (+ 2 I) 8))) + (get *A I) ) ) + (set (nth *A (inc (% I 8))) + (add32 + (get *A (inc (% I 8))) + (get *A (inc (% (inc I) 8))) ) ) ) ) ) + +(de iseed () + (do 4 + (mixA) ) + (for (I 1 (> 256 I) (inc 'I 8)) + (for (J I (> (+ 8 I) J) (inc J)) + (set (nth *A (inc (% (dec J) 8))) + (add32 + (get *A (inc (% (dec J) 8))) + (get *RR J) ) ) ) + (mixA) + (for (J I (> (+ 8 I) J) (inc J)) + (set (nth *MM J) + (get *A (inc (% (dec J) 8))) ) ) ) + (for (I 1 (> 256 I) (inc 'I 8)) + (for (J I (> (+ 8 I) J) (inc J)) + (set (nth *A (inc (% (dec J) 8))) + (add32 + (get *A (inc (% (dec J) 8))) + (get *MM J) ) ) ) + (mixA) + (for (J I (> (+ 8 I) J) (inc J)) + (set (nth *MM J) + (get *A (inc (% (dec J) 8))) ) ) ) + (isaac) ) + +(let + (*AA 0 + *BB 0 + *CC 0 + *MM (need 256 0) + *RC 0 + *RR (need + -256 + (mapcar + char + (head 256 (chop "this is my secret key")) ) 0 ) + *A (need 8 `(hex "9E3779B9")) ) + (iseed) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (make + (for I (mapcar char (chop "a Top Secret secret")) + (link + (x| + I + (+ + 32 + (% + (get + *RR + (if (>= 256 (inc '*RC)) + *RC + (isaac) + (one *RC) ) ) + 95 ) ) ) ) ) ) ) ) ) ) + +(bye) diff --git a/Task/The-ISAAC-Cipher/Python/the-isaac-cipher.py b/Task/The-ISAAC-Cipher/Python/the-isaac-cipher.py new file mode 100644 index 0000000000..846159957b --- /dev/null +++ b/Task/The-ISAAC-Cipher/Python/the-isaac-cipher.py @@ -0,0 +1,196 @@ +import random +import collections + +INT_MASK = 0xFFFFFFFF # we use this to emulate 32-bit overflow semantics by masking off higher bits after operations + +class IsaacRandom(random.Random): + """ + Random number generator using the ISAAC algorithm. + """ + + def seed(self, seed=None): + """ + Initialize internal state. + + The seed, if given, can be a string, an integer, or an iterable that contains + integers only. If no seed is given, a fixed default state is set up; unlike + our superclass, this class will not attempt to randomize the seed from outside sources. + """ + def mix(): + init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_state[1] &= INT_MASK + init_state[1] ^= (init_state[2]>>2) ; init_state[4] += init_state[1]; init_state[4] &= INT_MASK; init_state[2] += init_state[3]; init_state[2] &= INT_MASK + init_state[2] ^= ((init_state[3]<<8 )&INT_MASK); init_state[5] += init_state[2]; init_state[5] &= INT_MASK; init_state[3] += init_state[4]; init_state[3] &= INT_MASK + init_state[3] ^= (init_state[4]>>16) ; init_state[6] += init_state[3]; init_state[6] &= INT_MASK; init_state[4] += init_state[5]; init_state[4] &= INT_MASK + init_state[4] ^= ((init_state[5]<<10)&INT_MASK); init_state[7] += init_state[4]; init_state[7] &= INT_MASK; init_state[5] += init_state[6]; init_state[5] &= INT_MASK + init_state[5] ^= (init_state[6]>>4 ) ; init_state[0] += init_state[5]; init_state[0] &= INT_MASK; init_state[6] += init_state[7]; init_state[6] &= INT_MASK + init_state[6] ^= ((init_state[7]<<8 )&INT_MASK); init_state[1] += init_state[6]; init_state[1] &= INT_MASK; init_state[7] += init_state[0]; init_state[7] &= INT_MASK + init_state[7] ^= (init_state[0]>>9 ) ; init_state[2] += init_state[7]; init_state[2] &= INT_MASK; init_state[0] += init_state[1]; init_state[0] &= INT_MASK + + super().seed(0) # give a chance for the superclass to reset its state - the actual seed given to it doesn't matter + if seed is not None: + if isinstance(seed, str): + seed = [ord(x) for x in seed] + elif isinstance(seed, collections.Iterable): + seed = [x & INT_MASK for x in seed] + elif isinstance(seed, int): + val = abs(seed) + seed = [] + while val: + seed.append(val & INT_MASK) + val >>= 32 + else: + raise TypeError('Seed must be string, integer or iterable of integer') + + # make sure the seed list is exactly 256 elements long + if len(seed)>256: + del seed[256:] + elif len(seed)<256: + seed.extend([0]*(256-len(seed))) + + self.aa = self.bb = self.cc = 0 + self.mm = [] + init_state = [0x9e3779b9]*8 + + for _ in range(4): + mix() + + for i in range(0, 256, 8): + if seed is not None: + for j in range(8): + init_state[j] += seed[i+j] + init_state[j] &= INT_MASK + mix() + self.mm += init_state + + if seed is not None: + for i in range(0, 256, 8): + for j in range(8): + init_state[j] += self.mm[i+j] + init_state[j] &= INT_MASK + mix() + for j in range(8): + self.mm[i+j] = init_state[j] + + self.rand_count = 256 + self.rand_result = [0]*256 + + def getstate(self): + return super().getstate(), self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result + + def setstate(self, state): + super().setstate(state[0]) + _, self.aa, self.bb, self.cc, self.mm, self.rand_count, self.rand_result = state + + def _generate(self): + # Generate 256 random 32-bit values and save them in an internal field. + # The actual random functions will dish out these values to callers. + self.cc = (self.cc + 1) & INT_MASK + self.bb = (self.bb + self.cc) & INT_MASK + + for i in range(256): + x = self.mm[i] + mod = i & 3 + if mod==0: + self.aa ^= ((self.aa << 13) & INT_MASK) + elif mod==1: + self.aa ^= (self.aa >> 6) + elif mod==2: + self.aa ^= ((self.aa << 2) & INT_MASK) + else: # mod == 3 + self.aa ^= (self.aa >> 16) + self.aa = (self.mm[i^128] + self.aa) & INT_MASK + y = self.mm[i] = (self.mm[(x>>2) & 0xFF] + self.aa + self.bb) & INT_MASK + self.rand_result[i] = self.bb = (self.mm[(y>>10) & 0xFF] + x) & INT_MASK + + self.rand_count = 0 + + def next_int(self): + """Return a random integer between 0 (inclusive) and 2**32 (exclusive).""" + if self.rand_count == 256: + self._generate() + result = self.rand_result[self.rand_count] + self.rand_count += 1 + return result + + def getrandbits(self, k): + """Return a random integer between 0 (inclusive) and 2**k (exclusive).""" + result = 0 + ints_needed = (k+31)//32 + ints_used = 0 + while ints_used < ints_needed: + if self.rand_count == 256: + self._generate() + ints_to_take = min(256-self.rand_count, ints_needed) + for val in self.rand_result[self.rand_count : self.rand_count+ints_to_take]: + result = (result << 32) | val + self.rand_count += ints_to_take + ints_used += ints_to_take + result &= ((1<255 /* fill in mm[] with messy stuff */ + IF flag THEN Do /* use all the information in the seed */ + Call setix + a=add(a,randrsl.i); b=add(b,randrsl.i1) + c=add(c,randrsl.i2); d=add(d,randrsl.i3) + e=add(e,randrsl.i4); f=add(f,randrsl.i5) + g=add(g,randrsl.i6); h=add(h,randrsl.i7) + End + Call mix + mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d + mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h + i=i+8 + End + + IF flag THEN Do /* do a second pass to make all of the seed affect all of mm */ + i=0 + do until i>255 /* fill in mm[] with messy stuff */ + Call setix + a=add(a,mm.i); b=add(b,mm.i1); c=add(c,mm.i2); d=add(d,mm.i3) + e=add(e,mm.i4); f=add(f,mm.i5); g=add(g,mm.i6); h=add(h,mm.i7) + Call mix + mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d + mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h + i=i+8 + End + End + Call isaac /* fill in the first set of results */ + randcnt=0; /* prepare to use the first set of results */ + Return + +iseed: Procedure Expose aa bb cc randcnt randrsl. mm. +/*--------------------------------------------------------------------- +* Seed ISAAC with a given string. +* The string can be any size. The first 256 values will be used. +*--------------------------------------------------------------------*/ + Parse Arg seed,flag + mm.=0 + m=Length(seed)-1 + Do i=0 TO 255 + IF i>m THEN /* in case seed has less than 256 elements */ + randrsl.i=0 + ELSE + randrsl.i=c2d(substr(seed,i+1,1)) + end + Call iRandInit flag /* initialize ISAAC with seed */ + Return + +iRandom: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get a random 32-bit value 0..MAXINT */ + iRandom=randrsl.randcnt + randcnt=randcnt+1 + If randcnt>255 Then Do + Call isaac + randcnt=0 + End + Return irandom + +iRandA: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get a random character in printable ASCII range */ + iRandA=iRandom()//95+32 + Return iRandA + +xor: Procedure Expose aa bb cc randcnt randrsl. mm. + Parse Arg a,b + ac=d2c(a,4) + bc=d2c(b,4) + res=c2d(bitxor(ac,bc)) + return res//4294967296 + +Vernam: Procedure Expose aa bb cc randcnt randrsl. mm. +/* XOR encrypt on random stream. Output: string of hex chars */ + Parse Arg msg + Vernam='' + Do i=1 to length(msg) + Vernam=Vernam||d2c(xor(iRandA(),c2d(substr(msg,i,1)))) + End + Return Vernam + +letternum: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get position of the letter in chosen alphabet */ + Parse Arg letter,start + letternum=c2d(letter)-c2d(start) + Return letternum + +Caesar: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Caesar-shift a character places: Generalized Vigenere */ + Parse Arg m,ch,shift,modulo,start + IF m='iDecrypt' TheN shift=-shift + n=letternum(ch,start)+shift + n=n//modulo + IF n<0 Then n=n+modulo + Caesar=d2c(c2d(start)+n) + Return Caesar + +Vigenere: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Vigenere mod 95 encryption. Output: string of hex chars */ + Parse Arg msg,m + Vigenere='' + Do i=1 to length(msg) + Vigenere=Vigenere||Caesar(m,substr(msg,i,1),iRandA(),95,' ') + End + Return Vigenere + +shl: Procedure + res=arg(1)*(2**arg(2)) + return res//4294967296 + +shr: Procedure + res=arg(1)%(2**arg(2)) + return res//4294967296 + +setix: + i1=i+1 + i2=i+2 + i3=i+3 + i4=i+4 + i5=i+5 + i6=i+6 + i7=i+7 + Return + +add: Procedure +/* add argumemnts modulo 4294967296 */ + res=arg(1)+arg(2) + If arg(3)<>'' Then + res=res+arg(3) + return res//4294967296 diff --git a/Task/The-ISAAC-Cipher/REXX/the-isaac-cipher-2.rexx b/Task/The-ISAAC-Cipher/REXX/the-isaac-cipher-2.rexx new file mode 100644 index 0000000000..a0c2583dc1 --- /dev/null +++ b/Task/The-ISAAC-Cipher/REXX/the-isaac-cipher-2.rexx @@ -0,0 +1,239 @@ +/* REXX --------------------------------------------------------------- +* 25.07.2014 Walter Pachl framing version 1 for processing a file +*--------------------------------------------------------------------*/ +Parse Arg fid +select + When fid='' Then + fid='test_file.txt' + When fid='?' Then Do + Say 'rexx iscf file prompts you for a key,' + Say 'encrypts file into fn.enc' + Say 'and decrypts fn.enc into fn.dec' + Exit + End + Otherwise + Nop + End +Say 'Please enter a key' +Parse Pull key +enc=fn(fid)'.enc' ; 'erase' enc +dec=fn(fid)'.dec' ; 'erase' dec +Do While lines(fid)>0 + l=linein(fid) + Call lineout enc,iscx(l,key,'e') + End +Call lineout enc +Do While lines(enc)>0 + l=linein(enc) + Call lineout dec,iscx(l,key,'d') + End +Call lineout dec +Say 'original:' +'type' fid +Say 'encrypted:' +'type' enc +Say 'decrypted:' +'type' dec +Exit +iscx: Procedure +/* REXX --------------------------------------------------------------- +* 24.07.2014 Walter Pachl translated from Pascal +* extend with decoding +*--------------------------------------------------------------------*/ +Numeric Digits 32 +aa=0 +bb=0 +cc=0 +mm.=0 +randcnt=0 +randrsl.=0 +Parse Arg msg,key,mode + +Call iSeed key,1 /* 1) seed ISAAC with the key */ +If mode='e' Then + mode='iEncrypt' +Else + mode='iDecrypt' +mctx=Vigenere(msg,mode) /* 3) MOD encryption */ +Return mctx + +isaac: Procedure Expose mm. aa bb cc randrsl. randcnt + cc=add(cc,1) + bb=add(bb,cc) + Do i=0 To 255 + x=mm.i + im4=i//4 + Select + When im4=0 Then aa=xor(aa,shl(aa,13)) + When im4=1 Then aa=xor(aa,shr(aa, 6)) + When im4=2 Then aa=xor(aa,shl(aa, 2)) + When im4=3 Then aa=xor(aa,shr(aa,16)) + End + z=(i+128)//256 + aa=add(mm.z,aa) + z=shr(x,2)//256 + y=add(mm.z,aa,bb) + mm.i=y + z=shr(y,10)//256 + bb=add(mm.z,x) + randrsl.i=bb + End + randcnt=0 + Return + +mix: Procedure Expose a b c d e f g h mm. aa bb cc randrsl. randcnt + a=xor(a,shl(b,11)); d=add(d,a); b=add(b,c) + b=xor(b,shr(c, 2)); e=add(e,b); c=add(c,d) + c=xor(c,shl(d, 8)); f=add(f,c); d=add(d,e) + d=xor(d,shr(e,16)); g=add(g,d); e=add(e,f) + e=xor(e,shl(f,10)); h=add(h,e); f=add(f,g) + f=xor(f,shr(g, 4)); a=add(a,f); g=add(g,h) + g=xor(g,shl(h, 8)); b=add(b,g); h=add(h,a) + h=xor(h,shr(a, 9)); c=add(c,h); a=add(a,b) + Return + +iRandInit: Procedure Expose mm. randrsl. randcnt + Parse Arg flag + aa=0; bb=0; cc=0 + a= 2654435769 /* $9e3779b9; // the golden ratio */ + + b=a; c=a; d=a; e=a; f=a; g=a; h=a + + do i=0 TO 3 + Call mix + End + + i=0 + do until i>255 /* fill in mm[] with messy stuff */ + IF flag THEN Do /* use all the information in the seed */ + Call setix + a=add(a,randrsl.i); b=add(b,randrsl.i1) + c=add(c,randrsl.i2); d=add(d,randrsl.i3) + e=add(e,randrsl.i4); f=add(f,randrsl.i5) + g=add(g,randrsl.i6); h=add(h,randrsl.i7) + End + Call mix + mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d + mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h + i+=8 + End + + IF flag THEN Do /* do a second pass to make all of the seed affect all of mm */ + i=0 + do until i>255 /* fill in mm[] with messy stuff */ + Call setix + a=add(a,mm.i); b=add(b,mm.i1); c=add(c,mm.i2); d=add(d,mm.i3) + e=add(e,mm.i4); f=add(f,mm.i5); g=add(g,mm.i6); h=add(h,mm.i7) + Call mix + mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d + mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h + i+=8 + End + End + Call isaac /* fill in the first set of results */ + randcnt=0; /* prepare to use the first set of results */ + Return + +iseed: Procedure Expose aa bb cc randcnt randrsl. mm. +/*--------------------------------------------------------------------- +* Seed ISAAC with a given string. +* The string can be any size. The first 256 values will be used. +*--------------------------------------------------------------------*/ + Parse Arg seed,flag + mm.=0 + m=Length(seed)-1 + Do i=0 TO 255 + IF i>m THEN /* in case seed has less than 256 elements */ + randrsl.i=0 + ELSE + randrsl.i=c2d(substr(seed,i+1,1)) + end + Call iRandInit flag /* initialize ISAAC with seed */ + Return + +iRandom: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get a random 32-bit value 0..MAXINT */ + iRandom=randrsl.randcnt + randcnt=randcnt+1 + If randcnt>255 Then Do + Call isaac + randcnt=0 + End + Return irandom + +iRandA: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get a random character in printable ASCII range */ + iRandA=iRandom()//95+32 + Return iRandA + +xor: Procedure Expose aa bb cc randcnt randrsl. mm. + Parse Arg a,b + ac=d2c(a,4) + bc=d2c(b,4) + res=c2d(bitxor(ac,bc)) + return res//4294967296 + +Vernam: Procedure Expose aa bb cc randcnt randrsl. mm. +/* XOR encrypt on random stream. Output: string of hex chars */ + Parse Arg msg + Vernam='' + Do i=1 to length(msg) + Vernam=Vernam||d2c(xor(iRandA(),c2d(substr(msg,i,1)))) + End + Return Vernam + +letternum: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Get position of the letter in chosen alphabet */ + Parse Arg letter,start + letternum=c2d(letter)-c2d(start) + Return letternum + +Caesar: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Caesar-shift a character places: Generalized Vigenere */ + Parse Arg m,ch,shift,modulo,start + IF m='iDecrypt' TheN shift=-shift + n=letternum(ch,start)+shift + n=n//modulo + IF n<0 Then n=n+modulo + Caesar=d2c(c2d(start)+n) + Return Caesar + +Vigenere: Procedure Expose aa bb cc randcnt randrsl. mm. +/* Vigenere mod 95 encryption. Output: string of hex chars */ + Parse Arg msg,m + Vigenere='' + Do i=1 to length(msg) + Vigenere=Vigenere||Caesar(m,substr(msg,i,1),iRandA(),95,' ') + End + Return Vigenere + +shl: Procedure + res=arg(1)*(2**arg(2)) + return res//4294967296 + +shr: Procedure + res=arg(1)%(2**arg(2)) + return res//4294967296 + +setix: + i1=i+1 + i2=i+2 + i3=i+3 + i4=i+4 + i5=i+5 + i6=i+6 + i7=i+7 + Return + +add: Procedure +/* add argumemnts modulo 4294967296 */ + res=arg(1)+arg(2) + If arg(3)<>'' Then + res=res+arg(3) + return res//4294967296 + +fn: Procedure +/* REXX */ +parse Arg fid +Parse Var fid fn '.' ft +Return fn diff --git a/Task/The-ISAAC-Cipher/Racket/the-isaac-cipher.rkt b/Task/The-ISAAC-Cipher/Racket/the-isaac-cipher.rkt new file mode 100644 index 0000000000..ad02ef1f2a --- /dev/null +++ b/Task/The-ISAAC-Cipher/Racket/the-isaac-cipher.rkt @@ -0,0 +1,255 @@ +#lang racket +;; Imperative version: Translation of C +;; Vigenère: Translation of Pascal +(module+ test (require tests/eli-tester)) + +;; --------------------------------------------------------------------------------------------------- +;; standard.h: Standard definitions and types, Bob Jenkins +(define UB4MAXVAL #xffffffff) +(define-syntax-rule (bit target mask) (bitwise-and target mask)) +;; C-like operators +(define-syntax-rule (u4-truncate x) (bit x UB4MAXVAL)) +(define-syntax-rule (u4<< a b) (u4-truncate (arithmetic-shift a b))) +(define-syntax-rule (u4>> a b) (u4-truncate (arithmetic-shift a (- b)))) +(define-syntax-rule (_++ i) (let ((rv i)) (set! i (u4-truncate (add1 i))) rv)) +(define-syntax-rule (u4+= a b) (begin (set! a (u4-truncate (+ a b))) a)) +(define-syntax-rule (^= a b) (begin (set! a (u4-truncate (bitwise-xor a b))) a)) + +;; --------------------------------------------------------------------------------------------------- +;; rand.h: definitions for a random number generator +(define RANDSIZL 8) +(define RANDSIZ (u4<< 1 RANDSIZL)) +(define RANDSIZ-1 (sub1 RANDSIZ)) + +(struct randctx + (cnt + rsl ; RANDSIZ*4 bytes (makes u4's) + mem ; RANDSIZ*4 bytes (makes u4's) + a b c) #:mutable) + +(define (new-randctx) + (randctx 0 (make-bytes (* 4 RANDSIZ) 0) (make-bytes (* 4 RANDSIZ) 0) 0 0 0)) + +(define (bytes->hex-string B (start 0) (end #f) #:join (join "") #:show-bytes? (show-bytes? #f)) + (define hexes + (for/list ((b (in-bytes B start end))) + (~a (number->string b 16) #:width 2 #:align 'right #:pad-string "0"))) + (string-join + (append hexes (if show-bytes? + (list " \"" (bytes->string/utf-8 B #f start (or end (bytes-length B))) "\"") + null)) + join)) + +(define format-randctx + (match-lambda + [(randctx C (app bytes->hex-string R) (app bytes->hex-string M) a b c) + (format "randctx: cnt:~a~%rsl:~s~%mem:~s~%a:~a b:~a c:~a" C R M a b c)])) + +(define be? (system-big-endian?)) + +(define (bytes->u4 ary idx) + (integer-bytes->integer ary #f be? (* idx 4) (* (add1 idx) 4))) + +(define (u4->bytes! ary idx v) + (integer->integer-bytes (bit v UB4MAXVAL) 4 #f be? ary (* idx 4))) + +;; --------------------------------------------------------------------------------------------------- +;; rand.c: "By Bob Jenkins. My random number generator, ISAAC. Public Domain." +(define (ind mm x) + (define idx (bitwise-and x (u4<< RANDSIZ-1 2))) + (integer-bytes->integer mm #f be? idx (+ idx 4))) + +(define (isaac C) + (define M (randctx-mem C)) + (define R (randctx-rsl C)) + (define mm 0) + (define r 0) + (define-syntax-rule (rng-step mix) + (begin + (define x (bytes->u4 M m)) + (set! a (u4-truncate (+ (bitwise-xor a mix) (bytes->u4 M (_++ m2))))) + (define y (+ (ind M x) a b)) + (u4->bytes! M (_++ m) y) + (set! b (u4-truncate (+ (ind M (u4>> y RANDSIZL)) x))) + (u4->bytes! R (_++ r) b))) + + (define a (randctx-a C)) + + (set-randctx-c! C (add1 (randctx-c C))) + + (define b (u4-truncate (+ (randctx-b C) (randctx-c C)))) + + (define m mm) + (define m2 (+ m (/ RANDSIZ 2))) + (define mend m2) + + (define-syntax-rule (4-step-loop variant) + (let loop () + (when (< variant mend) + (rng-step (u4<< a 13)) (rng-step (u4>> a 6)) + (rng-step (u4<< a 2)) (rng-step (u4>> a 16)) + (loop)))) + + (4-step-loop m) + (set! m2 mm) + (4-step-loop m2) + + (set-randctx-b! C b) + (set-randctx-a! C a)) + +;; dot infix notation because I'm too lazy to move the operators left! +(define-syntax-rule (mix-line<< A B N D C) + (begin (A . ^= . (B . u4<< . N)) (D . u4+= . A) (B . u4+= . C))) +(define-syntax-rule (mix-line>> A B N D C) + (begin (A . ^= . (B . u4>> . N)) (D . u4+= . A) (B . u4+= . C))) + +(define-syntax-rule (mix a b c d e f g h) + (begin (mix-line<< a b 11 d c) (mix-line>> b c 2 e d) + (mix-line<< c d 8 f e) (mix-line>> d e 16 g f) + (mix-line<< e f 10 h g) (mix-line>> f g 4 a h) + (mix-line<< g h 8 b a) (mix-line>> h a 9 c b))) + +;; if (flag==TRUE), then use the contents of randrsl[] to initialize mm[]. +(define (rand-init C flag?) + (set-randctx-a! C 0) + (set-randctx-b! C 0) + (set-randctx-c! C 0) + + ;; seed-ctx should set these up (with the seed!): + ;; (set-ctx-rsl! C (make-bytes (* 4 RANDSIZ) 0)) + ;; (set-ctx-mem! C (make-bytes (* 4 RANDSIZ) 0)) + (define R (randctx-rsl C)) + (define M (randctx-mem C)) + + (define φ #x9e3779b9) ; the golden ratio + (match-define (list a b c d e f g h) (make-list 8 φ)) + + (for ((_ 4)) (mix a b c d e f g h)) ; scramble it + + (define-syntax-rule (mix-and-assign i M2) + (begin + (mix a b c d e f g h) + (u4->bytes! M2 (+ i 0) a) (u4->bytes! M2 (+ i 1) b) + (u4->bytes! M2 (+ i 2) c) (u4->bytes! M2 (+ i 3) d) + (u4->bytes! M2 (+ i 4) e) (u4->bytes! M2 (+ i 5) f) + (u4->bytes! M2 (+ i 6) g) (u4->bytes! M2 (+ i 7) h))) + + (define-syntax-rule (mix-with-mem M1 M2) + (for ((i (in-range 0 RANDSIZ 8))) + (a . u4+= . (bytes->u4 M1 (+ i 0))) (b . u4+= . (bytes->u4 M1 (+ i 1))) + (c . u4+= . (bytes->u4 M1 (+ i 2))) (d . u4+= . (bytes->u4 M1 (+ i 3))) + (e . u4+= . (bytes->u4 M1 (+ i 4))) (f . u4+= . (bytes->u4 M1 (+ i 5))) + (g . u4+= . (bytes->u4 M1 (+ i 6))) (h . u4+= . (bytes->u4 M1 (+ i 7))) + (mix-and-assign i M2))) + + (cond + [flag? ; initialize using the contents of r[] as the seed + (mix-with-mem R M) + (mix-with-mem M M)] ; do a second pass to make all of the seed affect all of m + [else ; fill in m[] with messy stuff + (for ((i (in-range 0 RANDSIZ 8))) (mix-and-assign i M))]) + + (isaac C) ; fill in the first set of results + (set-randctx-cnt! C 0)) ; prepare to use the first set of results + +(define (seed-ctx C key #:flag? (flag? #t)) + (bytes-fill! (randctx-mem C) 0) + (define R (randctx-rsl C)) + (bytes-fill! (randctx-rsl C) 0) + (for ((k (in-bytes key)) (i (in-range (quotient (bytes-length R) 4)))) (u4->bytes! R i k)) + (rand-init C flag?)) + +;; Get a random 32-bit value 0..MAXINT +(define (i-random C) + (define cnt (randctx-cnt C)) + (define r (bytes->u4 (randctx-rsl C) cnt)) + (define cnt+1 (add1 cnt)) + (cond [(>= cnt+1 RANDSIZ) (isaac C) (set-randctx-cnt! C 0)] + [else (set-randctx-cnt! C cnt+1)]) + r) + +;; Get a random character in printable ASCII range +(define ((i-rand-a C)) + (+ 32 (modulo (i-random C) 95))) + +(define (Vernham rnd-fn msg) + (define gsm (make-bytes (bytes-length msg))) + (for ((i (in-naturals)) (m (in-bytes msg))) + (define r (rnd-fn)) + (define b (bitwise-xor m r)) + (bytes-set! gsm i b)) + gsm) + +;; Get position of the letter in chosen alphabet +;; Caesar-shift a character places: Generalized Vigenere +(define ((Caesar mod-n start) encrypt? shift ch) + (define (letter-num letter/byte) + (- letter/byte (char->integer start))) + + (define shift-fn (if encrypt? + -)) + (+ (char->integer start) (modulo (shift-fn (letter-num ch) shift) mod-n))) + +;; Vigenère mod 95 encryption & decryption. Output: bytes +(define Vigenère-Caeser (Caesar 95 #\space)) +(define (Vigenère encrypt? rand-fn msg) + (list->bytes + (for/list ((b (in-bytes msg))) + (Vigenère-Caeser encrypt? (rand-fn) b)))) + +{module+ main + (define message #"a Top Secret secret") + (define key #"this is my secret key") + (define C (new-randctx)) + (seed-ctx C key) + (define vern.msg (Vernham (i-rand-a C) message)) + ;; Pascal doesn't reset the context betwen XOR and MOD + ;; (seed-ctx C key) + (define vigen.msg (Vigenère #t (i-rand-a C) message)) + (seed-ctx C key) + (define vern2.msg (Vernham (i-rand-a C) vern.msg)) + ;; Pascal doesn't reset the context betwen XOR and MOD + ;; (seed-ctx C key) + (define unvigen.msg (Vigenère #f (i-rand-a C) vigen.msg)) + ;; This is what MOD looks like from the context as seeded with key + (seed-ctx C key) + (define vigen-at-seed.msg (Vigenère #t (i-rand-a C) message)) + (seed-ctx C key) + (define unvigen-at-seed.msg (Vigenère #f (i-rand-a C) vigen-at-seed.msg)) + + (printf #<hex-string vern.msg) + (bytes->hex-string vigen.msg #:show-bytes? #t) + (bytes->hex-string vern2.msg #:show-bytes? #t) + (bytes->hex-string unvigen.msg #:show-bytes? #t) + (bytes->hex-string vigen-at-seed.msg #:show-bytes? #t) + (bytes->hex-string unvigen-at-seed.msg #:show-bytes? #t) + )} + +{module+ test + ;; "If the initial internal state is all zero, after ten calls the values of aa, bb, and cc in + ;; hexadecimal will be d4d3f473, 902c0691, and 0000000a." + (let () + (define C (new-randctx)) + (for ((_ 10)) (isaac C)) + (test (randctx-a C) => #xd4d3f473 + (randctx-b C) => #x902c0691 + (randctx-c C) => 10)) + } diff --git a/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-1.tcl b/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-1.tcl new file mode 100644 index 0000000000..56b59e188f --- /dev/null +++ b/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-1.tcl @@ -0,0 +1,110 @@ +package require Tcl 8.6 + +oo::class create ISAAC { + variable aa bb cc mm randrsl randcnt + + constructor {seed} { + namespace eval tcl { + namespace eval mathfunc { + proc mm {idx} { + upvar 1 mm list + lindex $list [expr {$idx % [llength $list]}] + } + proc clamp {value} { + expr {$value & 0xFFFFFFFF} + } + } + } + proc mix1 {i v} { + upvar 1 a a + lset a $i [expr {clamp([lindex $a $i] ^ $v)}] + lset a [set idx [expr {($i+3)%8}]] \ + [expr {clamp([lindex $a $idx] + [lindex $a $i])}] + lset a [set idx [expr {($i+1)%8}]] \ + [expr {clamp([lindex $a $idx] + [lindex $a [expr {($i+2)%8}]])}] + } + + binary scan $seed[string repeat \u0000 256] c256 randrsl + set mm [lrepeat 256 0] + set randcnt [set aa [set bb [set cc 0]]] + + set a [lrepeat 8 0x9e3779b9] + foreach i {1 2 3 4} { + mix1 0 [expr {[lindex $a 1] << 11}] + mix1 1 [expr {[lindex $a 2] >> 2}] + mix1 2 [expr {[lindex $a 3] << 8}] + mix1 3 [expr {[lindex $a 4] >> 16}] + mix1 4 [expr {[lindex $a 5] << 10}] + mix1 5 [expr {[lindex $a 6] >> 4}] + mix1 6 [expr {[lindex $a 7] << 8}] + mix1 7 [expr {[lindex $a 0] >> 9}] + } + for {set i 0} {$i < 256} {incr i 8} { + set a [lmap av $a bv [lrange $randrsl $i [expr {$i+7}]] { + expr {clamp($av + $bv)} + }] + mix1 0 [expr {[lindex $a 1] << 11}] + mix1 1 [expr {[lindex $a 2] >> 2}] + mix1 2 [expr {[lindex $a 3] << 8}] + mix1 3 [expr {[lindex $a 4] >> 16}] + mix1 4 [expr {[lindex $a 5] << 10}] + mix1 5 [expr {[lindex $a 6] >> 4}] + mix1 6 [expr {[lindex $a 7] << 8}] + mix1 7 [expr {[lindex $a 0] >> 9}] + for {set j 0} {$j < 8} {incr j} { + lset mm [expr {$i+$j}] [lindex $a $j] + } + } + for {set i 0} {$i < 256} {incr i 8} { + set a [lmap av $a bv [lrange $mm $i [expr {$i+7}]] { + expr {clamp($av + $bv)} + }] + mix1 0 [expr {[lindex $a 1] << 11}] + mix1 1 [expr {[lindex $a 2] >> 2}] + mix1 2 [expr {[lindex $a 3] << 8}] + mix1 3 [expr {[lindex $a 4] >> 16}] + mix1 4 [expr {[lindex $a 5] << 10}] + mix1 5 [expr {[lindex $a 6] >> 4}] + mix1 6 [expr {[lindex $a 7] << 8}] + mix1 7 [expr {[lindex $a 0] >> 9}] + for {set j 0} {$j < 8} {incr j} { + lset mm [expr {$i+$j}] [lindex $a $j] + } + } + my Step + } + + method Step {} { + incr bb [incr cc] + set i -1 + foreach x $mm { + set shift [lindex {13 -6 2 -16} [expr {[incr i] % 4}]] + set aa [expr {$aa ^ ($shift>0 ? $aa<<$shift : $aa>>-$shift)}] + set aa [expr {clamp($aa + mm($i+128))}] + set y [expr {clamp(mm($x>>2) + $aa + $bb)}] + lset mm $i $y + set bb [expr {clamp(mm($y>>10) + $x)}] + lset randrsl $i $bb + } + } + + method random {} { + set r [lindex $randrsl $randcnt] + if {[incr randcnt] == 256} { + my Step + set randcnt 0 + } + return $r + } + + method RandA {} { + expr {([my random] % 95) + 32} + } + method vernam {msg} { + binary scan $msg c* b + for {set i 0} {$i < [llength $b]} {incr i} { + lset b $i [expr {[lindex $b $i] & 255 ^ [my RandA]}] + } + return [binary encode hex [binary format c* $b]] + } +} diff --git a/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-2.tcl b/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-2.tcl new file mode 100644 index 0000000000..a9df806e0a --- /dev/null +++ b/Task/The-ISAAC-Cipher/Tcl/the-isaac-cipher-2.tcl @@ -0,0 +1,6 @@ +set key "this is my secret key" +set msg "a Top Secret secret" +ISAAC create demo $key +puts "Message: $msg" +puts "Key : $key" +puts "XOR : [demo vernam $msg]" diff --git a/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION new file mode 100644 index 0000000000..3c17c7859a --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION @@ -0,0 +1,4 @@ +Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. The lyrics can be found [http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html here]. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) + +;Cf: +* [[Comma quibbling]] diff --git a/Task/The-Twelve-Days-of-Christmas/AWK/the-twelve-days-of-christmas.awk b/Task/The-Twelve-Days-of-Christmas/AWK/the-twelve-days-of-christmas.awk new file mode 100644 index 0000000000..9a18248cdc --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/AWK/the-twelve-days-of-christmas.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f THE_TWELVE_DAYS_OF_CHRISTMAS.AWK +BEGIN { + gifts[++i] = "a partridge in a pear tree." + gifts[++i] = "two turtle doves, and" + gifts[++i] = "three french hens," + gifts[++i] = "four calling birds," + gifts[++i] = "five golden rings," + gifts[++i] = "six geese a-laying," + gifts[++i] = "seven swans a-swimming," + gifts[++i] = "eight maids a-milking," + gifts[++i] = "nine ladies dancing," + gifts[++i] = "ten lords a-leaping," + gifts[++i] = "eleven pipers piping," + gifts[++i] = "twelve drummers drumming," + split("first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth",days_arr," ") + for (i=1; i<=12; i++) { + printf("On the %s day of Christmas,\n",days_arr[i]) + print("my true love gave to me:") + for (j=i; j>0; j--) { + printf("%s\n",gifts[j]) + } + print("") + } + exit(0) +} diff --git a/Task/The-Twelve-Days-of-Christmas/ActionScript/the-twelve-days-of-christmas.as b/Task/The-Twelve-Days-of-Christmas/ActionScript/the-twelve-days-of-christmas.as new file mode 100644 index 0000000000..98287d408d --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/ActionScript/the-twelve-days-of-christmas.as @@ -0,0 +1,111 @@ +package { + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + import flash.ui.Keyboard; + + public class TwelveDaysOfChristmas extends Sprite { + + private var _textArea:TextField = new TextField(); + + public function TwelveDaysOfChristmas() { + if ( stage ) _init(); + else addEventListener(Event.ADDED_TO_STAGE, _init); + } + + private function _init(e:Event = null):void { + + removeEventListener(Event.ADDED_TO_STAGE, _init); + + _textArea = new TextField(); + _textArea.x = 10; + _textArea.y = 10; + _textArea.autoSize = TextFieldAutoSize.LEFT; + _textArea.wordWrap = true; + _textArea.width = stage.stageWidth - 20; + _textArea.height = stage.stageHeight - 10; + _textArea.multiline = true; + + var format:TextFormat = new TextFormat(); + format.size = 14; + _textArea.defaultTextFormat = format; + + var verses:Vector. = new Vector.(12, true); + var lines:Vector.; + + var days:Vector. = new Vector.(12, true); + var gifts:Vector. = new Vector.(12, true); + + days[0] = 'first'; + days[1] = 'second'; + days[2] = 'third'; + days[3] = 'fourth'; + days[4] = 'fifth'; + days[5] = 'sixth'; + days[6] = 'seventh'; + days[7] = 'eighth'; + days[8] = 'ninth'; + days[9] = 'tenth'; + days[10] = 'eleventh'; + days[11] = 'twelfth'; + + gifts[0] = 'A partridge in a pear tree'; + gifts[1] = 'Two turtle doves'; + gifts[2] = 'Three french hens'; + gifts[3] = 'Four calling birds'; + gifts[4] = 'Five golden rings'; + gifts[5] = 'Six geese a-laying'; + gifts[6] = 'Seven swans a-swimming'; + gifts[7] = 'Eight maids a-milking'; + gifts[8] = 'Nine ladies dancing'; + gifts[9] = 'Ten lords a-leaping'; + gifts[10] = 'Eleven pipers piping'; + gifts[11] = 'Twelve drummers drumming'; + + var i:uint, j:uint, k:uint, line:String; + + for ( i = 0; i < 12; i++ ) { + + lines = new Vector.(i + 2, true); + lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me"; + + j = i + 1; + k = 0; + while ( j-- > 0 ) + lines[++k] = gifts[j]; + + verses[i] = lines.join('\n'); + + if ( i == 0 ) + gifts[0] = 'And a partridge in a pear tree'; + + } + + var song:String = verses.join('\n\n'); + _textArea.text = song; + addChild(_textArea); + + _textArea.addEventListener(MouseEvent.MOUSE_WHEEL, _onMouseWheel); + stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); + + } + + private function _onKeyDown(e:KeyboardEvent):void { + if ( e.keyCode == Keyboard.DOWN ) + _textArea.y -= 40; + else if ( e.keyCode == Keyboard.UP ) + _textArea.y += 40; + } + + private function _onMouseWheel(e:MouseEvent):void { + _textArea.y += 20 * e.delta; + } + + } + +} diff --git a/Task/The-Twelve-Days-of-Christmas/Ada/the-twelve-days-of-christmas.ada b/Task/The-Twelve-Days-of-Christmas/Ada/the-twelve-days-of-christmas.ada new file mode 100644 index 0000000000..62cf29623c --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Ada/the-twelve-days-of-christmas.ada @@ -0,0 +1,36 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + +procedure Twelve_Days_Of_Christmas is + type Days is (First, Second, Third, Fourth, Fifth, Sixth, + Seventh, Eighth, Ninth, Tenth, Eleventh, Twelfth); + + package E_IO is new Ada.Text_IO.Enumeration_IO(Days); + use E_IO; + + Gifts : array (Days) of Unbounded_String := + (To_Unbounded_String(" A partridge in a pear-tree."), + To_Unbounded_String(" Two turtle doves"), + To_Unbounded_String(" Three French hens"), + To_Unbounded_String(" Four calling birds"), + To_Unbounded_String(" Five golden rings"), + To_Unbounded_String(" Six geese a-laying"), + To_Unbounded_String(" Seven swans a-swimming"), + To_Unbounded_String(" Eight maids a-milking"), + To_Unbounded_String(" Nine ladies dancing"), + To_Unbounded_String(" Ten lords a-leaping"), + To_Unbounded_String(" Eleven pipers piping"), + To_Unbounded_String(" Twelve drummers drumming")); +begin + for Day in Days loop + Put("On the "); Put(Day, Set => Lower_Case); Put(" day of Christmas,"); + New_Line; Put_Line("My true love gave to me:"); + for D in reverse Days'First..Day loop + Put_Line(To_String(Gifts(D))); + end loop; + if Day = First then + Replace_Slice(Gifts(Day), 2, 2, "And a"); + end if; + New_Line; + end loop; +end Twelve_Days_Of_Christmas; diff --git a/Task/The-Twelve-Days-of-Christmas/AutoHotkey/the-twelve-days-of-christmas.ahk b/Task/The-Twelve-Days-of-Christmas/AutoHotkey/the-twelve-days-of-christmas.ahk new file mode 100644 index 0000000000..076b93ff6b --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/AutoHotkey/the-twelve-days-of-christmas.ahk @@ -0,0 +1,22 @@ +nth := ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"] +lines := ["A partridge in a pear tree." + ,"Two turtle doves and" + ,"Three french hens" + ,"Four calling birds" + ,"Five golden rings" + ,"Six geese a-laying" + ,"Seven swans a-swimming" + ,"Eight maids a-milking" + ,"Nine ladies dancing" + ,"Ten lords a-leaping" + ,"Eleven pipers piping" + ,"Twelve drummers drumming"] + +full:="", mid:="" +loop % lines.MaxIndex() +{ + top:="On the " . nth[A_Index] . " day of Christmas,`nMy true love gave to me:" + mid:= lines[A_Index] . "`n" . mid + full:= full . top . "`n" . mid . ((A_Index +#include +#include +using namespace std; + +int main() +{ + const array days + { + "first", + "second", + "third", + "fourth", + "fifth", + "sixth", + "seventh", + "eighth", + "ninth", + "tenth", + "eleventh", + "twelfth" + }; + + const array gifts + { + "And a partridge in a pear tree", + "Two turtle doves", + "Three french hens", + "Four calling birds", + "FIVE GOLDEN RINGS", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming" + }; + + for(int i = 0; i < days.size(); ++i) + { + cout << "On the " << days[i] << " day of christmas, my true love gave" + << " to me\n"; + + if(i == 0) + { + cout << "A partridge in a pear tree\n"; + } + else + { + int j = i + 1; + while(j-- > 0) cout << gifts[j] << "\n"; + } + + cout << "\n"; + } + + return 0; +} diff --git a/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c b/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c new file mode 100644 index 0000000000..7d056b2c41 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/C/the-twelve-days-of-christmas.c @@ -0,0 +1,52 @@ +/*Abhishek Ghosh, 20th March 2014, Rotterdam*/ + +#include + +int main() +{ + int i,j; + + char days[12][10] = + { + "First", + "Second", + "Third", + "Fourth", + "Fifth", + "Sixth", + "Seventh", + "Eighth", + "Ninth", + "Tenth", + "Eleventh", + "Twelfth" + }; + + char gifts[12][33] = + { + "Twelve drummers drumming", + "Eleven pipers piping", + "Ten lords a-leaping", + "Nine ladies dancing", + "Eight maids a-milking", + "Seven swans a-swimming", + "Six geese a-laying", + "Five golden rings", + "Four calling birds", + "Three french hens", + "Two turtle doves", + "And a partridge in a pear tree." + }; + + for(i=0;i<12;i++) + { + printf("\n\nOn the %s day of Christmas\nMy true love gave to me:",days[i]); + + for(j=i;j>=0;j--) + { + (i==0)?printf("\nA partridge in a pear tree."):printf("\n%s%c",gifts[11-j],(j!=0)?',':' '); + } + } + + return 0; +} diff --git a/Task/The-Twelve-Days-of-Christmas/COBOL/the-twelve-days-of-christmas.cobol b/Task/The-Twelve-Days-of-Christmas/COBOL/the-twelve-days-of-christmas.cobol new file mode 100644 index 0000000000..4e9688c62e --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/COBOL/the-twelve-days-of-christmas.cobol @@ -0,0 +1,44 @@ + >>SOURCE FREE +PROGRAM-ID. twelve-days-of-christmas. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 gifts-area VALUE "partridge in a pear tree " + & "Two turtle doves " + & "Three french hens " + & "Four calling birds " + & "FIVE GOLDEN RINGS " + & "Six geese a-laying " + & "Seven swans a-swimming " + & "Eight maids a-milking " + & "Nine ladies dancing " + & "Ten lords a-leaping " + & "Eleven pipers piping " + & "Twelve drummers drumming ". + 03 gifts PIC X(30) OCCURS 12 TIMES + INDEXED BY gift-idx. + +01 ordinals-area VALUE "first second third fourth fifth " + & "sixth seventh eighth ninth tenth eleventh twelfth ". + 03 ordinals PIC X(10) OCCURS 12 TIMES. + +01 day-num PIC 99 COMP. + +PROCEDURE DIVISION. + PERFORM VARYING day-num FROM 1 BY 1 UNTIL day-num > 12 + DISPLAY "On the " FUNCTION TRIM(ordinals (day-num)) " day of Christmas," + " my true love gave to me" + + IF day-num = 1 + DISPLAY "A " gifts (1) + ELSE + PERFORM VARYING gift-idx FROM day-num BY -1 UNTIL gift-idx = 1 + DISPLAY gifts (gift-idx) + END-PERFORM + DISPLAY "And a " gifts (1) + END-IF + + DISPLAY SPACE + END-PERFORM + . +END PROGRAM twelve-days-of-christmas. diff --git a/Task/The-Twelve-Days-of-Christmas/Clojure/the-twelve-days-of-christmas.clj b/Task/The-Twelve-Days-of-Christmas/Clojure/the-twelve-days-of-christmas.clj new file mode 100644 index 0000000000..01cf1836ac --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Clojure/the-twelve-days-of-christmas.clj @@ -0,0 +1,16 @@ +(let [numbers '(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth) + + gifts ["And a partridge in a pear tree", "Two turtle doves", "Three French hens", + "Four calling birds", "Five gold rings", "Six geese a-laying", + "Seven swans a-swimming", "Eight maids a-miling", "Nine ladies dancing", + "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"] + + day (fn [n] (printf "On the %s day of Christmas, my true love gave to me\n" (nth numbers n)))] + + (day 0) + (println (clojure.string/replace (first gifts) "And a" "A")) + (dorun (for [d (range 1 12)] (do + (println) + (day d) + (dorun (for [n (range d -1 -1)] + (println (nth gifts n)))))))) diff --git a/Task/The-Twelve-Days-of-Christmas/D/the-twelve-days-of-christmas.d b/Task/The-Twelve-Days-of-Christmas/D/the-twelve-days-of-christmas.d new file mode 100644 index 0000000000..0ae7be6a27 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/D/the-twelve-days-of-christmas.d @@ -0,0 +1,29 @@ +immutable gifts = +"A partridge in a pear tree. +Two turtle doves +Three french hens +Four calling birds +Five golden rings +Six geese a-laying +Seven swans a-swimming +Eight maids a-milking +Nine ladies dancing +Ten lords a-leaping +Eleven pipers piping +Twelve drummers drumming"; + +immutable days = "first second third fourth fifth + sixth seventh eighth ninth tenth + eleventh twelfth"; + +void main() @safe { + import std.stdio, std.string, std.range; + + foreach (immutable n, immutable day; days.split) { + auto g = gifts.splitLines.take(n + 1).retro; + writeln("On the ", day, + " day of Christmas\nMy true love gave to me:\n", + g[0 .. $ - 1].join('\n'), + (n > 0 ? " and\n" ~ g.back : g.back.capitalize), '\n'); + } +} diff --git a/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go b/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go new file mode 100644 index 0000000000..43916090b8 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + numbers := []string{"first", "second", "third", "fourth", "fifth", + "sixth", "seventh", "eighth", "ninth", "tenth", + "eleventh", "twelfth"} + + gifts := []string{"And a partridge in a pear tree", "Two turtle doves", + "Three French hens", "Four calling birds", + "Five gold rings", "Six geese a-laying", + "Seven swans a-swimming", "Eight maids a-miling", + "Nine ladies dancing", "Ten lords a-leaping", + "Eleven pipers piping", "Twelve drummers drumming"} + + day := func(n int) { + fmt.Printf("On the %s day of Christams, my true love gave to me\n", numbers[n]) + } + + day(0) + fmt.Println(strings.Replace(gifts[0], "And a", "A", 1)) + for d := 1; d < 12; d++ { + fmt.Println() + day(d) + for g := d; g >= 0; g-- { + fmt.Println(gifts[g]) + } + } +} diff --git a/Task/The-Twelve-Days-of-Christmas/Groovy/the-twelve-days-of-christmas.groovy b/Task/The-Twelve-Days-of-Christmas/Groovy/the-twelve-days-of-christmas.groovy new file mode 100644 index 0000000000..54819d5085 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Groovy/the-twelve-days-of-christmas.groovy @@ -0,0 +1,12 @@ +def presents = ['A partridge in a pear tree.', 'Two turtle doves', 'Three french hens', 'Four calling birds', + 'Five golden rings', 'Six geese a-laying', 'Seven swans a-swimming', 'Eight maids a-milking', + 'Nine ladies dancing', 'Ten lords a-leaping', 'Eleven pipers piping', 'Twelve drummers drumming'] +['first', 'second', 'third', 'forth', 'fifth', 'sixth', 'seventh', 'eight', 'ninth', 'tenth', 'eleventh', 'Twelfth'].eachWithIndex{ day, dayIndex -> + println "On the $day day of Christmas" + println 'My true love gave to me:' + (dayIndex..0).each { p -> + print presents[p] + println p == 1 ? ' and' : '' + } + println() +} diff --git a/Task/The-Twelve-Days-of-Christmas/Icon/the-twelve-days-of-christmas.icon b/Task/The-Twelve-Days-of-Christmas/Icon/the-twelve-days-of-christmas.icon new file mode 100644 index 0000000000..467fd49827 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Icon/the-twelve-days-of-christmas.icon @@ -0,0 +1,13 @@ +procedure main() + days := ["first","second","third","fourth","fifth","sixth","seventh", + "eighth","ninth","tenth","eleventh","twelveth"] + gifts := ["A partridge in a pear tree.", "Two turtle doves and", + "Three french hens,", "Four calling birds,", + "Five golden rings,", "Six geese a-laying,", + "Seven swans a-swimming,", "Eight maids a-milking,", + "Nine ladies dancing,", "Ten lords a-leaping,", + "Eleven pipers piping,", "Twelve drummers drumming,"] + + every write("\nOn the ",days[day := 1 to 12]," day of Christmas my true love gave to me:") do + every write(" ",gifts[day to 1 by -1]) +end diff --git a/Task/The-Twelve-Days-of-Christmas/J/the-twelve-days-of-christmas.j b/Task/The-Twelve-Days-of-Christmas/J/the-twelve-days-of-christmas.j new file mode 100644 index 0000000000..ade823a445 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/J/the-twelve-days-of-christmas.j @@ -0,0 +1,26 @@ +require 'strings' NB. not necessary for versions > j6 + +days=: ;:'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' + +gifts=: <;.2 ] 0 : 0 +And a partridge in a pear tree. +Two turtle doves, +Three french hens, +Four calling birds, +Five golden rings, +Six geese a-laying, +Seven swans a-swimming, +Eight maids a-milking, +Nine ladies dancing, +Ten lords a-leaping, +Eleven pipers piping, +Twelve drummers drumming, +) + +firstline=: 'On the ' , ,&(' day of Christmas, my true love gave to me',LF) + +chgFirstVerse=: rplc&('nd a';'')&.>@{. , }. + +makeVerses=: [: chgFirstVerse (firstline&.> days) ,&.> [: <@;@|.\ gifts"_ + +singCarol=: LF joinstring makeVerses diff --git a/Task/The-Twelve-Days-of-Christmas/Java/the-twelve-days-of-christmas.java b/Task/The-Twelve-Days-of-Christmas/Java/the-twelve-days-of-christmas.java new file mode 100644 index 0000000000..5e37b633ea --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Java/the-twelve-days-of-christmas.java @@ -0,0 +1,26 @@ +public class TwelveDaysOfChristmas { + + final static String[] gifts = { + "A partridge in a pear tree.", "Two turtle doves and", + "Three french hens", "Four calling birds", + "Five golden rings", "Six geese a-laying", + "Seven swans a-swimming", "Eight maids a-milking", + "Nine ladies dancing", "Ten lords a-leaping", + "Eleven pipers piping", "Twelve drummers drumming", + "And a partridge in a pear tree.", "Two turtle doves" + }; + + final static String[] days = { + "first", "second", "third", "fourth", "fifth", "sixth", "seventh", + "eighth", "ninth", "tenth", "eleventh", "Twelfth" + }; + + public static void main(String[] args) { + for (int i = 0; i < days.length; i++) { + System.out.printf("%nOn the %s day of Christmas%n", days[i]); + System.out.println("My true love gave to me:"); + for (int j = i; j >= 0; j--) + System.out.println(gifts[i == 11 && j < 2 ? j + 12 : j]); + } + } +} diff --git a/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas.js b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas.js new file mode 100644 index 0000000000..033418ca96 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas.js @@ -0,0 +1,42 @@ +var days = [ + 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', + 'tenth', 'eleventh', 'twelfth', +]; + +var gifts = [ + "A partridge in a pear tree", + "Two turtle doves", + "Three french hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming" +]; + +var lines, verses = [], song; + +for ( var i = 0; i < 12; i++ ) { + + lines = []; + lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me"; + + var j = i + 1; + var k = 0; + while ( j-- > 0 ) + lines[++k] = gifts[j]; + + + verses[i] = lines.join('\n'); + + if ( i == 0 ) + gifts[0] = "And a partridge in a pear tree"; + +} + +song = verses.join('\n\n'); +document.write(song); diff --git a/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol b/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol new file mode 100644 index 0000000000..7852e63404 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol @@ -0,0 +1,53 @@ +CAN HAS STDIO? +HAI 1.2 + +I HAS A Dayz ITZ A BUKKIT +Dayz HAS A SRS 1 ITZ "first" +Dayz HAS A SRS 2 ITZ "second" +Dayz HAS A SRS 3 ITZ "third" +Dayz HAS A SRS 4 ITZ "fourth" +Dayz HAS A SRS 5 ITZ "fifth" +Dayz HAS A SRS 6 ITZ "sixth" +Dayz HAS A SRS 7 ITZ "seventh" +Dayz HAS A SRS 8 ITZ "eighth" +Dayz HAS A SRS 9 ITZ "ninth" +Dayz HAS A SRS 10 ITZ "tenth" +Dayz HAS A SRS 11 ITZ "eleventh" +Dayz HAS A SRS 12 ITZ "twelfth" + +I HAS A Prezents ITZ A BUKKIT +Prezents HAS A SRS 1 ITZ "A partridge in a pear tree" +Prezents HAS A SRS 2 ITZ "Two turtle doves" +Prezents HAS A SRS 3 ITZ "Three French hens" +Prezents HAS A SRS 4 ITZ "Four calling birds" +Prezents HAS A SRS 5 ITZ "Five gold rings" +Prezents HAS A SRS 6 ITZ "Six geese a-laying" +Prezents HAS A SRS 7 ITZ "Seven swans a-swimming" +Prezents HAS A SRS 8 ITZ "Eight maids a-milking" +Prezents HAS A SRS 9 ITZ "Nine ladies dancing" +Prezents HAS A SRS 10 ITZ "Ten lords a-leaping" +Prezents HAS A SRS 11 ITZ "Eleven pipers piping" +Prezents HAS A SRS 12 ITZ "Twelve drummers drumming" + +IM IN YR Outer UPPIN YR i WILE DIFFRINT i AN 12 + I HAS A Day ITZ SUM OF i AN 1 + VISIBLE "On the " ! + VISIBLE Dayz'Z SRS Day ! + VISIBLE " day of Christmas, my true love gave to me" + IM IN YR Inner UPPIN YR j WILE DIFFRINT j AN Day + I HAS A Count ITZ DIFFERENCE OF Day AN j + VISIBLE Prezents'Z SRS Count + IM OUTTA YR Inner + BOTH SAEM i AN 0 + O RLY? + YA RLY + Prezents'Z SRS 1 R "And a partridge in a pear tree" + OIC + DIFFRINT i AN 11 + O RLY? + YA RLY + VISIBLE "" + OIC +IM OUTTA YR Outer + +KTHXBYE diff --git a/Task/The-Twelve-Days-of-Christmas/Logo/the-twelve-days-of-christmas.logo b/Task/The-Twelve-Days-of-Christmas/Logo/the-twelve-days-of-christmas.logo new file mode 100644 index 0000000000..8dff0fd13c --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Logo/the-twelve-days-of-christmas.logo @@ -0,0 +1,21 @@ +make "numbers [first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth] +make "gifts [[And a partridge in a pear tree] [Two turtle doves] [Three French hens] + [Four calling birds] [Five gold rings] [Six geese a-laying] + [Seven swans a-swimming] [Eight maids a-miling] [Nine ladies dancing] + [Ten lords a-leaping] [Eleven pipers piping] [Twelve drummers drumming]] + +to nth :n + print (sentence [On the] (item :n :numbers) [day of Christmas, my true love gave to me]) +end + +nth 1 +print [A partridge in a pear tree] + +for [d 2 12] [ + print [] + nth :d + for [g :d 1] [ + print item :g gifts + ] +] +bye diff --git a/Task/The-Twelve-Days-of-Christmas/Lua/the-twelve-days-of-christmas.lua b/Task/The-Twelve-Days-of-Christmas/Lua/the-twelve-days-of-christmas.lua new file mode 100644 index 0000000000..165c592dd8 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Lua/the-twelve-days-of-christmas.lua @@ -0,0 +1,38 @@ +local days = { + 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', + 'tenth', 'eleventh', 'twelfth', +} + +local gifts = { + "A partridge in a pear tree", + "Two turtle doves", + "Three french hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming", +} + +local verses = {} + +for i = 1, 12 do + local lines = {} + lines[1] = "On the " .. days[i] .. " day of Christmas, my true love gave to me" + + local j = i + local k = 2 + repeat + lines[k] = gifts[j] + k = k + 1 + j = j - 1 + until j == 0 + + verses[i] = table.concat(lines, '\n') +end + +print(table.concat(verses, '\n\n')) diff --git a/Task/The-Twelve-Days-of-Christmas/Mathematica/the-twelve-days-of-christmas.math b/Task/The-Twelve-Days-of-Christmas/Mathematica/the-twelve-days-of-christmas.math new file mode 100644 index 0000000000..8756f3b5ee --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Mathematica/the-twelve-days-of-christmas.math @@ -0,0 +1,16 @@ +daysarray = {"first", "second", "third", "fourth", "fifth", "sixth", + "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}; +giftsarray = {"And a partridge in a pear tree.", "Two turtle doves,", + "Three french hens,", "Four calling birds,", "FIVE GOLDEN RINGS,", + "Six geese a-laying,", "Seven swans a-swimming,", + "Eight maids a-milking,", "Nine ladies dancing,", + "Ten lords a-leaping,", "Eleven pipers piping,", + "Twelve drummers drumming,"}; +Do[ + Print["On the " <> daysarray[[i]] <> + " day of Christmas, my true love gave to me: "] + Do [ + Print[If[i == 1, "A partridge in a pear tree.", giftsarray[[j]]]] + , {j, i, 1, -1}] + Print[] + , {i, 1, 12}] diff --git a/Task/The-Twelve-Days-of-Christmas/Objeck/the-twelve-days-of-christmas.objeck b/Task/The-Twelve-Days-of-Christmas/Objeck/the-twelve-days-of-christmas.objeck new file mode 100644 index 0000000000..b8bac79b4a --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Objeck/the-twelve-days-of-christmas.objeck @@ -0,0 +1,35 @@ +class TwelveDaysOfChristmas { + function : Main(args : String[]) ~ Nil { + days := ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", + "tenth", "eleventh", "twelfth"]; + + gifts := ["A partridge in a pear tree", + "Two turtle doves", + "Three french hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming"]; + + for(i := 0; i < days->Size(); i+=1;) { + IO.Console->Print("On the ")->Print(days[i])->PrintLine(" day of Christmas, my true love gave to me"); + + j := i + 1; + while(j > 0 ) { + j -= 1; + gifts[j]->PrintLine(); + }; + + IO.Console->PrintLine(); + + if (i = 0) { + gifts[0] := "And a partridge in a pear tree"; + }; + }; + } +} diff --git a/Task/The-Twelve-Days-of-Christmas/PHP/the-twelve-days-of-christmas.php b/Task/The-Twelve-Days-of-Christmas/PHP/the-twelve-days-of-christmas.php new file mode 100644 index 0000000000..acf5316bd5 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/PHP/the-twelve-days-of-christmas.php @@ -0,0 +1,46 @@ += 0 ) { + $lines[++$k] = $gifts[$j]; + $j--; + } + + $verses[$i] = implode(PHP_EOL, $lines); + + if ( $i == 0 ) + $gifts[0] = "And a partridge in a pear tree"; +} + +echo implode(PHP_EOL . PHP_EOL, $verses); + +?> diff --git a/Task/The-Twelve-Days-of-Christmas/Perl-6/the-twelve-days-of-christmas.pl6 b/Task/The-Twelve-Days-of-Christmas/Perl-6/the-twelve-days-of-christmas.pl6 new file mode 100644 index 0000000000..5629066d6a --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Perl-6/the-twelve-days-of-christmas.pl6 @@ -0,0 +1,27 @@ +my @days = ; + +my @gifts = lines q:to/END/; + And a partridge in a pear tree. + Two turtle doves, + Three french hens, + Four calling birds, + Five golden rings, + Six geese a-laying, + Seven swans a-swimming, + Eight maids a-milking, + Nine ladies dancing, + Ten lords a-leaping, + Eleven pipers piping, + Twelve drummers drumming, +END + +sub nth($n) { say "On the @days[$n] day of Christmas, my true love gave to me:" } + +nth(0); +say @gifts[0].subst('And a','A'); + +for 1 ... 11 -> $d { + say ''; + nth($d); + say @gifts[$_] for $d ... 0; +} diff --git a/Task/The-Twelve-Days-of-Christmas/Perl/the-twelve-days-of-christmas.pl b/Task/The-Twelve-Days-of-Christmas/Perl/the-twelve-days-of-christmas.pl new file mode 100644 index 0000000000..8090d4c2a0 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Perl/the-twelve-days-of-christmas.pl @@ -0,0 +1,25 @@ +use v5.10; + +my @days = qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth }; + +chomp ( my @gifts = grep { /\S/ } ); + +while ( my $day = shift @days ) { + say "On the $day day of Christmas,\nMy true love gave to me:"; + say for map { $day eq 'first' ? s/And a/A/r : $_ } @gifts[@days .. @gifts-1]; + say ""; +} + +__DATA__ +Twelve drummers drumming +Eleven pipers piping +Ten lords a-leaping +Nine ladies dancing +Eight maids a-milking +Seven swans a-swimming +Six geese a-laying +Five golden rings +Four calling birds +Three french hens +Two turtle doves +And a partridge in a pear tree. diff --git a/Task/The-Twelve-Days-of-Christmas/PicoLisp/the-twelve-days-of-christmas.l b/Task/The-Twelve-Days-of-Christmas/PicoLisp/the-twelve-days-of-christmas.l new file mode 100644 index 0000000000..fe6fc12d33 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/PicoLisp/the-twelve-days-of-christmas.l @@ -0,0 +1,29 @@ +(de days + first second third fourth fifth sixth + seventh eight ninth tenth eleventh twelfth ) + +(de texts + "A partridge in a pear tree." + "Two turtle doves and" + "Three french hens" + "Four calling birds" + "Five golden rings" + "Six geese a-laying" + "Seven swans a-swimming" + "Eight maids a-milking" + "Nine ladies dancing" + "Ten lords a-leaping" + "Eleven pipers piping" + "Twelve drummers drumming" ) + +(for (X . Day) days + (prinl "On the " Day " day of Christmas") + (prinl "My true love game to me:") + (for (Y X (gt0 Y) (dec Y)) + (prinl + (if (and (= 12 X) (= 1 Y)) + "And a partridge in a pear tree." + (get texts Y)) ) ) + (prinl) ) + +(bye) diff --git a/Task/The-Twelve-Days-of-Christmas/PowerShell/the-twelve-days-of-christmas.psh b/Task/The-Twelve-Days-of-Christmas/PowerShell/the-twelve-days-of-christmas.psh new file mode 100644 index 0000000000..6f84cf0c87 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/PowerShell/the-twelve-days-of-christmas.psh @@ -0,0 +1,39 @@ +$days = @{ + 1 = "first"; + 2 = "second"; + 3 = "third"; + 4 = "fourth"; + 5 = "fifth"; + 6 = "sixth"; + 7 = "seventh"; + 8 = "eight"; + 9 = "ninth"; + 10 = "tenth"; + 11 = "eleventh"; + 12 = "twelfth"; +} + +$gifts = @{ + 1 = 'A partridge in a pear tree'; + 2 = 'Two turtle doves'; + 3 = 'Three french hens'; + 4 = 'Four calling birds'; + 5 = 'Five golden rings'; + 6 = 'Six geese a-laying'; + 7 = 'Seven swans a-swimming'; + 8 = 'Eight maids a-milking'; + 9 = 'Nine ladies dancing'; + 10 = 'Ten lords a-leaping'; + 11 = 'Eleven pipers piping'; + 12 = 'Twelve drummers drumming'; +} + +1 .. 12 | % { + "On the $($days[$_]) day of Christmas`nMy true love gave to me" + $_ .. 1 | % { + $gift = $gifts[$_] + if ($_ -eq 2) { $gift += " and" } + $gift + } + "" +} diff --git a/Task/The-Twelve-Days-of-Christmas/Python/the-twelve-days-of-christmas.py b/Task/The-Twelve-Days-of-Christmas/Python/the-twelve-days-of-christmas.py new file mode 100644 index 0000000000..283cbde015 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Python/the-twelve-days-of-christmas.py @@ -0,0 +1,23 @@ +gifts = '''\ +A partridge in a pear tree. +Two turtle doves +Three french hens +Four calling birds +Five golden rings +Six geese a-laying +Seven swans a-swimming +Eight maids a-milking +Nine ladies dancing +Ten lords a-leaping +Eleven pipers piping +Twelve drummers drumming'''.split('\n') + +days = '''first second third fourth fifth + sixth seventh eighth ninth tenth + eleventh twelfth'''.split() + +for n, day in enumerate(days, 1): + g = gifts[:n][::-1] + print(('\nOn the %s day of Christmas\nMy true love gave to me:\n' % day) + + '\n'.join(g[:-1]) + + (' and\n' + g[-1] if n > 1 else g[-1].capitalize())) diff --git a/Task/The-Twelve-Days-of-Christmas/README b/Task/The-Twelve-Days-of-Christmas/README new file mode 100644 index 0000000000..8a7c4b8257 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas diff --git a/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx new file mode 100644 index 0000000000..75326c4761 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx @@ -0,0 +1,17 @@ +/*REXX program displays the verses of song "The 12 days of Christmas". */ +Nth='first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' +pad=left('',20) + + g.1= 'A partridge in a pear-tree.'; g.7 = 'Seven swans a-swimming,' + g.2= 'Two Turtle Doves, and' ; g.8 = 'Eight maids a-milking,' + g.3= 'Three French Hens,' ; g.9 = 'Nine ladies dancing,' + g.4= 'Four Calling Birds,' ; g.10= 'Ten lords a-leaping,' + g.5= 'Five Golden Rings,' ; g.11= 'Eleven pipers piping,' + g.6= 'Six geese a-laying,' ; g.12= 'Twelve drummers drumming,' + + do day=1 for 12 + say pad 'On the' word(Nth,day) 'day of Christmas' /*prologue, line 1.*/ + say pad 'My True Love gave to me:' /*prologue, line 2.*/ + do j=day to 1 by -1; say pad g.j; end /*display the gifts*/ + say /*add a blank line between verses*/ + end /*day*/ /*stick a fork in it, we're done.*/ diff --git a/Task/The-Twelve-Days-of-Christmas/Racket/the-twelve-days-of-christmas.rkt b/Task/The-Twelve-Days-of-Christmas/Racket/the-twelve-days-of-christmas.rkt new file mode 100644 index 0000000000..087d17ab93 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Racket/the-twelve-days-of-christmas.rkt @@ -0,0 +1,35 @@ +#lang racket +(define (ordinal-text d) + (vector-ref + (vector + "zeroth" "first" "second" "third" "fourth" + "fifth" "sixth" "seventh" "eighth" "ninth" + "tenth" "eleventh" "twelfth") + d)) + +(define (on-the... day) + (printf "On the ~a day of Christmas,~%" (ordinal-text day)) + (printf "My True Love gave to me,~%")) + +(define (prezzy prezzy-line day) + (match prezzy-line + [1 (string-append (if (= day 1) "A " "And a")" partridge in a pear tree")] + [2 "Two turtle doves"] + [3 "Three French hens"] + [4 "Four calling birds"] + [5 "FIVE GO-OLD RINGS"] + [6 "Six geese a-laying"] + [7 "Seven swans a-swimming"] + [8 "Eight maids a-milking"] + [9 "Nine ladies dancing"] + [10 "Ten lords a-leaping"] + [11 "Eleven pipers piping"] + [12 "Twelve drummers drumming"])) + +(define (line-end prezzy-line day) + (match* (day prezzy-line) [(12 1) "."] [(x 1) ".\n"] [(_ _) ","])) + +(for ((day (sequence-map add1 (in-range 12))) + #:when (on-the... day) + (prezzy-line (in-range day 0 -1))) + (printf "~a~a~%" (prezzy prezzy-line day) (line-end prezzy-line day))) diff --git a/Task/The-Twelve-Days-of-Christmas/Ruby/the-twelve-days-of-christmas.rb b/Task/The-Twelve-Days-of-Christmas/Ruby/the-twelve-days-of-christmas.rb new file mode 100644 index 0000000000..ffb94c9e67 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Ruby/the-twelve-days-of-christmas.rb @@ -0,0 +1,23 @@ +gifts = "A partridge in a pear tree +Two turtle doves +Three french hens +Four calling birds +Five golden rings +Six geese a-laying +Seven swans a-swimming +Eight maids a-milking +Nine ladies dancing +Ten lords a-leaping +Eleven pipers piping +Twelve drummers drumming".split("\n") + +days = %w(first second third fourth fifth sixth +seventh eighth ninth tenth eleventh twelfth) + +days.each_with_index do |day, i| + puts "On the #{day} day of Christmas" + puts "My true love gave to me:" + puts gifts[0, i+1].reverse + puts + gifts[1] << " and" if i == 0 +end diff --git a/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust b/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust new file mode 100644 index 0000000000..2f7d3ce205 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust @@ -0,0 +1,43 @@ +// -*- rust v0.9 -*- + +fn showpresents(count : uint) { + let days = ["second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", + "tenth", "eleventh", "twelfth"]; + + let presents = ["Two turtle doves", + "Three french hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming"]; + + println!("On the {:s} day of Christmas my true love gave to me {:s}", days[count-1], presents[count-1]); + if count > 0{ + let mut j = count-1; + while j > 0{ + println!("{:s}", presents[j-1]); + j -= 1; + + } + } + println("And a partridge in a pear tree \n"); +} + +fn main() { + + let mut count = 0; + while count < 12 { + match count { + 0 => println("On the first day of Christmas my true love gave to me a partridge in a pear tree"), + _ => showpresents(count) + }; + count += 1; + } + + +} diff --git a/Task/The-Twelve-Days-of-Christmas/Seed7/the-twelve-days-of-christmas.seed7 b/Task/The-Twelve-Days-of-Christmas/Seed7/the-twelve-days-of-christmas.seed7 new file mode 100644 index 0000000000..d3e9a1f7b7 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Seed7/the-twelve-days-of-christmas.seed7 @@ -0,0 +1,26 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const array string: gifts is [] ( + "A partridge in a pear tree.", "Two turtle doves and", + "Three french hens", "Four calling birds", + "Five golden rings", "Six geese a-laying", + "Seven swans a-swimming", "Eight maids a-milking", + "Nine ladies dancing", "Ten lords a-leaping", + "Eleven pipers piping", "Twelve drummers drumming"); + const array string: days is [] ( + "first", "second", "third", "fourth", "fifth", "sixth", + "seventh", "eighth", "ninth", "tenth", "eleventh", "Twelfth"); + var integer: day is 0; + var integer: gift is 0; + begin + for day range 1 to length(days) do + writeln; + writeln("On the " <& days[day] <& " day of Christmas,"); + writeln("My true love gave to me:"); + for gift range day downto 1 do + writeln(gifts[gift]); + end for; + end for; + end func; diff --git a/Task/The-Twelve-Days-of-Christmas/Tcl/the-twelve-days-of-christmas.tcl b/Task/The-Twelve-Days-of-Christmas/Tcl/the-twelve-days-of-christmas.tcl new file mode 100644 index 0000000000..30e150c707 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Tcl/the-twelve-days-of-christmas.tcl @@ -0,0 +1,23 @@ +set days { + first second third fourth fifth sixth + seventh eighth ninth tenth eleventh twelfth +} +set gifts [lreverse { + "A partridge in a pear tree." + "Two turtle doves, and" + "Three french hens," + "Four calling birds," + "Five golden rings," + "Six geese a-laying," + "Seven swans a-swimming," + "Eight maids a-milking," + "Nine ladies dancing," + "Ten lords a-leaping," + "Eleven pipers piping," + "Twelve drummers drumming," +}] + +set n -1;puts [join [lmap day $days { + format "On the $day day of Christmas,\nMy true love gave to me:\n%s" \ + [join [lrange $gifts end-[incr n] end] \n] +}] \n\n] diff --git a/Task/Total-circles-area/00DESCRIPTION b/Task/Total-circles-area/00DESCRIPTION new file mode 100644 index 0000000000..d3c2d91309 --- /dev/null +++ b/Task/Total-circles-area/00DESCRIPTION @@ -0,0 +1,44 @@ +Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. + +One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. + +To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the x and y coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks): + +[[File:total_circles_area_full.png|200px|thumb|right|Example circles]] +[[File:total_circles_area_filtered.png|200px|thumb|right|Example circles filtered]] + +
+      xc             yc        radius
+ 1.6417233788  1.6121789534 0.0848270516
+-1.4944608174  1.2077959613 1.1039549836
+ 0.6110294452 -0.6907087527 0.9089162485
+ 0.3844862411  0.2923344616 0.2375743054
+-0.2495892950 -0.3832854473 1.0845181219
+ 1.7813504266  1.6178237031 0.8162655711
+-0.1985249206 -0.8343333301 0.0538864941
+-1.7011985145 -0.1263820964 0.4776976918
+-0.4319462812  1.4104420482 0.7886291537
+ 0.2178372997 -0.9499557344 0.0357871187
+-0.6294854565 -1.3078893852 0.7653357688
+ 1.7952608455  0.6281269104 0.2727652452
+ 1.4168575317  1.0683357171 1.1016025378
+ 1.4637371396  0.9463877418 1.1846214562
+-0.5263668798  1.7315156631 1.4428514068
+-1.2197352481  0.9144146579 1.0727263474
+-0.1389358881  0.1092805780 0.7350208828
+ 1.5293954595  0.0030278255 1.2472867347
+-0.5258728625  1.3782633069 1.3495508831
+-0.1403562064  0.2437382535 1.3804956588
+ 0.8055826339 -0.0482092025 0.3327165165
+-0.6311979224  0.7184578971 0.2491045282
+ 1.4685857879 -0.8347049536 1.3670667538
+-0.6855727502  1.6465021616 1.0593087096
+ 0.0152957411  0.0638919221 0.9771215985
+ +The result is 21.56503660... . + +;See also + +* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ + +* http://stackoverflow.com/a/1667789/10562 diff --git a/Task/Total-circles-area/C/total-circles-area-1.c b/Task/Total-circles-area/C/total-circles-area-1.c new file mode 100644 index 0000000000..b1f7884778 --- /dev/null +++ b/Task/Total-circles-area/C/total-circles-area-1.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include +#include + +typedef double Fp; +typedef struct { Fp x, y, r; } Circle; + +Circle circles[] = { + { 1.6417233788, 1.6121789534, 0.0848270516}, + {-1.4944608174, 1.2077959613, 1.1039549836}, + { 0.6110294452, -0.6907087527, 0.9089162485}, + { 0.3844862411, 0.2923344616, 0.2375743054}, + {-0.2495892950, -0.3832854473, 1.0845181219}, + { 1.7813504266, 1.6178237031, 0.8162655711}, + {-0.1985249206, -0.8343333301, 0.0538864941}, + {-1.7011985145, -0.1263820964, 0.4776976918}, + {-0.4319462812, 1.4104420482, 0.7886291537}, + { 0.2178372997, -0.9499557344, 0.0357871187}, + {-0.6294854565, -1.3078893852, 0.7653357688}, + { 1.7952608455, 0.6281269104, 0.2727652452}, + { 1.4168575317, 1.0683357171, 1.1016025378}, + { 1.4637371396, 0.9463877418, 1.1846214562}, + {-0.5263668798, 1.7315156631, 1.4428514068}, + {-1.2197352481, 0.9144146579, 1.0727263474}, + {-0.1389358881, 0.1092805780, 0.7350208828}, + { 1.5293954595, 0.0030278255, 1.2472867347}, + {-0.5258728625, 1.3782633069, 1.3495508831}, + {-0.1403562064, 0.2437382535, 1.3804956588}, + { 0.8055826339, -0.0482092025, 0.3327165165}, + {-0.6311979224, 0.7184578971, 0.2491045282}, + { 1.4685857879, -0.8347049536, 1.3670667538}, + {-0.6855727502, 1.6465021616, 1.0593087096}, + { 0.0152957411, 0.0638919221, 0.9771215985}}; + +const size_t n_circles = sizeof(circles) / sizeof(Circle); + +static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } + +static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } + +static inline Fp sq(const Fp a) { return a * a; } + +// Return an uniform random value in [a, b). +static inline double uniform(const double a, const double b) { + const double r01 = rand() / (double)RAND_MAX; + return a + (b - a) * r01; +} + +static inline bool is_inside_circles(const Fp x, const Fp y) { + for (size_t i = 0; i < n_circles; i++) + if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) + return true; + return false; +} + +int main() { + // Initialize the bounding box (bbox) of the circles. + Fp x_min = INFINITY, x_max = -INFINITY; + Fp y_min = x_min, y_max = x_max; + + // Compute the bounding box of the circles. + for (size_t i = 0; i < n_circles; i++) { + Circle *c = &circles[i]; + x_min = min(x_min, c->x - c->r); + x_max = max(x_max, c->x + c->r); + y_min = min(y_min, c->y - c->r); + y_max = max(y_max, c->y + c->r); + + c->r *= c->r; // Square the radii to speed up testing. + } + + const Fp bbox_area = (x_max - x_min) * (y_max - y_min); + + // Montecarlo sampling. + srand(time(0)); + size_t to_try = 1U << 16; + size_t n_tries = 0; + size_t n_hits = 0; + + while (true) { + n_hits += is_inside_circles(uniform(x_min, x_max), + uniform(y_min, y_max)); + n_tries++; + + if (n_tries == to_try) { + const Fp area = bbox_area * n_hits / n_tries; + const Fp r = (Fp)n_hits / n_tries; + const Fp s = area * sqrt(r * (1 - r) / n_tries); + printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); + if (s * 3 <= 1e-3) // Stop at 3 sigmas. + break; + to_try *= 2; + } + } + + return 0; +} diff --git a/Task/Total-circles-area/C/total-circles-area-2.c b/Task/Total-circles-area/C/total-circles-area-2.c new file mode 100644 index 0000000000..5a3d527799 --- /dev/null +++ b/Task/Total-circles-area/C/total-circles-area-2.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include + +typedef double flt; +typedef struct { + flt x, y, r, r2; + flt y0, y1; // extent of circle y+r and y-r + flt x0, x1; // where scanline intersects circle +} circle_t; +#define SZ sizeof(circle_t) + +circle_t circles[] = { + { 1.6417233788, 1.6121789534, 0.0848270516}, +#error data snipped for space; copy from previous C example +}; + +flt max(flt x, flt y) { return x < y ? y : x; } +flt min(flt x, flt y) { return x > y ? y : x; } +flt sq(flt x) { return x * x; } +flt cdist(circle_t *c1, circle_t *c2) { + return sqrt(sq(c1->x - c2->x) + sq(c1->y - c2->y)); +} + +inline void swap_c(circle_t *c) +{ + circle_t tmp = c[0]; + c[0] = c[1], c[1] = tmp; +} + +flt area(circle_t *circs, int n_circ, flt ymin, flt ymax, flt step) +{ + int i, n = n_circ; + + circle_t *c = malloc(SZ * n); + memcpy(c, circs, SZ * n); + + while (n--) + for (i = 0; i < n; i++) + if (c[i].y1 < c[i+1].y1) swap_c(c + i); + + flt total = 0; + + int row = 1 + ceil((ymax - ymin) / step); + while (row--) { + flt y = ymin + step * row; + for (n = 0; n < n_circ; n++) + if (y >= c[n].y1) // rest of circles below scanline, ignore + break; + else if (y > c[n].y0) { + flt dx = sqrt(c[n].r2 - sq(y - c[n].y)); + c[n].x0 = c[n].x - dx; + c[n].x1 = c[n].x + dx; + + // keep circles sorted by left intersection + for (i = n; i-- && c[i].x0 > c[i+1].x0; swap_c(c + i)); + + } else {// remove a circle when scanline has passed it + memmove(c + n, c + n + 1, SZ * (--n_circ - n)); + n--; + } + + if (!n) continue; + + flt right = c->x1; + total += c->x1 - c->x0; + + for (i = 1; i < n; i++) { + if (c[i].x1 <= right) continue; + total += c[i].x1 - max(c[i].x0, right); + right = c[i].x1; + } + } + + free(c); + return total * step; +} + +int main(void) +{ + int n_circ = sizeof(circles) / SZ; + flt ymin = INFINITY, ymax = -INFINITY; + + circle_t *c1, *c2; + for (c1 = circles + n_circ; c1-- > circles; ) { + for (c2 = circles + n_circ; c2-- > circles; ) + // throw out circles inside another circle + if (c1 != c2 && cdist(c1, c2) + c1->r <= c2->r) { + *c1 = circles[--n_circ]; + break; + } + ymin = min(ymin, c1->y0 = c1->y - c1->r); + ymax = max(ymax, c1->y1 = c1->y + c1->r); + c1->r2 = sq(c1->r); + } + + flt s = 1. / (1 << 20); + flt y0 = floor(ymin / s) * s; + flt a = area(circles, n_circ, y0, ymax, s); + int nlines = (ymax - y0) / s; + + // roughly, it cease to make sense if sqrt(nlines) * 1e-14 >> s * s + printf("area = %.10f\tat %d scanlines\n", a, nlines); + + return 0; +} diff --git a/Task/Total-circles-area/D/total-circles-area-1.d b/Task/Total-circles-area/D/total-circles-area-1.d new file mode 100644 index 0000000000..76dedc141a --- /dev/null +++ b/Task/Total-circles-area/D/total-circles-area-1.d @@ -0,0 +1,114 @@ +import std.stdio, std.math, std.algorithm, std.typecons, std.range; + +alias Fp = real; +struct Circle { Fp x, y, r; } + +void removeInternalDisks(ref Circle[] circles) pure nothrow @safe { + static bool isFullyInternal(in Circle c1, in Circle c2) + pure nothrow @safe @nogc { + if (c1.r > c2.r) // Quick exit. + return false; + return (c1.x - c2.x) ^^ 2 + (c1.y - c2.y) ^^ 2 < + (c2.r - c1.r) ^^ 2; + } + + // Heuristics for performance: large radii first. + circles.sort!q{ a.r > b.r }; + + // Remove circles inside another circle. + for (auto i = circles.length; i-- > 0; ) + for (auto j = circles.length; j-- > 0; ) + if (i != j && isFullyInternal(circles[i], circles[j])) { + circles[i] = circles[$ - 1]; + circles.length--; + break; + } +} + +void main() { + Circle[] circles = [ + { 1.6417233788, 1.6121789534, 0.0848270516}, + {-1.4944608174, 1.2077959613, 1.1039549836}, + { 0.6110294452, -0.6907087527, 0.9089162485}, + { 0.3844862411, 0.2923344616, 0.2375743054}, + {-0.2495892950, -0.3832854473, 1.0845181219}, + { 1.7813504266, 1.6178237031, 0.8162655711}, + {-0.1985249206, -0.8343333301, 0.0538864941}, + {-1.7011985145, -0.1263820964, 0.4776976918}, + {-0.4319462812, 1.4104420482, 0.7886291537}, + { 0.2178372997, -0.9499557344, 0.0357871187}, + {-0.6294854565, -1.3078893852, 0.7653357688}, + { 1.7952608455, 0.6281269104, 0.2727652452}, + { 1.4168575317, 1.0683357171, 1.1016025378}, + { 1.4637371396, 0.9463877418, 1.1846214562}, + {-0.5263668798, 1.7315156631, 1.4428514068}, + {-1.2197352481, 0.9144146579, 1.0727263474}, + {-0.1389358881, 0.1092805780, 0.7350208828}, + { 1.5293954595, 0.0030278255, 1.2472867347}, + {-0.5258728625, 1.3782633069, 1.3495508831}, + {-0.1403562064, 0.2437382535, 1.3804956588}, + { 0.8055826339, -0.0482092025, 0.3327165165}, + {-0.6311979224, 0.7184578971, 0.2491045282}, + { 1.4685857879, -0.8347049536, 1.3670667538}, + {-0.6855727502, 1.6465021616, 1.0593087096}, + { 0.0152957411, 0.0638919221, 0.9771215985}]; + + writeln("Input Circles: ", circles.length); + removeInternalDisks(circles); + writeln("Circles left: ", circles.length); + + immutable Fp xMin = reduce!((acc, c) => min(acc, c.x - c.r)) + (Fp.max, circles[]); + immutable Fp xMax = reduce!((acc, c) => max(acc, c.x + c.r)) + (Fp(0), circles[]); + + alias YRange = Tuple!(Fp,"y0", Fp,"y1"); + auto yRanges = new YRange[circles.length]; + + Fp computeTotalArea(in Fp nSlicesX) nothrow @safe { + Fp total = 0; + + // Adapted from an idea by Cosmologicon. + foreach (immutable p; cast(int)(xMin * nSlicesX) .. + cast(int)(xMax * nSlicesX) + 1) { + immutable Fp x = p / nSlicesX; + size_t nPairs = 0; + + // Look for the circles intersecting the current + // vertical secant: + foreach (const ref c; circles) { + immutable Fp d = c.r ^^ 2 - (c.x - x) ^^ 2; + immutable Fp sd = d.sqrt; + if (d > 0) + // And keep only the intersection chords. + yRanges[nPairs++] = YRange(c.y - sd, c.y + sd); + } + + // Merge the ranges, counting the overlaps only once. + yRanges[0 .. nPairs].sort(); + Fp y = -Fp.max; + foreach (immutable r; yRanges[0 .. nPairs]) + if (y < r.y1) { + total += r.y1 - max(y, r.y0); + y = r.y1; + } + } + + return total / nSlicesX; + } + + // Iterate to reach some precision. + enum Fp epsilon = 1e-9; + Fp nSlicesX = 1_000; + Fp oldArea = -1; + while (true) { + immutable Fp newArea = computeTotalArea(nSlicesX); + if (abs(oldArea - newArea) < epsilon) { + writeln("N. vertical slices: ", nSlicesX); + writefln("Approximate area: %.17f", newArea); + return; + } + oldArea = newArea; + nSlicesX *= 2; + } +} diff --git a/Task/Total-circles-area/D/total-circles-area-2.d b/Task/Total-circles-area/D/total-circles-area-2.d new file mode 100644 index 0000000000..ce7f24b1f2 --- /dev/null +++ b/Task/Total-circles-area/D/total-circles-area-2.d @@ -0,0 +1,168 @@ +import std.stdio, std.typecons, std.math, std.algorithm, std.range; + +struct Vec { double x, y; } + +alias VF = double function(in Vec, in Vec) pure nothrow @safe @nogc; +enum VF vCross = (v1, v2) => v1.x * v2.y - v1.y * v2.x; +enum VF vDot = (v1, v2) => v1.x * v2.x + v1.y * v2.y; + +alias VV = Vec function(in Vec, in Vec) pure nothrow @safe @nogc; +enum VV vAdd = (v1, v2) => Vec(v1.x + v2.x, v1.y + v2.y); +enum VV vSub = (v1, v2) => Vec(v1.x - v2.x, v1.y - v2.y); + +enum vLen = (in Vec v) pure nothrow @safe @nogc => vDot(v, v).sqrt; +enum VF vDist = (a, b) => vSub(a, b).vLen; +enum vScale = (in double s, in Vec v) pure nothrow @safe @nogc => + Vec(v.x * s, v.y * s); +enum vNorm = (in Vec v) pure nothrow @safe @nogc => + Vec(v.x / v.vLen, v.y / v.vLen); + +alias A = Typedef!double; + +enum vAngle = (in Vec v) pure nothrow @safe @nogc => atan2(v.y, v.x).A; + +A aNorm(in A a) pure nothrow @safe @nogc { + if (a > PI) return A(a - PI * 2.0); + if (a < -PI) return A(a + PI * 2.0); + return a; +} + +struct Circle { double x, y, r; } + +A[] circleCross(in Circle c0, in Circle c1) pure nothrow { + immutable d = vDist(Vec(c0.x, c0.y), Vec(c1.x, c1.y)); + if (d >= c0.r + c1.r || d <= abs(c0.r - c1.r)) + return []; + + immutable s = (c0.r + c1.r + d) / 2.0; + immutable a = sqrt(s * (s - d) * (s - c0.r) * (s - c1.r)); + immutable h = 2.0 * a / d; + immutable dr = Vec(c1.x - c0.x, c1.y - c0.y); + immutable dx = vScale(sqrt(c0.r ^^ 2 - h ^^ 2), dr.vNorm); + immutable ang = (c0.r ^^ 2 + d ^^ 2 > c1.r ^^ 2) ? + dr.vAngle : + A(PI + dr.vAngle); + immutable da = asin(h / c0.r).A; + return [A(ang - da), A(ang + da)].map!aNorm.array; +} + +// Angles of the start and end points of the circle arc. +alias Angle2 = Tuple!(A,"a0", A,"a1"); + +alias Arc = Tuple!(Circle,"c", Angle2,"aa"); + +enum arcPoint = (in Circle c, in A a) pure nothrow @safe @nogc => + vAdd(Vec(c.x, c.y), Vec(c.r * cos(cast(double)a), + c.r * sin(cast(double)a))); + +alias ArcF = Vec function(in Arc) pure nothrow @safe @nogc; +enum ArcF arcStart = ar => arcPoint(ar.c, ar.aa.a0); +enum ArcF arcMid = ar => arcPoint(ar.c, A((ar.aa.a0+ar.aa.a1) / 2)); +enum ArcF arcEnd = ar => arcPoint(ar.c, ar.aa.a1); +enum ArcF arcCenter = ar => Vec(ar.c.x, ar.c.y); + +enum arcArea = (in Arc ar) pure nothrow @safe @nogc => + ar.c.r ^^ 2 * (ar.aa.a1 - ar.aa.a0) / 2.0; + +Arc[] splitCircles(immutable Circle[] cs) pure /*nothrow*/ { + static enum cSplit = (in Circle c, in A[] angs) pure nothrow => + c.repeat.zip(angs.zip(angs.dropOne).map!Angle2).map!Arc; + + // If an arc that was part of one circle is inside *another* circle, + // it will not be part of the zero-winding path, so reject it. + static bool inCircle(VC)(in VC vc, in Circle c) pure nothrow @nogc{ + return vc[1] != c && vDist(Vec(vc[0].x, vc[0].y), + Vec(c.x, c.y)) < c.r; + } + + enum inAnyCircle = (in Arc arc) nothrow @safe => + cs.map!(c => inCircle(tuple(arc.arcMid, arc.c), c)).any; + + auto f(in Circle c) pure nothrow { + auto angs = cs.map!(c1 => circleCross(c, c1)).join; + return tuple(c, ([A(-PI), A(PI)] ~ angs) + .sort().release); + } + + return cs.map!f.map!(ca => cSplit(ca[])).join + .filter!(ar => !inAnyCircle(ar)).array; +} + + +/** Given a list of arcs, build sets of closed paths from them. If +one arc's end point is no more than 1e-4 from another's start point, +they are considered connected. Since these start/end points resulted +from intersecting circles earlier, they *should* be exactly the same, +but floating point precision may cause small differences, hence the +1e-4 error margin. When there are genuinely different intersections +closer than this margin, the method will backfire, badly. */ +const(Arc[])[] makePaths(in Arc[] arcs) pure nothrow @safe { + static const(Arc[])[] joinArcs(in Arc[] a, in Arc[] xxs) + pure nothrow { + static enum eps = 1e-4; + if (xxs.empty) return [a]; + immutable x = xxs[0]; + const xs = xxs.dropOne; + if (a.empty) return joinArcs([x], xs); + if (vDist(a[0].arcStart, a.back.arcEnd) < eps) + return [a] ~ joinArcs([], xxs); + if (vDist(a.back.arcEnd, x.arcStart) < eps) + return joinArcs(a ~ [x], xs); + return joinArcs(a, xs ~ [x]); + } + return joinArcs([], arcs); +} + +// Slice N-polygon into N-2 triangles. +double polylineArea(in Vec[] vvs) pure nothrow { + static enum triArea = (in Vec a, in Vec b, in Vec c) + pure nothrow @nogc => vCross(vSub(b, a), vSub(c, b)) / 2.0; + const vs = vvs.dropOne; + immutable vvs0 = vvs[0]; + return zip(vs, vs.dropOne).map!(vv => triArea(vvs0, vv[])).sum; +} + +double pathArea(in Arc[] arcs) pure nothrow { + static f(in Tuple!(double, const(Vec)[]) ae, in Arc arc) + pure nothrow { + return tuple(ae[0] + arc.arcArea, + ae[1] ~ [arc.arcCenter, arc.arcEnd]); + } + const ae = reduce!f(tuple(0.0, (const(Vec)[]).init), arcs); + return ae[0] + ae[1].polylineArea; +} + +enum circlesArea = (immutable Circle[] cs) pure /*nothrow*/ => + cs.splitCircles.makePaths.map!pathArea.sum; + + +void main() { + immutable circles = [ + Circle( 1.6417233788, 1.6121789534, 0.0848270516), + Circle(-1.4944608174, 1.2077959613, 1.1039549836), + Circle( 0.6110294452, -0.6907087527, 0.9089162485), + Circle( 0.3844862411, 0.2923344616, 0.2375743054), + Circle(-0.2495892950, -0.3832854473, 1.0845181219), + Circle( 1.7813504266, 1.6178237031, 0.8162655711), + Circle(-0.1985249206, -0.8343333301, 0.0538864941), + Circle(-1.7011985145, -0.1263820964, 0.4776976918), + Circle(-0.4319462812, 1.4104420482, 0.7886291537), + Circle( 0.2178372997, -0.9499557344, 0.0357871187), + Circle(-0.6294854565, -1.3078893852, 0.7653357688), + Circle( 1.7952608455, 0.6281269104, 0.2727652452), + Circle( 1.4168575317, 1.0683357171, 1.1016025378), + Circle( 1.4637371396, 0.9463877418, 1.1846214562), + Circle(-0.5263668798, 1.7315156631, 1.4428514068), + Circle(-1.2197352481, 0.9144146579, 1.0727263474), + Circle(-0.1389358881, 0.1092805780, 0.7350208828), + Circle( 1.5293954595, 0.0030278255, 1.2472867347), + Circle(-0.5258728625, 1.3782633069, 1.3495508831), + Circle(-0.1403562064, 0.2437382535, 1.3804956588), + Circle( 0.8055826339, -0.0482092025, 0.3327165165), + Circle(-0.6311979224, 0.7184578971, 0.2491045282), + Circle( 1.4685857879, -0.8347049536, 1.3670667538), + Circle(-0.6855727502, 1.6465021616, 1.0593087096), + Circle( 0.0152957411, 0.0638919221, 0.9771215985)]; + + writefln("Area: %1.13f", circles.circlesArea); +} diff --git a/Task/Total-circles-area/Go/total-circles-area.go b/Task/Total-circles-area/Go/total-circles-area.go new file mode 100644 index 0000000000..d0842adef9 --- /dev/null +++ b/Task/Total-circles-area/Go/total-circles-area.go @@ -0,0 +1,232 @@ +package main + +import ( + "flag" + "fmt" + "math" + "runtime" + "sort" +) + +// Note, the standard "image" package has Point and Rectangle but we +// can't use them here since they're defined using int rather than +// float64. + +type Circle struct{ X, Y, R, rsq float64 } + +func NewCircle(x, y, r float64) Circle { + // We pre-calculate r² as an optimization + return Circle{x, y, r, r * r} +} + +func (c Circle) ContainsPt(x, y float64) bool { + return distSq(x, y, c.X, c.Y) <= c.rsq +} + +func (c Circle) ContainsC(c2 Circle) bool { + return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) +} + +func (c Circle) ContainsR(r Rect) (full, corner bool) { + nw := c.ContainsPt(r.NW()) + ne := c.ContainsPt(r.NE()) + sw := c.ContainsPt(r.SW()) + se := c.ContainsPt(r.SE()) + return nw && ne && sw && se, nw || ne || sw || se +} + +func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } +func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } +func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } +func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } + +type Rect struct{ X1, Y1, X2, Y2 float64 } + +func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } +func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } +func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } +func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } +func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } + +func (r Rect) Centre() (float64, float64) { + return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 +} + +func (r Rect) ContainsPt(x, y float64) bool { + return r.X1 <= x && x < r.X2 && + r.Y1 <= y && y < r.Y2 +} + +func (r Rect) ContainsPC(c Circle) bool { // only N,W,E,S points of circle + return r.ContainsPt(c.North()) || + r.ContainsPt(c.South()) || + r.ContainsPt(c.West()) || + r.ContainsPt(c.East()) +} + +func (r Rect) MinSide() float64 { + return math.Min(r.X2-r.X1, r.Y2-r.Y1) +} + +func distSq(x1, y1, x2, y2 float64) float64 { + Δx, Δy := x2-x1, y2-y1 + return (Δx * Δx) + (Δy * Δy) +} + +type CircleSet []Circle + +// sort.Interface for sorting by radius big to small: +func (s CircleSet) Len() int { return len(s) } +func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } + +func (sp *CircleSet) RemoveContainedC() { + s := *sp + sort.Sort(s) + for i := 0; i < len(s); i++ { + for j := i + 1; j < len(s); { + if s[i].ContainsC(s[j]) { + s[j], s[len(s)-1] = s[len(s)-1], s[j] + s = s[:len(s)-1] + } else { + j++ + } + } + } + *sp = s +} + +func (s CircleSet) Bounds() Rect { + x1 := s[0].X - s[0].R + x2 := s[0].X + s[0].R + y1 := s[0].Y - s[0].R + y2 := s[0].Y + s[0].R + for _, c := range s[1:] { + x1 = math.Min(x1, c.X-c.R) + x2 = math.Max(x2, c.X+c.R) + y1 = math.Min(y1, c.Y-c.R) + y2 = math.Max(y2, c.Y+c.R) + } + return Rect{x1, y1, x2, y2} +} + +var nWorkers = 4 + +func (s CircleSet) UnionArea(ε float64) (min, max float64) { + sort.Sort(s) + stop := make(chan bool) + inside := make(chan Rect) + outside := make(chan Rect) + unknown := make(chan Rect, 5e7) // XXX + + for i := 0; i < nWorkers; i++ { + go s.worker(stop, unknown, inside, outside) + } + r := s.Bounds() + max = r.Area() + unknown <- r + for max-min > ε { + select { + case r = <-inside: + min += r.Area() + case r = <-outside: + max -= r.Area() + } + } + close(stop) + return min, max +} + +func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { + for { + select { + case <-stop: + return + case r := <-unk: + inside, outside := s.CategorizeR(r) + switch { + case inside: + in <- r + case outside: + out <- r + default: + // Split + midX, midY := r.Centre() + unk <- Rect{r.X1, r.Y1, midX, midY} + unk <- Rect{midX, r.Y1, r.X2, midY} + unk <- Rect{r.X1, midY, midX, r.Y2} + unk <- Rect{midX, midY, r.X2, r.Y2} + } + } + } +} + +func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { + anyCorner := false + for _, c := range s { + full, corner := c.ContainsR(r) + if full { + return true, false // inside + } + anyCorner = anyCorner || corner + } + if anyCorner { + return false, false // uncertain + } + for _, c := range s { + if r.ContainsPC(c) { + return false, false // uncertain + } + } + return false, true // outside +} + +func main() { + flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") + maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") + flag.Parse() + + if *maxproc > 0 { + runtime.GOMAXPROCS(*maxproc) + } else { + *maxproc = runtime.GOMAXPROCS(0) + } + + circles := CircleSet{ + NewCircle(1.6417233788, 1.6121789534, 0.0848270516), + NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), + NewCircle(0.6110294452, -0.6907087527, 0.9089162485), + NewCircle(0.3844862411, 0.2923344616, 0.2375743054), + NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), + NewCircle(1.7813504266, 1.6178237031, 0.8162655711), + NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), + NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), + NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), + NewCircle(0.2178372997, -0.9499557344, 0.0357871187), + NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), + NewCircle(1.7952608455, 0.6281269104, 0.2727652452), + NewCircle(1.4168575317, 1.0683357171, 1.1016025378), + NewCircle(1.4637371396, 0.9463877418, 1.1846214562), + NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), + NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), + NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), + NewCircle(1.5293954595, 0.0030278255, 1.2472867347), + NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), + NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), + NewCircle(0.8055826339, -0.0482092025, 0.3327165165), + NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), + NewCircle(1.4685857879, -0.8347049536, 1.3670667538), + NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), + NewCircle(0.0152957411, 0.0638919221, 0.9771215985), + } + fmt.Println("Starting with", len(circles), "circles.") + circles.RemoveContainedC() + fmt.Println("Removing redundant ones leaves", len(circles), "circles.") + fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) + const ε = 0.0001 + min, max := circles.UnionArea(ε) + avg := (min + max) / 2.0 + rng := max - min + fmt.Printf("Area = %v±%v\n", avg, rng) + fmt.Printf("Area ≈ %.*f\n", 5, avg) +} diff --git a/Task/Total-circles-area/Haskell/total-circles-area-1.hs b/Task/Total-circles-area/Haskell/total-circles-area-1.hs new file mode 100644 index 0000000000..900864dd1d --- /dev/null +++ b/Task/Total-circles-area/Haskell/total-circles-area-1.hs @@ -0,0 +1,53 @@ +data Circle = Circle { cx :: Double, cy :: Double, cr :: Double } + +isInside :: Double -> Double -> Circle -> Bool +isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2) + +isInsideAny :: Double -> Double -> [Circle] -> Bool +isInsideAny x y = any (isInside x y) + +approximatedArea :: [Circle] -> Int -> Double +approximatedArea cs box_side = (fromIntegral count) * dx * dy + where + -- compute the bounding box of the circles + x_min = minimum [cx c - cr c | c <- circles] + x_max = maximum [cx c + cr c | c <- circles] + y_min = minimum [cy c - cr c | c <- circles] + y_max = maximum [cy c + cr c | c <- circles] + dx = (x_max - x_min) / (fromIntegral box_side) + dy = (y_max - y_min) / (fromIntegral box_side) + count = length [0 | r <- [0 .. box_side - 1], + c <- [0 .. box_side - 1], + isInsideAny (posx c) (posy r) circles] + posy r = y_min + (fromIntegral r) * dy + posx c = x_min + (fromIntegral c) * dx + +circles :: [Circle] +circles = [Circle ( 1.6417233788) ( 1.6121789534) 0.0848270516, + Circle (-1.4944608174) ( 1.2077959613) 1.1039549836, + Circle ( 0.6110294452) (-0.6907087527) 0.9089162485, + Circle ( 0.3844862411) ( 0.2923344616) 0.2375743054, + Circle (-0.2495892950) (-0.3832854473) 1.0845181219, + Circle ( 1.7813504266) ( 1.6178237031) 0.8162655711, + Circle (-0.1985249206) (-0.8343333301) 0.0538864941, + Circle (-1.7011985145) (-0.1263820964) 0.4776976918, + Circle (-0.4319462812) ( 1.4104420482) 0.7886291537, + Circle ( 0.2178372997) (-0.9499557344) 0.0357871187, + Circle (-0.6294854565) (-1.3078893852) 0.7653357688, + Circle ( 1.7952608455) ( 0.6281269104) 0.2727652452, + Circle ( 1.4168575317) ( 1.0683357171) 1.1016025378, + Circle ( 1.4637371396) ( 0.9463877418) 1.1846214562, + Circle (-0.5263668798) ( 1.7315156631) 1.4428514068, + Circle (-1.2197352481) ( 0.9144146579) 1.0727263474, + Circle (-0.1389358881) ( 0.1092805780) 0.7350208828, + Circle ( 1.5293954595) ( 0.0030278255) 1.2472867347, + Circle (-0.5258728625) ( 1.3782633069) 1.3495508831, + Circle (-0.1403562064) ( 0.2437382535) 1.3804956588, + Circle ( 0.8055826339) (-0.0482092025) 0.3327165165, + Circle (-0.6311979224) ( 0.7184578971) 0.2491045282, + Circle ( 1.4685857879) (-0.8347049536) 1.3670667538, + Circle (-0.6855727502) ( 1.6465021616) 1.0593087096, + Circle ( 0.0152957411) ( 0.0638919221) 0.9771215985] + +main = putStrLn $ "Approximated area: " ++ + (show $ approximatedArea circles 5000) diff --git a/Task/Total-circles-area/Haskell/total-circles-area-2.hs b/Task/Total-circles-area/Haskell/total-circles-area-2.hs new file mode 100644 index 0000000000..526c10472a --- /dev/null +++ b/Task/Total-circles-area/Haskell/total-circles-area-2.hs @@ -0,0 +1,169 @@ +{-# LANGUAGE GeneralizedNewtypeDeriving #-} + +import Data.List (sort) + +data Vec = Vec Double Double + +vCross, vDot :: Vec -> Vec -> Double +vCross (Vec a b) (Vec c d) = a*d - b*c +vDot (Vec a b) (Vec c d) = a*c + b*d + +vAdd, vSub :: Vec -> Vec -> Vec +vAdd (Vec a b) (Vec c d) = Vec (a + c) (b + d) +vSub (Vec a b) (Vec c d) = Vec (a - c) (b - d) + +vLen :: Vec -> Double +vLen x = sqrt $ vDot x x + +vDist :: Vec -> Vec -> Double +vDist a b = vLen (a `vSub` b) + +vScale :: Double -> Vec -> Vec +vScale s (Vec x y) = Vec (x * s) (y * s) + +vNorm :: Vec -> Vec +vNorm v@(Vec x y) = Vec (x / l) (y / l) where l = vLen v + + +newtype Angle = A Double + deriving (Eq, Ord, Num, Fractional) + +aPi = A pi + +vAngle :: Vec -> Angle +vAngle (Vec x y) = A (atan2 y x) + +aNorm :: Angle -> Angle +aNorm a | a > aPi = a - aPi * 2 + | a < -aPi = a + aPi * 2 + | otherwise = a + + +data Circle = Circle Double Double Double + deriving (Eq) + +circleCross :: Circle -> Circle -> [Angle] +circleCross (Circle x0 y0 r0) (Circle x1 y1 r1) + | d >= r0 + r1 || d <= abs(r0 - r1) = [] + | otherwise = map aNorm [ang - da, ang + da] + where + d = vDist (Vec x0 y0) (Vec x1 y1) + s = (r0 + r1 + d) / 2 + a = sqrt $ s * (s - d) * (s - r0) * (s - r1) + h = 2 * a / d + dr = Vec (x1 - x0) (y1 - y0) + dx = vScale (sqrt $ r0 ^ 2 - h ^ 2) $ vNorm dr + ang = if r0 ^ 2 + d ^ 2 > r1 ^ 2 + then vAngle dr + else aPi + vAngle dr + da = A (asin (h / r0)) + + +-- Angles of the start and end points of the circle arc. +data Angle2 = Angle2 Angle Angle + +data Arc = Arc Circle Angle2 + +arcPoint :: Circle -> Angle -> Vec +arcPoint (Circle x y r) (A a) = + vAdd (Vec x y) (Vec (r * cos a) (r * sin a)) + +arcStart, arcMid, arcEnd, arcCenter :: Arc -> Vec +arcStart (Arc c (Angle2 a0 a1)) = arcPoint c a0 +arcMid (Arc c (Angle2 a0 a1)) = arcPoint c ((a0 + a1) / 2) +arcEnd (Arc c (Angle2 a0 a1)) = arcPoint c a1 +arcCenter (Arc (Circle x y r) _) = Vec x y + +arcArea :: Arc -> Double +arcArea (Arc (Circle _ _ r) (Angle2 a0 a1)) = r ^ 2 * aDiff / 2 + where (A aDiff) = a1 - a0 + + +splitCircles :: [Circle] -> [Arc] +splitCircles cs = filter (not . inAnyCircle) arcs where + cSplit :: (Circle, [Angle]) -> [Arc] + cSplit (c, angs) = + zipWith Arc (repeat c) $ zipWith Angle2 angs $ tail angs + + -- If an arc that was part of one circle is inside *another* circle, + -- it will not be part of the zero-winding path, so reject it. + inCircle :: (Vec, Circle) -> Circle -> Bool + inCircle (Vec x0 y0, c1) c2@(Circle x y r) = + c1 /= c2 && vDist (Vec x0 y0) (Vec x y) < r + + f :: Circle -> (Circle, [Angle]) + f c = (c, sort $ [-aPi, aPi] ++ (concatMap (circleCross c) cs)) + cAngs = map f cs + arcs = concatMap cSplit cAngs + + inAnyCircle :: Arc -> Bool + inAnyCircle arc@(Arc c _) = any (inCircle (arcMid arc, c)) cs + + +{- +Given a list of arcs, build sets of closed paths from them. +If one arc's end point is no more than 1e-4 from another's +start point, they are considered connected. Since these +start/end points resulted from intersecting circles earlier, +they *should* be exactly the same, but floating point +precision may cause small differences, hence the 1e-4 error +margin. When there are genuinely different intersections +closer than this margin, the method will backfire, badly. +-} +makePaths :: [Arc] -> [[Arc]] +makePaths arcs = joinArcs [] arcs where + joinArcs :: [Arc] -> [Arc] -> [[Arc]] + joinArcs a [] = [a] + joinArcs [] (x:xs) = joinArcs [x] xs + joinArcs a (x:xs) + | vDist (arcStart (head a)) (arcEnd (last a)) < 1e-4 + = a : joinArcs [] (x:xs) + | vDist (arcEnd (last a)) (arcStart x) < 1e-4 + = joinArcs (a ++ [x]) xs + | otherwise = joinArcs a (xs ++ [x]) + + +pathArea :: [Arc] -> Double +pathArea arcs = a + polylineArea e where + (a, e) = foldl f (0, []) arcs + f (a, e) arc = (a + arcArea arc, e ++ [arcCenter arc, arcEnd arc]) + + +-- Slice N-polygon into N-2 triangles. +polylineArea :: [Vec] -> Double +polylineArea (v:vs) = sum $ zipWith (triArea v) vs (tail vs) + where triArea a b c = ((b `vSub` a) `vCross` (c `vSub` b)) / 2 + + +circlesArea :: [Circle] -> Double +circlesArea = sum . map pathArea . makePaths . splitCircles + + +circles :: [Circle] +circles = [Circle ( 1.6417233788) ( 1.6121789534) 0.0848270516, + Circle (-1.4944608174) ( 1.2077959613) 1.1039549836, + Circle ( 0.6110294452) (-0.6907087527) 0.9089162485, + Circle ( 0.3844862411) ( 0.2923344616) 0.2375743054, + Circle (-0.2495892950) (-0.3832854473) 1.0845181219, + Circle ( 1.7813504266) ( 1.6178237031) 0.8162655711, + Circle (-0.1985249206) (-0.8343333301) 0.0538864941, + Circle (-1.7011985145) (-0.1263820964) 0.4776976918, + Circle (-0.4319462812) ( 1.4104420482) 0.7886291537, + Circle ( 0.2178372997) (-0.9499557344) 0.0357871187, + Circle (-0.6294854565) (-1.3078893852) 0.7653357688, + Circle ( 1.7952608455) ( 0.6281269104) 0.2727652452, + Circle ( 1.4168575317) ( 1.0683357171) 1.1016025378, + Circle ( 1.4637371396) ( 0.9463877418) 1.1846214562, + Circle (-0.5263668798) ( 1.7315156631) 1.4428514068, + Circle (-1.2197352481) ( 0.9144146579) 1.0727263474, + Circle (-0.1389358881) ( 0.1092805780) 0.7350208828, + Circle ( 1.5293954595) ( 0.0030278255) 1.2472867347, + Circle (-0.5258728625) ( 1.3782633069) 1.3495508831, + Circle (-0.1403562064) ( 0.2437382535) 1.3804956588, + Circle ( 0.8055826339) (-0.0482092025) 0.3327165165, + Circle (-0.6311979224) ( 0.7184578971) 0.2491045282, + Circle ( 1.4685857879) (-0.8347049536) 1.3670667538, + Circle (-0.6855727502) ( 1.6465021616) 1.0593087096, + Circle ( 0.0152957411) ( 0.0638919221) 0.9771215985] + +main = print $ circlesArea circles diff --git a/Task/Total-circles-area/J/total-circles-area.j b/Task/Total-circles-area/J/total-circles-area.j new file mode 100644 index 0000000000..a91fea84c7 --- /dev/null +++ b/Task/Total-circles-area/J/total-circles-area.j @@ -0,0 +1,75 @@ +NB. check points on a regular grid within the bounding box + + +N=: 400 NB. grids in each dimension. Controls accuracy. + + +'X Y R'=: |: XYR=: (_&".;._2~ LF&=)0 :0 + 1.6417233788 1.6121789534 0.0848270516 +-1.4944608174 1.2077959613 1.1039549836 + 0.6110294452 -0.6907087527 0.9089162485 + 0.3844862411 0.2923344616 0.2375743054 +-0.2495892950 -0.3832854473 1.0845181219 + 1.7813504266 1.6178237031 0.8162655711 +-0.1985249206 -0.8343333301 0.0538864941 +-1.7011985145 -0.1263820964 0.4776976918 +-0.4319462812 1.4104420482 0.7886291537 + 0.2178372997 -0.9499557344 0.0357871187 +-0.6294854565 -1.3078893852 0.7653357688 + 1.7952608455 0.6281269104 0.2727652452 + 1.4168575317 1.0683357171 1.1016025378 + 1.4637371396 0.9463877418 1.1846214562 +-0.5263668798 1.7315156631 1.4428514068 +-1.2197352481 0.9144146579 1.0727263474 +-0.1389358881 0.1092805780 0.7350208828 + 1.5293954595 0.0030278255 1.2472867347 +-0.5258728625 1.3782633069 1.3495508831 +-0.1403562064 0.2437382535 1.3804956588 + 0.8055826339 -0.0482092025 0.3327165165 +-0.6311979224 0.7184578971 0.2491045282 + 1.4685857879 -0.8347049536 1.3670667538 +-0.6855727502 1.6465021616 1.0593087096 + 0.0152957411 0.0638919221 0.9771215985 +) + +bbox=: (<./@:- , >./@:+)&R +BBOXX=: bbox X +BBOXY=: bbox Y + +grid=: 3 : 0 +'MN MX N'=. y +D=. MX-MN +EDGE=. D%N +(MN(+ -:)EDGE)+(D-EDGE)*(i. % <:)N +) + +assert 2.2 2.6 3 3.4 3.8 -: grid 2 4 5 + +GRIDDED_SAMPLES=: BBOXX {@:;&(grid@:(,&N)) BBOXY + +Note '4 4{.GRIDDED_SAMPLES' NB. example +┌─────────────────┬─────────────────┬─────────────────┬─────────────────┐ +│_2.59706 _2.20043│_2.59706 _2.19774│_2.59706 _2.19505│_2.59706 _2.19236│ +├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ +│_2.59434 _2.20043│_2.59434 _2.19774│_2.59434 _2.19505│_2.59434 _2.19236│ +├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ +│_2.59162 _2.20043│_2.59162 _2.19774│_2.59162 _2.19505│_2.59162 _2.19236│ +├─────────────────┼─────────────────┼─────────────────┼─────────────────┤ +│_2.58891 _2.20043│_2.58891 _2.19774│_2.58891 _2.19505│_2.58891 _2.19236│ +└─────────────────┴─────────────────┴─────────────────┴─────────────────┘ +) +XY=: >,GRIDDED_SAMPLES NB. convert to an usual array of floats. + +mp=: $:~ :(+/ .*) NB. matrix product +assert (*: 5 13) -: (mp"1) 3 4,:5 12 + +in=: *:@:{:@:] >: [: mp (- }:) NB. logical function +assert 0 0 in 1 0 2 NB. X Y in X Y R +assert 0 0 (-.@:in) 44 2 3 + +CONTAINED=: XY in"1/XYR NB. logical table of circles containing each grid +FRACTION=: CONTAINED (+/@:(+./"1)@:[ % *:@:]) N +AREA=: BBOXX*&(-/)BBOXY NB. area of the bounding box. +FRACTION*AREA + +NB. result is 21.5645 diff --git a/Task/Total-circles-area/Julia/total-circles-area.julia b/Task/Total-circles-area/Julia/total-circles-area.julia new file mode 100644 index 0000000000..6ffb7e89bd --- /dev/null +++ b/Task/Total-circles-area/Julia/total-circles-area.julia @@ -0,0 +1,43 @@ +tic() +# +# Size of my grid -- higher values => higher accuracy. +# +ngrid = 10000; + +xc = [1.6417233788 -1.4944608174 0.6110294452 0.3844862411 -0.2495892950 1.7813504266 -0.1985249206 -1.7011985145 -0.4319462812 0.2178372997 -0.6294854565 1.7952608455 1.4168575317 1.4637371396 -0.5263668798 -1.2197352481 -0.1389358881 1.5293954595 -0.5258728625 -0.1403562064 0.8055826339 -0.6311979224 1.4685857879 -0.6855727502 0.0152957411]; +yc = [1.6121789534 1.2077959613 -0.6907087527 0.2923344616 -0.3832854473 1.6178237031 -0.8343333301 -0.1263820964 1.4104420482 -0.9499557344 -1.3078893852 0.6281269104 1.0683357171 0.9463877418 1.7315156631 0.9144146579 0.1092805780 0.0030278255 1.3782633069 0.2437382535 -0.0482092025 0.7184578971 -0.8347049536 1.6465021616 0.0638919221]; +r = [0.0848270516 1.1039549836 0.9089162485 0.2375743054 1.0845181219 0.8162655711 0.0538864941 0.4776976918 0.7886291537 0.0357871187 0.7653357688 0.2727652452 1.1016025378 1.1846214562 1.4428514068 1.0727263474 0.7350208828 1.2472867347 1.3495508831 1.3804956588 0.3327165165 0.2491045282 1.3670667538 1.0593087096 0.9771215985]; +r2 = r .* r; + +ncircles = length(xc); + +# +# Compute the bounding box of the circles. +# +xmin = minimum(xc-r); +xmax = maximum(xc+r); +ymin = minimum(yc-r); +ymax = maximum(yc+r); + +# +# Keep a counter. +# +inside = 0; + +# +# For every point in my grid. +# +for x = linspace(xmin,xmax,ngrid) + for y = linspace(ymin,ymax,ngrid) + if any(r2 .> (x - xc).^2 + (y - yc).^2) + inside = inside + 1; + end + end +end + +box_area = (xmax-xmin) * (ymax-ymin); + +result = box_area * inside / ngrid^2; +toc() + +println(result) diff --git a/Task/Total-circles-area/MATLAB/total-circles-area.m b/Task/Total-circles-area/MATLAB/total-circles-area.m new file mode 100644 index 0000000000..1c1c01489b --- /dev/null +++ b/Task/Total-circles-area/MATLAB/total-circles-area.m @@ -0,0 +1,45 @@ +function res = circles() + +tic +% +% Size of my grid -- higher values => higher accuracy. +% +ngrid = 5000; + +xc = [1.6417233788 -1.4944608174 0.6110294452 0.3844862411 -0.2495892950 1.7813504266 -0.1985249206 -1.7011985145 -0.4319462812 0.2178372997 -0.6294854565 1.7952608455 1.4168575317 1.4637371396 -0.5263668798 -1.2197352481 -0.1389358881 1.5293954595 -0.5258728625 -0.1403562064 0.8055826339 -0.6311979224 1.4685857879 -0.6855727502 0.0152957411]; +yc = [1.6121789534 1.2077959613 -0.6907087527 0.2923344616 -0.3832854473 1.6178237031 -0.8343333301 -0.1263820964 1.4104420482 -0.9499557344 -1.3078893852 0.6281269104 1.0683357171 0.9463877418 1.7315156631 0.9144146579 0.1092805780 0.0030278255 1.3782633069 0.2437382535 -0.0482092025 0.7184578971 -0.8347049536 1.6465021616 0.0638919221]; +r = [0.0848270516 1.1039549836 0.9089162485 0.2375743054 1.0845181219 0.8162655711 0.0538864941 0.4776976918 0.7886291537 0.0357871187 0.7653357688 0.2727652452 1.1016025378 1.1846214562 1.4428514068 1.0727263474 0.7350208828 1.2472867347 1.3495508831 1.3804956588 0.3327165165 0.2491045282 1.3670667538 1.0593087096 0.9771215985]; +r2 = r .* r; + +ncircles = length(xc); + +% +% Compute the bounding box of the circles. +% +xmin = min(xc-r); +xmax = max(xc+r); +ymin = min(yc-r); +ymax = max(yc+r); + +% +% Keep a counter. +% +inside = 0; + +% +% For every point in my grid. +% +for x = linspace(xmin,xmax,ngrid) + for y = linspace(ymin,ymax,ngrid) + if any(r2 > (x - xc).^2 + (y - yc).^2) + inside = inside + 1; + end + end +end + +box_area = (xmax-xmin) * (ymax-ymin); + +res = box_area * inside / ngrid^2; +toc + +end diff --git a/Task/Total-circles-area/Mathematica/total-circles-area-1.math b/Task/Total-circles-area/Mathematica/total-circles-area-1.math new file mode 100644 index 0000000000..20279d3190 --- /dev/null +++ b/Task/Total-circles-area/Mathematica/total-circles-area-1.math @@ -0,0 +1,28 @@ +data = ImportString[" 1.6417233788 1.6121789534 0.0848270516 + -1.4944608174 1.2077959613 1.1039549836 + 0.6110294452 -0.6907087527 0.9089162485 + 0.3844862411 0.2923344616 0.2375743054 + -0.2495892950 -0.3832854473 1.0845181219 + 1.7813504266 1.6178237031 0.8162655711 + -0.1985249206 -0.8343333301 0.0538864941 + -1.7011985145 -0.1263820964 0.4776976918 + -0.4319462812 1.4104420482 0.7886291537 + 0.2178372997 -0.9499557344 0.0357871187 + -0.6294854565 -1.3078893852 0.7653357688 + 1.7952608455 0.6281269104 0.2727652452 + 1.4168575317 1.0683357171 1.1016025378 + 1.4637371396 0.9463877418 1.1846214562 + -0.5263668798 1.7315156631 1.4428514068 + -1.2197352481 0.9144146579 1.0727263474 + -0.1389358881 0.1092805780 0.7350208828 + 1.5293954595 0.0030278255 1.2472867347 + -0.5258728625 1.3782633069 1.3495508831 + -0.1403562064 0.2437382535 1.3804956588 + 0.8055826339 -0.0482092025 0.3327165165 + -0.6311979224 0.7184578971 0.2491045282 + 1.4685857879 -0.8347049536 1.3670667538 + -0.6855727502 1.6465021616 1.0593087096 + 0.0152957411 0.0638919221 0.9771215985", "Table"]; + +toDisk[{x_, y_, r_}] := Disk[{x, y}, r]; +RegionMeasure[RegionUnion[toDisk /@ data]] diff --git a/Task/Total-circles-area/Mathematica/total-circles-area-2.math b/Task/Total-circles-area/Mathematica/total-circles-area-2.math new file mode 100644 index 0000000000..f29df3a790 --- /dev/null +++ b/Task/Total-circles-area/Mathematica/total-circles-area-2.math @@ -0,0 +1 @@ +toDisk[{x_, y_, r_}] := Disk[{Rationalize[x, 0], Rationalize[y, 0]}, Rationalize[r, 0]] diff --git a/Task/Total-circles-area/Perl-6/total-circles-area.pl6 b/Task/Total-circles-area/Perl-6/total-circles-area.pl6 new file mode 100644 index 0000000000..ee867e8641 --- /dev/null +++ b/Task/Total-circles-area/Perl-6/total-circles-area.pl6 @@ -0,0 +1,177 @@ +class Point { + has Real $.x; + has Real $.y; + has Int $!cbits; # bitmap of circle membership + + method cbits { $!cbits //= set_cbits(self) } + method gist { $!x ~ "\t" ~ $!y } +} + +multi infix:(Point $p1, Point $p2) { + sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2; +} + +multi infix:(Point $p1, Point $p2) { + Point.new(x => ($p1.x + $p2.x) / 2, y => ($p1.y + $p2.y) / 2); +} + +class Circle { + has Point $.center; + has Real $.radius; + + has Point $.north = Point.new(x => $!center.x, y => $!center.y + $!radius); + has Point $.west = Point.new(x => $!center.x - $!radius, y => $!center.y); + has Point $.south = Point.new(x => $!center.x, y => $!center.y - $!radius); + has Point $.east = Point.new(x => $!center.x + $!radius, y => $!center.y); + + multi method contains(Circle $c) { $!center to $c.center <= $!radius - $c.radius } + multi method contains(Point $p) { $!center to $p <= $!radius } + method gist { $!center.gist ~ "\t" ~ $.radius } +} + +class Rect { + has Point $.nw; + has Point $.ne; + has Point $.sw; + has Point $.se; + + method diag { $!ne to $!se } + method area { ($!ne.x - $!nw.x) * ($!nw.y - $!sw.y) } + method contains(Point $p) { + $!nw.x < $p.x < $!ne.x and + $!sw.y < $p.y < $!nw.y; + } +} + +my @rawcircles = sort -*.radius, + map -> $x, $y, $radius { Circle.new(:center(Point.new(:$x, :$y)), :$radius) }, + < + 1.6417233788 1.6121789534 0.0848270516 + -1.4944608174 1.2077959613 1.1039549836 + 0.6110294452 -0.6907087527 0.9089162485 + 0.3844862411 0.2923344616 0.2375743054 + -0.2495892950 -0.3832854473 1.0845181219 + 1.7813504266 1.6178237031 0.8162655711 + -0.1985249206 -0.8343333301 0.0538864941 + -1.7011985145 -0.1263820964 0.4776976918 + -0.4319462812 1.4104420482 0.7886291537 + 0.2178372997 -0.9499557344 0.0357871187 + -0.6294854565 -1.3078893852 0.7653357688 + 1.7952608455 0.6281269104 0.2727652452 + 1.4168575317 1.0683357171 1.1016025378 + 1.4637371396 0.9463877418 1.1846214562 + -0.5263668798 1.7315156631 1.4428514068 + -1.2197352481 0.9144146579 1.0727263474 + -0.1389358881 0.1092805780 0.7350208828 + 1.5293954595 0.0030278255 1.2472867347 + -0.5258728625 1.3782633069 1.3495508831 + -0.1403562064 0.2437382535 1.3804956588 + 0.8055826339 -0.0482092025 0.3327165165 + -0.6311979224 0.7184578971 0.2491045282 + 1.4685857879 -0.8347049536 1.3670667538 + -0.6855727502 1.6465021616 1.0593087096 + 0.0152957411 0.0638919221 0.9771215985 + >».Num; + +# remove redundant circles +my @circles; +while @rawcircles { + my $c = @rawcircles.shift; + next if @circles.any.contains($c); + push @circles, $c; +} + +sub set_cbits(Point $p) { + my $cbits = 0; + for @circles Z (1,2,4...*) -> $c, $b { + $cbits += $b if $c.contains($p); + } + $cbits; +} + +my $xmin = [min] @circles.map: { .center.x - .radius } +my $xmax = [max] @circles.map: { .center.x + .radius } +my $ymin = [min] @circles.map: { .center.y - .radius } +my $ymax = [max] @circles.map: { .center.y + .radius } + +my $min-radius = @circles[*-1].radius; + +my $outer-rect = Rect.new: + nw => Point.new(x => $xmin, y => $ymax), + ne => Point.new(x => $xmax, y => $ymax), + sw => Point.new(x => $xmin, y => $ymin), + se => Point.new(x => $xmax, y => $ymin); + +my $outer-area = $outer-rect.area; + +my @unknowns = $outer-rect; +my $known-dry = 0e0; +my $known-wet = 0e0; +my $div = 1; + +# divide current rects each into four rects, analyze each +sub divide(@old) { + + $div *= 2; + + # rects too small to hold circle? + my $smallish = @old[0].diag < $min-radius; + + my @unk; + for @old { + my $center = .nw mid .se; + my $north = .nw mid .ne; + my $south = .sw mid .se; + my $west = .nw mid .sw; + my $east = .ne mid .se; + + for Rect.new(nw => .nw, ne => $north, sw => $west, se => $center), + Rect.new(nw => $north, ne => .ne, sw => $center, se => $east), + Rect.new(nw => $west, ne => $center, sw => .sw, se => $south), + Rect.new(nw => $center, ne => $east, sw => $south, se => .se) + { + my @bits = .nw.cbits, .ne.cbits, .sw.cbits, .se.cbits; + + # if all 4 points wet by same circle, guaranteed wet + if [+&] @bits { + $known-wet += .area; + next; + } + + # if all 4 corners are dry, must check further + if not [+|] @bits and $smallish { + + # check that no circle bulges into this rect + my $ok = True; + for @circles -> $c { + if .contains($c.east) or .contains($c.west) or + .contains($c.north) or .contains($c.south) + { + $ok = False; + last; + } + } + if $ok { + $known-dry += .area; + next; + } + } + push @unk, $_; # dunno yet + } + } + @unk; +} + +my $delta = 0.001; +repeat until my $diff < $delta { + @unknowns = divide(@unknowns); + + $diff = $outer-area - $known-dry - $known-wet; + say 'div: ', $div.fmt('%-5d'), + ' unk: ', (+@unknowns).fmt('%-6d'), + ' est: ', ($known-wet + $diff/2).fmt('%9.6f'), + ' wet: ', $known-wet.fmt('%9.6f'), + ' dry: ', ($outer-area - $known-dry).fmt('%9.6f'), + ' diff: ', $diff.fmt('%9.6f'), + ' error: ', ($diff - @unknowns * @unknowns[0].area).fmt('%e'); +} diff --git a/Task/Total-circles-area/Python/total-circles-area-1.py b/Task/Total-circles-area/Python/total-circles-area-1.py new file mode 100644 index 0000000000..1d3fe61810 --- /dev/null +++ b/Task/Total-circles-area/Python/total-circles-area-1.py @@ -0,0 +1,56 @@ +from collections import namedtuple + +Circle = namedtuple("Circle", "x y r") + +circles = [ + Circle( 1.6417233788, 1.6121789534, 0.0848270516), + Circle(-1.4944608174, 1.2077959613, 1.1039549836), + Circle( 0.6110294452, -0.6907087527, 0.9089162485), + Circle( 0.3844862411, 0.2923344616, 0.2375743054), + Circle(-0.2495892950, -0.3832854473, 1.0845181219), + Circle( 1.7813504266, 1.6178237031, 0.8162655711), + Circle(-0.1985249206, -0.8343333301, 0.0538864941), + Circle(-1.7011985145, -0.1263820964, 0.4776976918), + Circle(-0.4319462812, 1.4104420482, 0.7886291537), + Circle( 0.2178372997, -0.9499557344, 0.0357871187), + Circle(-0.6294854565, -1.3078893852, 0.7653357688), + Circle( 1.7952608455, 0.6281269104, 0.2727652452), + Circle( 1.4168575317, 1.0683357171, 1.1016025378), + Circle( 1.4637371396, 0.9463877418, 1.1846214562), + Circle(-0.5263668798, 1.7315156631, 1.4428514068), + Circle(-1.2197352481, 0.9144146579, 1.0727263474), + Circle(-0.1389358881, 0.1092805780, 0.7350208828), + Circle( 1.5293954595, 0.0030278255, 1.2472867347), + Circle(-0.5258728625, 1.3782633069, 1.3495508831), + Circle(-0.1403562064, 0.2437382535, 1.3804956588), + Circle( 0.8055826339, -0.0482092025, 0.3327165165), + Circle(-0.6311979224, 0.7184578971, 0.2491045282), + Circle( 1.4685857879, -0.8347049536, 1.3670667538), + Circle(-0.6855727502, 1.6465021616, 1.0593087096), + Circle( 0.0152957411, 0.0638919221, 0.9771215985)] + +def main(): + # compute the bounding box of the circles + x_min = min(c.x - c.r for c in circles) + x_max = max(c.x + c.r for c in circles) + y_min = min(c.y - c.r for c in circles) + y_max = max(c.y + c.r for c in circles) + + box_side = 500 + + dx = (x_max - x_min) / box_side + dy = (y_max - y_min) / box_side + + count = 0 + + for r in xrange(box_side): + y = y_min + r * dy + for c in xrange(box_side): + x = x_min + c * dx + if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) + for circle in circles): + count += 1 + + print "Approximated area:", count * dx * dy + +main() diff --git a/Task/Total-circles-area/Python/total-circles-area-2.py b/Task/Total-circles-area/Python/total-circles-area-2.py new file mode 100644 index 0000000000..fbfeeb3562 --- /dev/null +++ b/Task/Total-circles-area/Python/total-circles-area-2.py @@ -0,0 +1,57 @@ +from math import floor, ceil, sqrt + +def area_scan(prec, circs): + def sect((cx, cy, r), y): + dr = sqrt(r ** 2 - (y - cy) ** 2) + return (cx - dr, cx + dr) + + ys = [a[1] + a[2] for a in circs] + [a[1] - a[2] for a in circs] + mins = int(floor(min(ys) / prec)) + maxs = int(ceil(max(ys) / prec)) + + total = 0 + for y in (prec * x for x in xrange(mins, maxs + 1)): + right = -float("inf") + + for (x0, x1) in sorted(sect((cx, cy, r), y) + for (cx, cy, r) in circs + if abs(y - cr) < r): + if x1 <= right: + continue + total += x1 - max(x0, right) + right = x1 + + return total * prec + +def main(): + circles = [ + ( 1.6417233788, 1.6121789534, 0.0848270516), + (-1.4944608174, 1.2077959613, 1.1039549836), + ( 0.6110294452, -0.6907087527, 0.9089162485), + ( 0.3844862411, 0.2923344616, 0.2375743054), + (-0.2495892950, -0.3832854473, 1.0845181219), + ( 1.7813504266, 1.6178237031, 0.8162655711), + (-0.1985249206, -0.8343333301, 0.0538864941), + (-1.7011985145, -0.1263820964, 0.4776976918), + (-0.4319462812, 1.4104420482, 0.7886291537), + ( 0.2178372997, -0.9499557344, 0.0357871187), + (-0.6294854565, -1.3078893852, 0.7653357688), + ( 1.7952608455, 0.6281269104, 0.2727652452), + ( 1.4168575317, 1.0683357171, 1.1016025378), + ( 1.4637371396, 0.9463877418, 1.1846214562), + (-0.5263668798, 1.7315156631, 1.4428514068), + (-1.2197352481, 0.9144146579, 1.0727263474), + (-0.1389358881, 0.1092805780, 0.7350208828), + ( 1.5293954595, 0.0030278255, 1.2472867347), + (-0.5258728625, 1.3782633069, 1.3495508831), + (-0.1403562064, 0.2437382535, 1.3804956588), + ( 0.8055826339, -0.0482092025, 0.3327165165), + (-0.6311979224, 0.7184578971, 0.2491045282), + ( 1.4685857879, -0.8347049536, 1.3670667538), + (-0.6855727502, 1.6465021616, 1.0593087096), + ( 0.0152957411, 0.0638919221, 0.9771215985)] + + p = 1e-3 + print "@stepsize", p, "area = %.4f" % area_scan(p, circles) + +main() diff --git a/Task/Total-circles-area/Python/total-circles-area-3.py b/Task/Total-circles-area/Python/total-circles-area-3.py new file mode 100644 index 0000000000..9b1f5bc328 --- /dev/null +++ b/Task/Total-circles-area/Python/total-circles-area-3.py @@ -0,0 +1,106 @@ +from __future__ import division +from math import sqrt +from itertools import count +from pprint import pprint as pp +try: + from itertools import izip as zip +except: + pass + +# Remove duplicates and sort, largest first. +circles = sorted(set([ + # xcenter ycenter radius + (1.6417233788, 1.6121789534, 0.0848270516), + (-1.4944608174, 1.2077959613, 1.1039549836), + (0.6110294452, -0.6907087527, 0.9089162485), + (0.3844862411, 0.2923344616, 0.2375743054), + (-0.2495892950, -0.3832854473, 1.0845181219), + (1.7813504266, 1.6178237031, 0.8162655711), + (-0.1985249206, -0.8343333301, 0.0538864941), + (-1.7011985145, -0.1263820964, 0.4776976918), + (-0.4319462812, 1.4104420482, 0.7886291537), + (0.2178372997, -0.9499557344, 0.0357871187), + (-0.6294854565, -1.3078893852, 0.7653357688), + (1.7952608455, 0.6281269104, 0.2727652452), + (1.4168575317, 1.0683357171, 1.1016025378), + (1.4637371396, 0.9463877418, 1.1846214562), + (-0.5263668798, 1.7315156631, 1.4428514068), + (-1.2197352481, 0.9144146579, 1.0727263474), + (-0.1389358881, 0.1092805780, 0.7350208828), + (1.5293954595, 0.0030278255, 1.2472867347), + (-0.5258728625, 1.3782633069, 1.3495508831), + (-0.1403562064, 0.2437382535, 1.3804956588), + (0.8055826339, -0.0482092025, 0.3327165165), + (-0.6311979224, 0.7184578971, 0.2491045282), + (1.4685857879, -0.8347049536, 1.3670667538), + (-0.6855727502, 1.6465021616, 1.0593087096), + (0.0152957411, 0.0638919221, 0.9771215985), + ]), key=lambda x: -x[-1]) + +def vdcgen(base=2): + 'Van der Corput sequence generator' + for n in count(): + vdc, denom = 0,1 + while n: + denom *= base + n, remainder = divmod(n, base) + vdc += remainder / denom + yield vdc + +def vdc_2d(): + 'Two dimensional Van der Corput sequence generator' + for x, y in zip(vdcgen(base=2), vdcgen(base=3)): + yield x, y + +def bounding_box(circles): + 'Return minx, maxx, miny, maxy' + return (min(x - r for x,y,r in circles), + max(x + r for x,y,r in circles), + min(y - r for x,y,r in circles), + max(y + r for x,y,r in circles) + ) +def circle_is_in_circle(c1, c2): + x1, y1, r1 = c1 + x2, y2, r2 = c2 + return sqrt((x2 - x1)**2 + (y2 - y1)**2) <= r1 - r2 + +def remove_covered_circles(circles): + 'Takes circles in decreasing radius order. Removes those covered by others' + covered = [] + for i, c1 in enumerate(circles): + eliminate = [c2 for c2 in circles[i+1:] + if circle_is_in_circle(c1, c2)] + if eliminate: covered += [c1, eliminate] + for c in eliminate: circles.remove(c) + #pp(covered) + +def main(circles): + print('Originally %i circles' % len(circles)) + print('Bounding box: %r' % (bounding_box(circles),)) + remove_covered_circles(circles) + print(' down to %i due to some being wholly covered by others' % len(circles)) + minx, maxx, miny, maxy = bounding_box(circles) + # Shift to 0,0 and compute r**2 once + circles2 = [(x - minx, y - miny, r*r) for x, y, r in circles] + scalex, scaley = abs(maxx - minx), abs(maxy - miny) + pcount, inside, last = 0, 0, '' + for px, py in vdc_2d(): + pcount += 1 + px *= scalex; py *= scaley + if any((px-cx)**2 + (py-cy)**2 <= cr2 for cx, cy, cr2 in circles2): + inside += 1 + if not pcount % 100000: + area = (inside/pcount) * scalex * scaley + print('Points: %8i, Area estimate: %r' + % (pcount, area)) + # Hack to check if precision OK + this = '%.4f' % area + if this == last: + break + else: + last = this + print('The value has settled to %s' % this) + + +if __name__ == '__main__': + main(circles) diff --git a/Task/Total-circles-area/Python/total-circles-area-4.py b/Task/Total-circles-area/Python/total-circles-area-4.py new file mode 100644 index 0000000000..400e40b0cc --- /dev/null +++ b/Task/Total-circles-area/Python/total-circles-area-4.py @@ -0,0 +1,158 @@ +from collections import namedtuple +from functools import partial +from itertools import repeat, imap, izip +from decimal import Decimal, getcontext + +# Requires the egg: https://pypi.python.org/pypi/dmath/ +from dmath import atan2, asin, sin, cos, pi as piCompute + +getcontext().prec = 40 # Set FP precision. +sqrt = Decimal.sqrt +pi = piCompute() +D2 = Decimal(2) + +Vec = namedtuple("Vec", "x y") +vcross = lambda (a, b), (c, d): a*d - b*c +vdot = lambda (a, b), (c, d): a*c + b*d +vadd = lambda (a, b), (c, d): Vec(a + c, b + d) +vsub = lambda (a, b), (c, d): Vec(a - c, b - d) +vlen = lambda x: sqrt(vdot(x, x)) +vdist = lambda a, b: vlen(vsub(a, b)) +vscale = lambda s, (x, y): Vec(x * s, y * s) + +def vnorm(v): + l = vlen(v) + return Vec(v.x / l, v.y / l) + +vangle = lambda (x, y): atan2(y, x) + +def anorm(a): + if a > pi: return a - pi * D2 + if a < -pi: return a + pi * D2 + return a + +Circle = namedtuple("Circle", "x y r") + +def circle_cross((x0, y0, r0), (x1, y1, r1)): + d = vdist(Vec(x0, y0), Vec(x1, y1)) + if d >= r0 + r1 or d <= abs(r0 - r1): + return [] + + s = (r0 + r1 + d) / D2 + a = sqrt(s * (s - d) * (s - r0) * (s - r1)) + h = D2 * a / d + dr = Vec(x1 - x0, y1 - y0) + dx = vscale(sqrt(r0 ** 2 - h ** 2), vnorm(dr)) + ang = vangle(dr) if \ + r0 ** 2 + d ** 2 > r1 ** 2 \ + else pi + vangle(dr) + da = asin(h / r0) + return map(anorm, [ang - da, ang + da]) + +# Angles of the start and end points of the circle arc. +Angle2 = namedtuple("Angle2", "a1 a2") + +Arc = namedtuple("Arc", "c aa") + +arcPoint = lambda (x, y, r), a: \ + vadd(Vec(x, y), Vec(r * cos(a), r * sin(a))) + +arc_start = lambda (c, (a0, a1)): arcPoint(c, a0) +arc_mid = lambda (c, (a0, a1)): arcPoint(c, (a0 + a1) / D2) +arc_end = lambda (c, (a0, a1)): arcPoint(c, a1) +arc_center = lambda ((x, y, r), _): Vec(x, y) + +arc_area = lambda ((_0, _1, r), (a0, a1)): r ** 2 * (a1 - a0) / D2 + +def split_circles(cs): + cSplit = lambda (c, angs): \ + imap(Arc, repeat(c), imap(Angle2, angs, angs[1:])) + + # If an arc that was part of one circle is inside *another* circle, + # it will not be part of the zero-winding path, so reject it. + in_circle = lambda ((x0, y0), c), (x, y, r): \ + c != Circle(x, y, r) and vdist(Vec(x0, y0), Vec(x, y)) < r + + def in_any_circle(arc): + return any(in_circle((arc_mid(arc), arc.c), c) for c in cs) + + concat_map = lambda f, xs: [y for x in xs for y in f(x)] + + f = lambda c: \ + (c, sorted([-pi, pi] + + concat_map(partial(circle_cross, c), cs))) + cAngs = map(f, cs) + arcs = concat_map(cSplit, cAngs) + return filter(lambda ar: not in_any_circle(ar), arcs) + +# Given a list of arcs, build sets of closed paths from them. +# If one arc's end point is no more than 1e-4 from another's +# start point, they are considered connected. Since these +# start/end points resulted from intersecting circles earlier, +# they *should* be exactly the same, but floating point +# precision may cause small differences, hence the 1e-4 error +# margin. When there are genuinely different intersections +# closer than this margin, the method will backfire, badly. +def make_paths(arcs): + eps = Decimal("0.0001") + def join_arcs(a, xxs): + if not xxs: + return [a] + x, xs = xxs[0], xxs[1:] + if not a: + return join_arcs([x], xs) + if vdist(arc_start(a[0]), arc_end(a[-1])) < eps: + return [a] + join_arcs([], xxs) + if vdist(arc_end(a[-1]), arc_start(x)) < eps: + return join_arcs(a + [x], xs) + return join_arcs(a, xs + [x]) + return join_arcs([], arcs) + +# Slice N-polygon into N-2 triangles. +def polyline_area(vvs): + tri_area = lambda a, b, c: vcross(vsub(b, a), vsub(c, b)) / D2 + v, vs = vvs[0], vvs[1:] + return sum(tri_area(v, v1, v2) for v1, v2 in izip(vs, vs[1:])) + +def path_area(arcs): + f = lambda (a, e), arc: \ + (a + arc_area(arc), e + [arc_center(arc), arc_end(arc)]) + (a, e) = reduce(f, arcs, (0, [])) + return a + polyline_area(e) + +circles_area = lambda cs: \ + sum(imap(path_area, make_paths(split_circles(cs)))) + +def main(): + raw_circles = """\ + 1.6417233788 1.6121789534 0.0848270516 + -1.4944608174 1.2077959613 1.1039549836 + 0.6110294452 -0.6907087527 0.9089162485 + 0.3844862411 0.2923344616 0.2375743054 + -0.2495892950 -0.3832854473 1.0845181219 + 1.7813504266 1.6178237031 0.8162655711 + -0.1985249206 -0.8343333301 0.0538864941 + -1.7011985145 -0.1263820964 0.4776976918 + -0.4319462812 1.4104420482 0.7886291537 + 0.2178372997 -0.9499557344 0.0357871187 + -0.6294854565 -1.3078893852 0.7653357688 + 1.7952608455 0.6281269104 0.2727652452 + 1.4168575317 1.0683357171 1.1016025378 + 1.4637371396 0.9463877418 1.1846214562 + -0.5263668798 1.7315156631 1.4428514068 + -1.2197352481 0.9144146579 1.0727263474 + -0.1389358881 0.1092805780 0.7350208828 + 1.5293954595 0.0030278255 1.2472867347 + -0.5258728625 1.3782633069 1.3495508831 + -0.1403562064 0.2437382535 1.3804956588 + 0.8055826339 -0.0482092025 0.3327165165 + -0.6311979224 0.7184578971 0.2491045282 + 1.4685857879 -0.8347049536 1.3670667538 + -0.6855727502 1.6465021616 1.0593087096 + 0.0152957411 0.0638919221 0.9771215985""".splitlines() + + circles = [Circle(*imap(Decimal, row.split())) + for row in raw_circles] + print "Total Area:", circles_area(circles) + +main() diff --git a/Task/Total-circles-area/README b/Task/Total-circles-area/README new file mode 100644 index 0000000000..0fe3094591 --- /dev/null +++ b/Task/Total-circles-area/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Total_circles_area diff --git a/Task/Total-circles-area/REXX/total-circles-area-1.rexx b/Task/Total-circles-area/REXX/total-circles-area-1.rexx new file mode 100644 index 0000000000..49ad8b483e --- /dev/null +++ b/Task/Total-circles-area/REXX/total-circles-area-1.rexx @@ -0,0 +1,49 @@ +/*REXX pgm calculates the total area of (possibly overlapping) circles. */ +parse arg box . /*obtain possible #boxes from CL.*/ +if box=='' then box=500 /*allow specification of # boxes.*/ +numeric digits 15 /*ensure enough digits for points*/ + data = ' 1.6417233788 1.6121789534 0.0848270516', + '-1.4944608174 1.2077959613 1.1039549836', + ' 0.6110294452 -0.6907087527 0.9089162485', + ' 0.3844862411 0.2923344616 0.2375743054', + '-0.2495892950 -0.3832854473 1.0845181219', + ' 1.7813504266 1.6178237031 0.8162655711', + '-0.1985249206 -0.8343333301 0.0538864941', + '-1.7011985145 -0.1263820964 0.4776976918', + '-0.4319462812 1.4104420482 0.7886291537', + ' 0.2178372997 -0.9499557344 0.0357871187', + '-0.6294854565 -1.3078893852 0.7653357688', + ' 1.7952608455 0.6281269104 0.2727652452', + ' 1.4168575317 1.0683357171 1.1016025378', + ' 1.4637371396 0.9463877418 1.1846214562', + '-0.5263668798 1.7315156631 1.4428514068', + '-1.2197352481 0.9144146579 1.0727263474', + '-0.1389358881 0.1092805780 0.7350208828', + ' 1.5293954595 0.0030278255 1.2472867347', + '-0.5258728625 1.3782633069 1.3495508831', + '-0.1403562064 0.2437382535 1.3804956588', + ' 0.8055826339 -0.0482092025 0.3327165165', + '-0.6311979224 0.7184578971 0.2491045282', + ' 1.4685857879 -0.8347049536 1.3670667538', + '-0.6855727502 1.6465021616 1.0593087096', + ' 0.0152957411 0.0638919221 0.9771215985' +circles=words(data)%3 /* ══x══ ══y══ ══radius══ */ +parse var data minX minY . 1 maxX maxY . /*assign some min & max vals.*/ + do j=1 for circles; _=j*3-2 /*assign circles with datam. */ + @x.j=word(data,_); @y.j=word(data,_+1) + @r.j=word(data,_+2); @rr.j=@r.j**2 + minX=min(minX, @x.j-@r.j); maxX=max(maxX, @x.j+@r.j) + minY=min(minY, @y.j-@r.j); maxY=max(maxY, @y.j+@r.j) + end /*j*/ +dx=(maxX-minX) / box +dy=(maxY-minY) / box +#=0 /*count of sample points. */ + do row=0 to box; y=minY+row*dy /*process the grid rows. */ + do col=0 to box; x=minX+col*dx /*process the grid cols. */ + do k=1 for circles /*now process each circle. */ + if (x-@x.k)**2+(y-@y.k)**2 <= @rr.k then do; #=#+1; leave; end + end /*k*/ + end /*col*/ + end /*row*/ + /*stick a fork in it, we're done.*/ +say 'The approximate area is: ' #*dx*dy " using" box**2 "points." diff --git a/Task/Total-circles-area/REXX/total-circles-area-2.rexx b/Task/Total-circles-area/REXX/total-circles-area-2.rexx new file mode 100644 index 0000000000..452073d723 --- /dev/null +++ b/Task/Total-circles-area/REXX/total-circles-area-2.rexx @@ -0,0 +1,83 @@ +/*REXX pgm calculates the total area of (possibly overlapping) circles. */ +parse arg box . /*obtain possible #boxes from CL.*/ +if box=='' then box=-500 /*allow specification of # boxes,*/ +verbose= box<0 /*set a flag if in verbose mode. */ +box=abs(box); boxen=box+1 /*use |box| value from here on.*/ +numeric digits 15 /*ensure enough digits for points*/ + data = ' 1.6417233788 1.6121789534 0.0848270516', + '-1.4944608174 1.2077959613 1.1039549836', + ' 0.6110294452 -0.6907087527 0.9089162485', + ' 0.3844862411 0.2923344616 0.2375743054', + '-0.2495892950 -0.3832854473 1.0845181219', + ' 1.7813504266 1.6178237031 0.8162655711', + '-0.1985249206 -0.8343333301 0.0538864941', + '-1.7011985145 -0.1263820964 0.4776976918', + '-0.4319462812 1.4104420482 0.7886291537', + ' 0.2178372997 -0.9499557344 0.0357871187', + '-0.6294854565 -1.3078893852 0.7653357688', + ' 1.7952608455 0.6281269104 0.2727652452', + ' 1.4168575317 1.0683357171 1.1016025378', + ' 1.4637371396 0.9463877418 1.1846214562', + '-0.5263668798 1.7315156631 1.4428514068', + '-1.2197352481 0.9144146579 1.0727263474', + '-0.1389358881 0.1092805780 0.7350208828', + ' 1.5293954595 0.0030278255 1.2472867347', + '-0.5258728625 1.3782633069 1.3495508831', + '-0.1403562064 0.2437382535 1.3804956588', + ' 0.8055826339 -0.0482092025 0.3327165165', + '-0.6311979224 0.7184578971 0.2491045282', + ' 1.4685857879 -0.8347049536 1.3670667538', + '-0.6855727502 1.6465021616 1.0593087096', + ' 0.0152957411 0.0638919221 0.9771215985' +circles=words(data)%3 /* ══x══ ══y══ ══radius══ */ +if verbose then say 'There are' circles "circles." +parse var data minX minY . 1 maxX maxY . /*assign some min & max vals.*/ + + do j=1 for circles; _=j*3-2 /*assign circles with datam. */ + @x.j=word(data,_); @y.j=word(data,_+1) + @r.j=word(data,_+2)/1; @rr.j=@r.j**2 + minX=min(minX, @x.j-@r.j); maxX=max(maxX, @x.j+@r.j) + minY=min(minY, @y.j-@r.j); maxY=max(maxY, @y.j+@r.j) + end /*j*/ + + do m=1 for circles /*sort the circles by radii. */ + do n=m+1 to circles /*sort by descending radii. */ + if @r.n>@r.m then parse value @x.n @y.n @r.n @x.m @y.m @r.m with, + @x.m @y.m @r.m @x.n @y.n @r.n + end /*n*/ /* [↑] Higher? Then swap.*/ + end /*m*/ + +dx=(maxX-minX) / box +dy=(maxY-minY) / box +w=length(circles); #in=0 /*#in►fully contained circles*/ +isIn@ = ' is contained in circle ' /* [↓] find contained circles*/ + + do j=1 for circles /*traipse through J circles*/ + do k=1 for circles /* " " K " */ + if k==j | @r.j==0 then iterate /*ignore self or zero radius.*/ + if @y.j+@r.j > @y.k+@r.k then iterate /*is cir J outside cir K?*/ + if @x.j-@r.j < @x.k-@r.k then iterate /* " " " " " " */ + if @y.j-@r.j < @y.k-@r.k then iterate /* " " " " " " */ + if @x.j+@r.j > @x.k+@r.k then iterate /* " " " " " " */ + if verbose then say 'Circle ' right(j,w) isIn@ right(k,w) + @r.j=0; #in=#in+1 /*elide this circle; bump #in*/ + end /*k*/ + end /*j*/ /* [↑] elided overlapping cir*/ + +if #in==0 then #in='no' /*use gooder English. (joke)*/ +if verbose then say #in "circles are fully contained within other circles." +nC=0 /*number of "new" circles. */ + do n=1 for circles; if @r.n==0 then iterate /*skip if 0.*/ + nC=nC+1; @x.nC=@x.n; @y.nC=@y.n; @r.nC=@r.n; @rr.nC=@r.n**2 + end /*n*/ /* [↑] elide overlapping cir*/ +#=0 /*the count of sample points.*/ + do row=0 for boxen; y=minY+row*dy /*process each grid row. */ + do col=0 for boxen; x=minX+col*dx /* " " " column. */ + do k=1 for nC /*now process each new circle*/ + if (x-@x.k)**2+(y-@y.k)**2 <= @rr.k then do; #=#+1; leave; end + end /*k*/ + end /*col*/ + end /*row*/ +say +say 'The approximate area is: ' #*dx*dy " using" box**2 "points." + /*stick a fork in it, we're done.*/ diff --git a/Task/Total-circles-area/Ruby/total-circles-area-1.rb b/Task/Total-circles-area/Ruby/total-circles-area-1.rb new file mode 100644 index 0000000000..03346a77e7 --- /dev/null +++ b/Task/Total-circles-area/Ruby/total-circles-area-1.rb @@ -0,0 +1,51 @@ +circles = [ + [ 1.6417233788, 1.6121789534, 0.0848270516], + [-1.4944608174, 1.2077959613, 1.1039549836], + [ 0.6110294452, -0.6907087527, 0.9089162485], + [ 0.3844862411, 0.2923344616, 0.2375743054], + [-0.2495892950, -0.3832854473, 1.0845181219], + [ 1.7813504266, 1.6178237031, 0.8162655711], + [-0.1985249206, -0.8343333301, 0.0538864941], + [-1.7011985145, -0.1263820964, 0.4776976918], + [-0.4319462812, 1.4104420482, 0.7886291537], + [ 0.2178372997, -0.9499557344, 0.0357871187], + [-0.6294854565, -1.3078893852, 0.7653357688], + [ 1.7952608455, 0.6281269104, 0.2727652452], + [ 1.4168575317, 1.0683357171, 1.1016025378], + [ 1.4637371396, 0.9463877418, 1.1846214562], + [-0.5263668798, 1.7315156631, 1.4428514068], + [-1.2197352481, 0.9144146579, 1.0727263474], + [-0.1389358881, 0.1092805780, 0.7350208828], + [ 1.5293954595, 0.0030278255, 1.2472867347], + [-0.5258728625, 1.3782633069, 1.3495508831], + [-0.1403562064, 0.2437382535, 1.3804956588], + [ 0.8055826339, -0.0482092025, 0.3327165165], + [-0.6311979224, 0.7184578971, 0.2491045282], + [ 1.4685857879, -0.8347049536, 1.3670667538], + [-0.6855727502, 1.6465021616, 1.0593087096], + [ 0.0152957411, 0.0638919221, 0.9771215985], +] + +def minmax_circle(circles) + xmin = circles.map {|xc, yc, radius| xc - radius}.min + xmax = circles.map {|xc, yc, radius| xc + radius}.max + ymin = circles.map {|xc, yc, radius| yc - radius}.min + ymax = circles.map {|xc, yc, radius| yc + radius}.max + [xmin, xmax, ymin, ymax] +end + +# remove internal circle +def select_circle(circles) + circles = circles.sort_by{|cx,cy,r| -r} + size = circles.size + select = [*0...size] + for i in 0...size-1 + xi,yi,ri = circles[i].to_a + for j in i+1...size + xj,yj,rj = circles[j].to_a + select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2 + end + end + circles.values_at(*select) +end +circles = select_circle(circles) diff --git a/Task/Total-circles-area/Ruby/total-circles-area-2.rb b/Task/Total-circles-area/Ruby/total-circles-area-2.rb new file mode 100644 index 0000000000..4b75f973cf --- /dev/null +++ b/Task/Total-circles-area/Ruby/total-circles-area-2.rb @@ -0,0 +1,30 @@ +def grid_sample(circles, box_side=500) + # compute the bounding box of the circles + xmin, xmax, ymin, ymax = minmax_circle(circles) + + dx = (xmax - xmin) / box_side + dy = (ymax - ymin) / box_side + + circle2 = circles.map{|cx,cy,r| [cx,cy,r*r]} + include = ->(x,y){circle2.any?{|cx, cy, r2| (x-cx)**2 + (y-cy)**2 < r2}} + count = 0 + + box_side.times do |r| + y = ymin + r * dy + box_side.times do |c| + x = xmin + c * dx + count += 1 if include[x,y] + end + end + #puts box_side => "Approximated area:#{count * dx * dy}" + count * dx * dy +end + +puts "Grid Sample" +n = 500 +2.times do + t0 = Time.now + puts "Approximated area:#{grid_sample(circles, n)} (#{n} grid)" + n *= 2 + puts "#{Time.now - t0} sec" +end diff --git a/Task/Total-circles-area/Ruby/total-circles-area-3.rb b/Task/Total-circles-area/Ruby/total-circles-area-3.rb new file mode 100644 index 0000000000..42ec33ffbb --- /dev/null +++ b/Task/Total-circles-area/Ruby/total-circles-area-3.rb @@ -0,0 +1,31 @@ +def area_scan(prec, circles) + sect = ->(y) do + circles.select{|cx,cy,r| (y - cy).abs < r}.map do |cx,cy,r| + dr = Math.sqrt(r ** 2 - (y - cy) ** 2) + [cx - dr, cx + dr] + end + end + xmin, xmax, ymin, ymax = minmax_circle(circles) + ymin = (ymin / prec).floor + ymax = (ymax / prec).ceil + + total = 0 + for y in ymin..ymax + y *= prec + right = xmin + for x0, x1 in sect[y].sort + next if x1 <= right + total += x1 - [x0, right].max + right = x1 + end + end + total * prec +end + +puts "Scanline Method" +prec = 1e-2 +3.times do + t0 = Time.now + puts "%8.6f : %12.9f, %p sec" % [prec, area_scan(prec, circles), Time.now-t0] + prec /= 10 +end diff --git a/Task/Total-circles-area/Tcl/total-circles-area.tcl b/Task/Total-circles-area/Tcl/total-circles-area.tcl new file mode 100644 index 0000000000..0aeb32e4cb --- /dev/null +++ b/Task/Total-circles-area/Tcl/total-circles-area.tcl @@ -0,0 +1,110 @@ +set circles { + 1.6417233788 1.6121789534 0.0848270516 + -1.4944608174 1.2077959613 1.1039549836 + 0.6110294452 -0.6907087527 0.9089162485 + 0.3844862411 0.2923344616 0.2375743054 + -0.2495892950 -0.3832854473 1.0845181219 + 1.7813504266 1.6178237031 0.8162655711 + -0.1985249206 -0.8343333301 0.0538864941 + -1.7011985145 -0.1263820964 0.4776976918 + -0.4319462812 1.4104420482 0.7886291537 + 0.2178372997 -0.9499557344 0.0357871187 + -0.6294854565 -1.3078893852 0.7653357688 + 1.7952608455 0.6281269104 0.2727652452 + 1.4168575317 1.0683357171 1.1016025378 + 1.4637371396 0.9463877418 1.1846214562 + -0.5263668798 1.7315156631 1.4428514068 + -1.2197352481 0.9144146579 1.0727263474 + -0.1389358881 0.1092805780 0.7350208828 + 1.5293954595 0.0030278255 1.2472867347 + -0.5258728625 1.3782633069 1.3495508831 + -0.1403562064 0.2437382535 1.3804956588 + 0.8055826339 -0.0482092025 0.3327165165 + -0.6311979224 0.7184578971 0.2491045282 + 1.4685857879 -0.8347049536 1.3670667538 + -0.6855727502 1.6465021616 1.0593087096 + 0.0152957411 0.0638919221 0.9771215985 +} + +proc init {} { + upvar 1 circles circles + set xMin [set yMin inf] + set xMax [set yMax -inf] + set i -1 + foreach {xc yc rad} $circles { + set xMin [expr {min($xMin, $xc-$rad)}] + set xMax [expr {max($xMax, $xc+$rad)}] + set yMin [expr {min($yMin, $yc-$rad)}] + set yMax [expr {max($yMax, $yc+$rad)}] + lset circles [incr i 3] [expr {$rad**2}] + } + return [list $xMin $xMax $yMin $yMax] +} + +proc sampleGrid {circles steps} { + lassign [init] xMin xMax yMin yMax + set dx [expr {($xMax-$xMin)/$steps}] + set dy [expr {($yMax-$yMin)/$steps}] + set n 0 + for {set i 0} {$i < $steps} {incr i} { + set x [expr {$xMin + $i * $dx}] + for {set j 0} {$j < $steps} {incr j} { + set y [expr {$yMin + $j * $dy}] + foreach {xc yc rad2} $circles { + if {($x-$xc)**2 + ($y-$yc)**2 <= $rad2} { + incr n + break + } + } + } + } + return [expr {$dx * $dy * $n}] +} + +proc sampleMC {circles samples} { + lassign [init] xMin xMax yMin yMax + set n 0 + for {set i 0} {$i < $samples} {incr i} { + set x [expr {$xMin+rand()*($xMax-$xMin)}] + set y [expr {$yMin+rand()*($yMax-$yMin)}] + foreach {xc yc rad2} $circles { + if {($x-$xc)**2 + ($y-$yc)**2 <= $rad2} { + incr n + break + } + } + } + return [expr {($xMax-$xMin) * ($yMax-$yMin) * $n / $samples}] +} + +proc samplePerturb {circles steps votes} { + lassign [init] xMin xMax yMin yMax + set dx [expr {($xMax-$xMin)/$steps}] + set dy [expr {($yMax-$yMin)/$steps}] + set n 0 + for {set i 0} {$i < $steps} {incr i} { + set x [expr {$xMin + $i * $dx}] + for {set j 0} {$j < $steps} {incr j} { + set y [expr {$yMin + $j * $dy}] + foreach {xc yc rad2} $circles { + set in 0 + for {set v 0} {$v < $votes} {incr v} { + set xr [expr {$x + (rand()-0.5)*$dx}] + set yr [expr {$y + (rand()-0.5)*$dy}] + if {($xr-$xc)**2 + ($yr-$yc)**2 <= $rad2} { + incr in + } + } + if {$in*2 >= $votes} { + incr n + break + } + } + } + } + return [expr {$dx * $dy * $n}] +} + +puts [format "estimated area (grid): %.4f" [sampleGrid $circles 500]] +puts [format "estimated area (monte carlo): %.2f" [sampleMC $circles 1000000]] +puts [format "estimated area (perturbed sample): %.4f" [samplePerturb $circles 500 5]] diff --git a/Task/Ulam-spiral--for-primes-/00DESCRIPTION b/Task/Ulam-spiral--for-primes-/00DESCRIPTION new file mode 100644 index 0000000000..9d19e5624b --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/00DESCRIPTION @@ -0,0 +1,101 @@ +An Ulam spiral (of primes numbers) is a method of visualizing prime numbers when expressed in a (normally counter-clockwise) outward spiral (usually starting at '''1'''), constructed on a square grid, starting at the "center". + +An Ulam spiral is also known as a ''prime spiral''. + +The first grid (green) is shown with all numbers (primes and non-primes) shown, starting at '''1'''. + +In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot), and all non-primes as shown as a blank (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables). + +Normally, the spiral starts in the "center", and the 2nd number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the 2nd number) is viewed upwards from the 1st number instead of to the right, but that is just a matter of orientation. + +Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities). + + + +{| class="wikitable" style="float:center;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%" +|- +| '''65''' || '''64''' || '''63''' || '''62''' || '''61''' || '''60''' || '''59''' || '''58''' || '''57''' +|-> +| '''66''' || '''37''' || '''36''' || '''35''' || '''34''' || '''33''' || '''32''' || '''31''' || '''56''' +|- +| '''67''' || '''38''' || '''17''' || '''16''' || '''15''' || '''14''' || '''13''' || '''30''' || '''55''' +|- +| '''68''' || '''39''' || '''18''' || ''' 5''' || ''' 4''' || ''' 3''' || '''12''' || '''29''' || '''54''' +|- +| '''69''' || '''40''' || '''19''' || ''' 6''' || ''' 1''' || ''' 2''' || '''11''' || '''28''' || '''53''' +|- +| '''70''' || '''41''' || '''20''' || ''' 7''' || ''' 8''' || ''' 9''' || '''10''' || '''27''' || '''52''' +|- +| '''71''' || '''42''' || '''21''' || '''22''' || '''23''' || '''24''' || '''25''' || '''26''' || '''51''' +|- +| '''72''' || '''43''' || '''44''' || '''45''' || '''46''' || '''47''' || '''48''' || '''49''' || '''50''' +|- +| '''73''' || '''74''' || '''75''' || '''76''' || '''77''' || '''78''' || '''79''' || '''80''' || '''81''' +|} + + +[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)]. + + +Then, to show the Ulam prime spiral, a character (or glyph) is shown instead of each prime number, and a blank for all non-prime numbers. In the orange grid below, the prime numbers are left intact to see what numbers are to be changed to the character for viewing. + + + +{| class="wikitable" style="float:center;border: 4px solid blue; background:orange; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%" +|- +| ''' ''' || ''' ''' || ''' ''' || ''' ''' || '''61''' || ''' ''' || '''59''' || ''' ''' || ''' ''' +|- +| ''' ''' || '''37''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || '''31''' || ''' ''' +|- +| '''67''' || ''' ''' || '''17''' || ''' ''' || ''' ''' || ''' ''' || '''13''' || ''' ''' || ''' ''' +|- +| ''' ''' || ''' ''' || ''' ''' || ''' 5''' || ''' ''' || ''' 3''' || ''' ''' || '''29''' || ''' ''' +|- +| ''' ''' || ''' ''' || '''19''' || ''' ''' || ''' ''' || ''' 2''' || '''11''' || ''' ''' || '''53''' +|- +| ''' ''' || '''41''' || ''' ''' || ''' 7''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' +|- +| '''71''' || ''' ''' || ''' ''' || ''' ''' || '''23''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' +|- +| ''' ''' || '''43''' || ''' ''' || ''' ''' || ''' ''' || '''47''' || ''' ''' || ''' ''' || ''' ''' +|- +| '''73''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || '''79''' || ''' ''' || ''' ''' +|} + + + +Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a or some other suitable glyph. + +{| class="wikitable" style="float:center;border: 4px solid blue; background:yellow; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%" +|- +| ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' +|- +| ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' +|- +| ''' ∙''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' +|- +| ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ∙''' || ''' ''' +|- +| ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ∙''' || ''' ''' || ''' ∙''' +|- +| ''' ''' || ''' ∙''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' +|- +| ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' +|- +| ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' || ''' ''' +|- +| ''' ∙''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ''' || ''' ∙''' || ''' ''' || ''' ''' +|} + + +;Task + +For any sized '''N x N''' grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be '''1'''), with some suitably dotty representation to indicate primes, and the absence of dots to indicate non-primes. + +You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen. + +;Also see: +::* Wikipedia entry: [http://en.wikipedia.org/wiki/Ulam_spiral Ulam spiral]. +::* MathWorld™ entry: [http://mathworld.wolfram.com/PrimeSpiral.html Prime Spiral]. + +

diff --git a/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--1.ada b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--1.ada new file mode 100644 index 0000000000..7e56acbff7 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--1.ada @@ -0,0 +1,19 @@ +generic + Size: Positive; + -- determines the size of the square + with function Represent(N: Natural) return String; + -- this turns a number into a string to be printed + -- the length of the output should not change + -- e.g., Represent(N) may return " #" if N is a prime + -- and " " else + with procedure Put_String(S: String); + -- outputs a string, no new line + with procedure New_Line; + -- the name says all +package Generic_Ulam is + + procedure Print_Spiral; + -- calls Put_String(Represent(I)) N^2 times + -- and New_Line N times + +end Generic_Ulam; diff --git a/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--2.ada b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--2.ada new file mode 100644 index 0000000000..e766ea957d --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--2.ada @@ -0,0 +1,36 @@ +package body Generic_Ulam is + + subtype Index is Natural range 0 .. Size-1; + subtype Number is Positive range 1 .. Size**2; + + function Cell(Row, Column: Index) return Number is + -- outputs the number at the given position in the square + -- taken from the Python solution + X: Integer := Column - (Size-1)/2; + Y: Integer := Row - Size/2; + MX: Natural := abs(X); + MY: Natural := abs(Y); + L: Natural := 2 * Natural'Max(MX, MY); + D: Integer; + begin + if Y >= X then + D := 3 * L + X + Y; + else + D := L - X - Y; + end if; + return (L-1) ** 2 + D; + end Cell; + + procedure Print_Spiral is + N: Number; + begin + for R in Index'Range loop + for C in Index'Range loop + N := Cell(R, C); + Put_String(Represent(N)); + end loop; + New_Line; + end loop; + end Print_Spiral; + +end Generic_Ulam; diff --git a/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada new file mode 100644 index 0000000000..7207fc146e --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada @@ -0,0 +1,27 @@ +with Generic_Ulam, Ada.Text_IO, Prime_Numbers; + +procedure Ulam is + + package P is new Prime_Numbers(Natural, 0, 1, 2); + + function Vis(N: Natural) return String is + (if P.Is_Prime(N) then " <>" else " "); + + function Num(N: Natural) return String is + (if P.Is_Prime(N) then + (if N < 10 then " " elsif N < 100 then " " else "") & Natural'Image(N) + else " ---"); + + procedure NL is + begin + Ada.Text_IO.New_Line; + end NL; + + package Numeric is new Generic_Ulam(29, Num, Ada.Text_IO.Put, NL); + package Visual is new Generic_Ulam(10, Vis, Ada.Text_IO.Put, NL); + +begin + Numeric.Print_Spiral; + NL; + Visual.Print_Spiral; +end Ulam; diff --git a/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c new file mode 100644 index 0000000000..0d2e571173 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c @@ -0,0 +1,87 @@ +#include +#include +#include +#include + +typedef uint32_t bitsieve; + +unsigned sieve_check(bitsieve *b, const unsigned v) +{ + if ((v != 2 && !(v & 1)) || (v < 2)) + return 0; + else + return !(b[v >> 6] & (1 << (v >> 1 & 31))); +} + +bitsieve* sieve(const unsigned v) +{ + unsigned i, j; + bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t)); + + for (i = 3; i <= sqrt(v); i += 2) + if (!(b[i >> 6] & (1 << (i >> 1 & 31)))) + for (j = i*i; j < v; j += (i << 1)) + b[j >> 6] |= (1 << (j >> 1 & 31)); + + return b; +} + +#define max(x,y) ((x) > (y) ? (x) : (y)) + +/* This mapping taken from python solution */ +int ulam_get_map(int x, int y, int n) +{ + x -= (n - 1) / 2; + y -= n / 2; + + int mx = abs(x), my = abs(y); + int l = 2 * max(mx, my); + int d = y > x ? l * 3 + x + y : l - x - y; + + return pow(l - 1, 2) + d; +} + +/* Passing a value of 0 as glyph will print numbers */ +void output_ulam_spiral(int n, const char glyph) +{ + /* An even side length does not make sense, use greatest odd value < n */ + n -= n % 2 == 0 ? 1 : 0; + + const char *spaces = "................."; + int mwidth = log10(n * n) + 1; + + bitsieve *b = sieve(n * n + 1); + int x, y; + + for (x = 0; x < n; ++x) { + for (y = 0; y < n; ++y) { + int z = ulam_get_map(y, x, n); + + if (glyph == 0) { + if (sieve_check(b, z)) + printf("%*d ", mwidth, z); + else + printf("%.*s ", mwidth, spaces); + } + else { + printf("%c", sieve_check(b, z) ? glyph : spaces[0]); + } + } + printf("\n"); + } + + free(b); +} + +int main(int argc, char *argv[]) +{ + const int n = argc < 2 ? 9 : atoi(argv[1]); + + output_ulam_spiral(n, 0); + printf("\n"); + + output_ulam_spiral(n, '#'); + printf("\n"); + + return 0; +} diff --git a/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--2.c b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--2.c new file mode 100644 index 0000000000..138d989259 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--2.c @@ -0,0 +1,30 @@ +#include +#include + +int isprime(int n) +{ + int p; + for (p = 2; p*p <= n; p++) + if (n%p == 0) return 0; + return n > 2; +} + +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 c, char **v) +{ + int i, j, w = 50, h = 50, s = 1; + if (c > 1 && (w = atoi(v[1])) <= 0) w = 50; + if (c > 2 && (h = atoi(v[2])) <= 0) h = w; + if (c > 3 && (s = atoi(v[3])) <= 0) s = 1; + + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) + putchar(isprime(w*h + s - 1 - spiral(w, h, j, i))[" #"]); + putchar('\n'); + } + return 0; +} diff --git a/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--1.d b/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--1.d new file mode 100644 index 0000000000..1badc1b920 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--1.d @@ -0,0 +1,34 @@ +import std.stdio, std.math, std.algorithm, std.array, std.range; + +int cell(in int n, int x, int y, in int start=1) pure nothrow @safe @nogc { + x = x - (n - 1) / 2; + y = y - n / 2; + immutable l = 2 * max(x.abs, y.abs); + immutable d = (y > x) ? (l * 3 + x + y) : (l - x - y); + return (l - 1) ^^ 2 + d + start - 1; +} + +void showSpiral(in int n, in string symbol="# ", in int start=1, string space=null) /*@safe*/ { + if (space is null) + space = " ".replicate(symbol.length); + + immutable top = start + n ^^ 2 + 1; + auto isPrime = [false, false, true] ~ [true, false].replicate(top / 2); + foreach (immutable x; 3 .. 1 + cast(int)real(top).sqrt) { + if (!isPrime[x]) + continue; + foreach (immutable i; iota(x ^^ 2, top, x * 2)) + isPrime[i] = false; + } + + string cellStr(in int x) pure nothrow @safe @nogc { + return isPrime[x] ? symbol : space; + } + + foreach (immutable y; 0 .. n) + n.iota.map!(x => cell(n, x, y, start)).map!cellStr.joiner.writeln; +} + +void main() { + 35.showSpiral; +} diff --git a/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--2.d b/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--2.d new file mode 100644 index 0000000000..b358b589c3 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/D/ulam-spiral--for-primes--2.d @@ -0,0 +1,33 @@ +import std.stdio, std.math, std.algorithm, std.array, grayscale_image; + +uint cell(in uint n, int x, int y, in uint start=1) pure nothrow @safe @nogc { + x = x - (n - 1) / 2; + y = y - n / 2; + immutable l = 2 * max(x.abs, y.abs); + immutable d = (y > x) ? (l * 3 + x + y) : (l - x - y); + return (l - 1) ^^ 2 + d + start - 1; +} + +bool[] primes(in uint n, in uint top, in uint start=1) pure nothrow @safe { + auto isPrime = [false, false, true] ~ [true, false].replicate(top / 2); + + foreach (immutable x; 3 .. 1 + cast(uint)real(top).sqrt) + if (isPrime[x]) + for (uint i = x ^^ 2; i < top; i += x * 2) + isPrime[i] = false; + return isPrime; +} + +void main() { + enum n = 512; + enum start = 1; + immutable top = start + n ^^ 2 + 1; + immutable isPrime = primes(n, top, start); + auto img = new Image!Gray(n, n); + + foreach (immutable y; 0 .. n) + foreach (immutable x; 0 .. n) + img[x, y] = isPrime[cell(n, x, y, start)] ? Gray.black : Gray.white; + + img.savePGM("ulam_spiral.pgm"); +} diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--1.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--1.j new file mode 100644 index 0000000000..8f56655226 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--1.j @@ -0,0 +1 @@ +spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,) diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--2.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--2.j new file mode 100644 index 0000000000..b271e465c0 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--2.j @@ -0,0 +1,12 @@ + spiral 5 + 0 1 2 3 4 +15 16 17 18 5 +14 23 24 19 6 +13 22 21 20 7 +12 11 10 9 8 + (*: - spiral) 5 +25 24 23 22 21 +10 9 8 7 20 +11 2 1 6 19 +12 3 4 5 18 +13 14 15 16 17 diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--3.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--3.j new file mode 100644 index 0000000000..1ce0d62069 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--3.j @@ -0,0 +1,6 @@ + (1 p: *: - spiral) 5 +0 0 1 0 0 +0 0 0 1 0 +1 1 0 0 1 +0 1 0 1 0 +1 0 0 0 1 diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--4.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--4.j new file mode 100644 index 0000000000..7f2c520a1d --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--4.j @@ -0,0 +1,6 @@ + (' o' {~ 1 p: *: - spiral) 5 + o + o +oo o + o o +o o diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--5.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--5.j new file mode 100644 index 0000000000..565041a390 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--5.j @@ -0,0 +1,4 @@ + (0: :(<:@[)) '' +0 + 3 (0: :(<:@[)) '' +2 diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--6.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--6.j new file mode 100644 index 0000000000..ed2ea7c468 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--6.j @@ -0,0 +1 @@ +ulam=: 1j1 #"1 ' o' {~ 1 p: 0: :(<:@[) + *:@] - spiral@] diff --git a/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--7.j b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--7.j new file mode 100644 index 0000000000..7908066a9b --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/J/ulam-spiral--for-primes--7.j @@ -0,0 +1,29 @@ + ulam 16 + o o +o o o + o o o +o o o o + o o o + o o o o o + o o o o + o o o + o o o o o o o + o o o + o o + o o o o o + o o o + o + o o o o +o o + 9 ulam 12 + o o +o o o o + o o o o + o o o + o o +o o o o o + o o + o + o o o o + o + o o o diff --git a/Task/Ulam-spiral--for-primes-/Java/ulam-spiral--for-primes-.java b/Task/Ulam-spiral--for-primes-/Java/ulam-spiral--for-primes-.java new file mode 100644 index 0000000000..19b4dc1ece --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Java/ulam-spiral--for-primes-.java @@ -0,0 +1,64 @@ +import java.util.Arrays; + +public class Ulam{ + enum Direction{ + RIGHT, UP, LEFT, DOWN; + } + + private static String[][] genUlam(int n){ + return genUlam(n, 1); + } + + private static String[][] genUlam(int n, int i){ + String[][] spiral = new String[n][n]; + Direction dir = Direction.RIGHT; + int j = i; + int y = n / 2; + int x = (n % 2 == 0) ? y - 1 : y; //shift left for even n's + while(j <= ((n * n) - 1 + i)){ + spiral[y][x] = isPrime(j) ? String.format("%4d", j) : " ---"; + + switch(dir){ + case RIGHT: + if(x <= (n - 1) && spiral[y - 1][x] == null && j > i) dir = Direction.UP; break; + case UP: + if(spiral[y][x - 1] == null) dir = Direction.LEFT; break; + case LEFT: + if(x == 0 || spiral[y + 1][x] == null) dir = Direction.DOWN; break; + case DOWN: + if(spiral[y][x + 1] == null) dir = Direction.RIGHT; break; + } + + switch(dir){ + case RIGHT: x++; break; + case UP: y--; break; + case LEFT: x--; break; + case DOWN: y++; break; + } + j++; + } + return spiral; + } + + public static boolean isPrime(int a){ + if(a == 2) return true; + if(a <= 1 || a % 2 == 0) return false; + long max = (long)Math.sqrt(a); + for(long n = 3; n <= max; n += 2){ + if(a % n == 0) return false; + } + return true; + } + + public static void main(String[] args){ + String[][] ulam = genUlam(9); + for(String[] row : ulam){ + System.out.println(Arrays.toString(row).replaceAll(",", "")); + } + System.out.println(); + + for(String[] row : ulam){ + System.out.println(Arrays.toString(row).replaceAll("\\[\\s+\\d+", "[ * ").replaceAll("\\s+\\d+", " * ").replaceAll(",", "")); + } + } +} diff --git a/Task/Ulam-spiral--for-primes-/Perl-6/ulam-spiral--for-primes-.pl6 b/Task/Ulam-spiral--for-primes-/Perl-6/ulam-spiral--for-primes-.pl6 new file mode 100644 index 0000000000..6755855581 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Perl-6/ulam-spiral--for-primes-.pl6 @@ -0,0 +1,51 @@ +sub MAIN($max = 160, $start = 1) { + (my %world){0}{0} = 0; + my $loc = 0+0i; + my $dir = 1; + my $n = $start; + my $side = 0; + + while ++$side < $max { + step for ^$side; + turn-left; + step for ^$side; + turn-left; + } + + braille-graphics %world; + + sub step { + $loc += $dir; + %world{$loc.im}{$loc.re} = $n if (++$n).is-prime; + } + + sub turn-left { $dir *= -i; } + sub turn-right { $dir *= i; } + +} + +sub braille-graphics (%a) { + my ($ylo, $yhi, $xlo, $xhi); + for %a.keys -> $y { + $ylo min= +$y; $yhi max= +$y; + for %a{$y}.keys -> $x { + $xlo min= +$x; $xhi max= +$x; + } + } + + for $ylo, $ylo + 4 ...^ * > $yhi -> \y { + for $xlo, $xlo + 2 ...^ * > $xhi -> \x { + my $cell = 0x2800; + $cell += 1 if %a{y + 0}{x + 0}; + $cell += 2 if %a{y + 1}{x + 0}; + $cell += 4 if %a{y + 2}{x + 0}; + $cell += 8 if %a{y + 0}{x + 1}; + $cell += 16 if %a{y + 1}{x + 1}; + $cell += 32 if %a{y + 2}{x + 1}; + $cell += 64 if %a{y + 3}{x + 0}; + $cell += 128 if %a{y + 3}{x + 1}; + print chr($cell); + } + print "\n"; + } +} diff --git a/Task/Ulam-spiral--for-primes-/Perl/ulam-spiral--for-primes-.pl b/Task/Ulam-spiral--for-primes-/Perl/ulam-spiral--for-primes-.pl new file mode 100644 index 0000000000..7c15354bc9 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Perl/ulam-spiral--for-primes-.pl @@ -0,0 +1,29 @@ +use ntheory qw/is_prime/; +use Imager; + +my $n = shift || 512; +my $start = shift || 1; +my $file = "ulam.png"; + +sub cell { + my($n, $x, $y, $start) = @_; + $y -= $n>>1; + $x -= ($n-1)>>1; + my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y)); + my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y; + ($l-1)**2 + $d + $start - 1; +} + +my $black = Imager::Color->new('#000000'); +my $white = Imager::Color->new('#FFFFFF'); +my $img = Imager->new(xsize => $n, ysize => $n, channels => 1); +$img->box(filled=>1, color=>$white); + +for my $y (0 .. $n-1) { + for my $x (0 .. $n-1) { + my $v = cell($n, $x, $y, $start); + $img->setpixel(x => $x, y => $y, color => $black) if is_prime($v); + } +} + +$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n"; diff --git a/Task/Ulam-spiral--for-primes-/Python/ulam-spiral--for-primes-.py b/Task/Ulam-spiral--for-primes-/Python/ulam-spiral--for-primes-.py new file mode 100644 index 0000000000..fd71785776 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Python/ulam-spiral--for-primes-.py @@ -0,0 +1,36 @@ +# coding=UTF-8 +from __future__ import print_function, division +from math import sqrt + +def cell(n, x, y, start=1): + d, y, x = 0, y - n//2, x - (n - 1)//2 + l = 2*max(abs(x), abs(y)) + d = (l*3 + x + y) if y >= x else (l - x - y) + return (l - 1)**2 + d + start - 1 + +def show_spiral(n, symbol='# ', start=1, space=None): + top = start + n*n + 1 + is_prime = [False,False,True] + [True,False]*(top//2) + for x in range(3, 1 + int(sqrt(top))): + if not is_prime[x]: continue + for i in range(x*x, top, x*2): + is_prime[i] = False + + cell_str = lambda x: f(x) if is_prime[x] else space + f = lambda _: symbol # how to show prime cells + + if space == None: space = ' '*len(symbol) + + if not len(symbol): # print numbers instead + max_str = len(str(n*n + start - 1)) + if space == None: space = '.'*max_str + ' ' + f = lambda x: ('%' + str(max_str) + 'd ')%x + + for y in range(n): + print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)])) + print() + +show_spiral(10, symbol=u'♞', space=u'♘') # black are the primes +show_spiral(9, symbol='', space=' - ') +# for filling giant terminals +#show_spiral(1001, symbol='*', start=42) diff --git a/Task/Ulam-spiral--for-primes-/README b/Task/Ulam-spiral--for-primes-/README new file mode 100644 index 0000000000..6d875be894 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Ulam_spiral_(for_primes) diff --git a/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--1.rexx b/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--1.rexx new file mode 100644 index 0000000000..1929f5eaad --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--1.rexx @@ -0,0 +1,42 @@ +/*REXX pgm shows cntr-clockwise Ulam spiral of primes in a square matrix*/ +parse arg size init char . /*get the matrix size from the CL*/ +if size=='' | size==',' then size=79 /*No size? Then use default of 79*/ +if init=='' | init==',' then init= 1 /*No init? Then use default of 1 */ +if char=='' then char='█' /*No char? Then use default of █ */ +tot=size**2; offset=init-1 /*numbers in spiral; start offset*/ +uR.=0; bR.=0 /*the upper/bottom right corners.*/ + do od=1 by 2 to tot; _=od**2+1+offset; uR._=1; _=_ + od; bR._=1; end +bL.=0; uL.=0 /*the bottom/upper left corners. */ + do ev=2 by 2 to tot; _=ev**2+1+offset; bL._=1; _=_ + ev; uL._=1; end +$.= +bigP=0; #p=0; app=1; inc=0; r=1; $=0; minR=1; maxR=1; $=0; !.= +/*──────────────────────────────────────────────construct the spiral #s.*/ + do i=init for tot; r=r+inc; minR=min(minR,r); maxR=max(maxR,r) + x=isPrime(i); if x then bigP=max(bigP,i); #p=#p+x /*bigP, #primes.*/ + if app then $.r=$.r || x /*append token.*/ + else $.r= x || $.r /*prepend token.*/ + if uR.i then do; app=1; inc=+1; iterate; end /*advance ↓ */ + if bL.i then do; app=0; inc=-1; iterate; end /* " ↑ */ + if bR.i then do; app=0; inc= 0; iterate; end /* " ► */ + if uL.i then do; app=1; inc= 0; iterate; end /* " ◄ */ + end /*i*/ + + do j=minR to maxR by 2; jp=j+1; $=$+1 /*fold two lines*/ + do k=1 for length($.j); top=substr($.j,k,1) /*the 1st line*/ + bot=word(substr($.jp,k,1) 0,1) /*2nd line*/ + if top then if bot then !.$=!.$'█' /*has top & bot.*/ + else !.$=!.$'▀' /*has top,¬ bot.*/ + else if bot then !.$=!.$'▄' /*¬ top, has bot*/ + else !.$=!.$' ' /*¬ top, ¬ bot.*/ + end /*k*/ + end /*j*/ /* [↓] show prime# spiral matrix*/ + do m=1 for $; say !.m; end /*m*/ +say; say init 'is the starting point,' , + tot 'numbers used,' #p "primes found, largest prime:" bigP +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────ISPRIME subroutine──────────────────────────────*/ +isPrime: procedure; parse arg x; if x<2 then return 0 +if wordpos(x,'2 3 5 7')\==0 then return 1 +if x//2==0 then return 0; if x//3==0 then return 0 + do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end +return 1 diff --git a/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--2.rexx b/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--2.rexx new file mode 100644 index 0000000000..6919316532 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/REXX/ulam-spiral--for-primes--2.rexx @@ -0,0 +1,42 @@ +/*REXX pgm shows a clockwise Ulam spiral of primes in a square matrix. */ +parse arg size init char . /*get the matrix size from the CL*/ +if size=='' | size==',' then size=79 /*No size? Then use default of 79*/ +if init=='' | init==',' then init= 1 /*No init? Then use default of 1 */ +if char=='' then char='█' /*No char? Then use default of █ */ +tot=size**2; offset=init-1 /*numbers in spiral; start offset*/ +uR.=0; bR.=0 /*the upper/bottom right corners.*/ + do od=1 by 2 to tot; _=od**2+1+offset; uR._=1; _=_ + od; bR._=1; end +bL.=0; uL.=0 /*the bottom/upper left corners. */ + do ev=2 by 2 to tot; _=ev**2+1+offset; bL._=1; _=_ + ev; uL._=1; end +$.= +bigP=0; #p=0; app=1; inc=0; r=1; $=0; minR=1; maxR=1; $=0; !.= +/*──────────────────────────────────────────────construct the spiral #s.*/ + do i=init for tot; r=r+inc; minR=min(minR,r); maxR=max(maxR,r) + x=isPrime(i); if x then bigP=max(bigP,i); #p=#p+x /*bigP, #primes.*/ + if app then $.r=$.r || x /*append token.*/ + else $.r= x || $.r /*prepend token.*/ + if uR.i then do; app=1; inc=+1; iterate; end /*advance ↓ */ + if bL.i then do; app=0; inc=-1; iterate; end /* " ↑ */ + if bR.i then do; app=0; inc= 0; iterate; end /* " ► */ + if uL.i then do; app=1; inc= 0; iterate; end /* " ◄ */ + end /*i*/ + + do j=minR to maxR by 2; jp=j+1; $=$+1 /*fold two lines*/ + do k=1 for length($.j); top=substr($.j,k,1) /*the 1st line*/ + bot=word(substr($.jp,k,1) 0,1) /*2nd line*/ + if top then if bot then !.$=!.$'█' /*has top & bot.*/ + else !.$=!.$'▀' /*has top,¬ bot.*/ + else if bot then !.$=!.$'▄' /*¬ top, has bot*/ + else !.$=!.$' ' /*¬ top, ¬ bot*/ + end /*k*/ + end /*j*/ /* [↓] show prime# spiral matrix*/ + do m=1 for $; say !.m; end /*m*/ +say; say init 'is the starting point,' , + tot 'numbers used,' #p "primes found, largest prime:" bigP +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────ISPRIME subroutine──────────────────────────────*/ +isPrime: procedure; parse arg x; if x<2 then return 0 +if wordpos(x,'2 3 5 7')\==0 then return 1 +if x//2==0 then return 0; if x//3==0 then return 0 + do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end +return 1 diff --git a/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt b/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt new file mode 100644 index 0000000000..dfc21a2dab --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt @@ -0,0 +1,36 @@ +#lang racket +(require (only-in math/number-theory prime?)) + +(define ((cell-fn n (start 1)) x y) + (let* ((y (- y (quotient n 2))) + (x (- x (quotient (sub1 n) 2))) + (l (* 2 (if (> (abs x) (abs y)) (abs x) (abs y)))) + (d (if (> y x) (+ (* l 3) x y) (- l x y)))) + (+ (sqr (- l 1)) d start -1))) + +(define (show-spiral n + #:symbol (smb "# ") + #:start (start 1) + #:space (space (and smb (make-string (string-length smb) #\space)))) + (define top (+ start (sqr n) 1)) + (define cell (cell-fn n start)) + (define print-cell + (if smb + (λ (i p?) (display (if p? smb space))) + (let* ((max-len (string-length (~a (+ (sqr n) start -1)))) + (space (or space (make-string (string-length (~a (+ (sqr n) start -1))) #\_)))) + (λ (i p?) + (display (if p? (~a #:width max-len i #:align 'right) space)) + (display #\space))))) + + (for* ((y (in-range 1 (add1 n))) #:when (unless (= y 1) (newline)) (x (in-range 1 (add1 n)))) + (define c (cell x y)) + (define p? (prime? c)) + (print-cell c p?)) + (newline)) + +(show-spiral 9 #:symbol #f) +(show-spiral 10 #:symbol "♞" #:space "♘") ; black are the primes +(show-spiral 50 #:symbol "*" #:start 42) +; for filling giant terminals +; (show_spiral 1001 "*" 42) diff --git a/Task/Unix-ls/00DESCRIPTION b/Task/Unix-ls/00DESCRIPTION new file mode 100644 index 0000000000..f841775c89 --- /dev/null +++ b/Task/Unix-ls/00DESCRIPTION @@ -0,0 +1,17 @@ +Write a program that will list everything in the current folder, similar to the Unix utility “ls” [http://man7.org/linux/man-pages/man1/ls.1.html] (or the Windows terminal command “DIR”). The output must be sorted, but printing extended details and producing multi-column output is not required. + +;Example output +For the list of paths: +
/foo/bar
+/foo/bar/1
+/foo/bar/2
+/foo/bar/a
+/foo/bar/b
+ +When the program is executed in `/foo`, it should print: +
bar
+and when the program is executed in `/foo/bar`, it should print: +
1
+2
+a
+b
diff --git a/Task/Unix-ls/AWK/unix-ls.awk b/Task/Unix-ls/AWK/unix-ls.awk new file mode 100644 index 0000000000..39dd30ef56 --- /dev/null +++ b/Task/Unix-ls/AWK/unix-ls.awk @@ -0,0 +1,8 @@ +# syntax: GAWK -f UNIX_LS.AWK * | SORT +BEGINFILE { + printf("%s\n",FILENAME) + nextfile +} +END { + exit(0) +} diff --git a/Task/Unix-ls/Ada/unix-ls.ada b/Task/Unix-ls/Ada/unix-ls.ada new file mode 100644 index 0000000000..4edec9cd49 --- /dev/null +++ b/Task/Unix-ls/Ada/unix-ls.ada @@ -0,0 +1,29 @@ +with Ada.Text_IO, Ada.Directories, Ada.Containers.Indefinite_Vectors; + +procedure Directory_List is + + use Ada.Directories, Ada.Text_IO; + Search: Search_Type; Found: Directory_Entry_Type; + package SV is new Ada.Containers.Indefinite_Vectors(Natural, String); + Result: SV.Vector; + package Sorting is new SV.Generic_Sorting; use Sorting; + function SName return String is (Simple_Name(Found)); + +begin + Start_Search(Search, Directory => ".", Pattern =>""); + while More_Entries(Search) loop + Get_Next_Entry(Search, Found); + declare + Name: String := Simple_Name(Found); + begin + if Name(Name'First) /= '.' then + Result.Append(Name); + end if; -- ingnore filenames beginning with "." + end; + end loop; -- now Result holds the entire directory in arbitrary order + + Sort(Result); -- nor Result holds the directory in proper order + for I in Result.First_Index .. Result.Last_Index loop + Put_Line(Result.Element(I)); + end loop; +end Directory_List; diff --git a/Task/Unix-ls/C/unix-ls.c b/Task/Unix-ls/C/unix-ls.c new file mode 100644 index 0000000000..6b2689ea05 --- /dev/null +++ b/Task/Unix-ls/C/unix-ls.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include +#include + +int cmpstr(const void *a, const void *b) +{ + return strcmp(*(const char**)a, *(const char**)b); +} + +int main(void) +{ + DIR *basedir; + char path[PATH_MAX]; + struct dirent *entry; + char **dirnames; + int diralloc = 128; + int dirsize = 0; + + if (!(dirnames = malloc(diralloc * sizeof(char*)))) { + perror("malloc error:"); + return 1; + } + + if (!getcwd(path, PATH_MAX)) { + perror("getcwd error:"); + return 1; + } + + if (!(basedir = opendir(path))) { + perror("opendir error:"); + return 1; + } + + while ((entry = readdir(basedir))) { + if (dirsize >= diralloc) { + diralloc *= 2; + if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) { + perror("realloc error:"); + return 1; + } + } + dirnames[dirsize++] = strdup(entry->d_name); + } + + qsort(dirnames, dirsize, sizeof(char*), cmpstr); + + int i; + for (i = 0; i < dirsize; ++i) { + if (dirnames[i][0] != '.') { + printf("%s\n", dirnames[i]); + } + } + + for (i = 0; i < dirsize; ++i) + free(dirnames[i]); + free(dirnames); + closedir(basedir); + return 0; +} diff --git a/Task/Unix-ls/Clojure/unix-ls.clj b/Task/Unix-ls/Clojure/unix-ls.clj new file mode 100644 index 0000000000..ac137270ba --- /dev/null +++ b/Task/Unix-ls/Clojure/unix-ls.clj @@ -0,0 +1,3 @@ +(def files (sort (filter #(= "." (.getParent %)) (file-seq (clojure.java.io/file "."))))) + +(doseq [n files] (println (.getName n))) diff --git a/Task/Unix-ls/D/unix-ls.d b/Task/Unix-ls/D/unix-ls.d new file mode 100644 index 0000000000..507681b3d7 --- /dev/null +++ b/Task/Unix-ls/D/unix-ls.d @@ -0,0 +1,6 @@ +void main() { + import std.stdio, std.file, std.path; + + foreach (const string path; dirEntries(getcwd, SpanMode.shallow)) + path.baseName.writeln; +} diff --git a/Task/Unix-ls/Forth/unix-ls-1.fth b/Task/Unix-ls/Forth/unix-ls-1.fth new file mode 100644 index 0000000000..f7f99d68df --- /dev/null +++ b/Task/Unix-ls/Forth/unix-ls-1.fth @@ -0,0 +1,12 @@ +256 buffer: filename-buf +: each-filename { xt -- } \ xt-consuming variant + s" ." open-dir throw { d } + begin filename-buf 256 d read-dir throw while + filename-buf swap xt execute + repeat d close-dir throw ; + +\ immediate variant +: each-filename[ s" ." postpone sliteral ]] open-dir throw >r begin filename-buf 256 r@ read-dir throw while filename-buf swap [[ ; immediate compile-only +: ]each-filename ]] repeat drop r> close-dir throw [[ ; immediate compile-only + +: ls ( -- ) [: cr type ;] each-filename ; diff --git a/Task/Unix-ls/Forth/unix-ls-2.fth b/Task/Unix-ls/Forth/unix-ls-2.fth new file mode 100644 index 0000000000..2394fcb012 --- /dev/null +++ b/Task/Unix-ls/Forth/unix-ls-2.fth @@ -0,0 +1,15 @@ +: save-string ( c-addr u -- a ) + dup 1+ allocate throw dup >r place r> ; + +require ffl/car.fs +: sorted-filenames ( -- car ) + 0 car-new { a } + [: swap count rot count compare ;] a car-compare! + each-filename[ save-string a car-insert-sorted ]each-filename + a ; + +: each-sorted-filename ( xt -- ) + sorted-filenames { a } a car-execute [: free throw ;] a car-execute a car-free ; + +: ls ( -- ) + [: count cr type ;] each-sorted-filename ; diff --git a/Task/Unix-ls/Go/unix-ls.go b/Task/Unix-ls/Go/unix-ls.go new file mode 100644 index 0000000000..4669d86d1f --- /dev/null +++ b/Task/Unix-ls/Go/unix-ls.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "log" + "os" + "sort" +) + +func main() { + f, err := os.Open(".") + if err != nil { + log.Fatal(err) + } + files, err := f.Readdirnames(0) + f.Close() + if err != nil { + log.Fatal(err) + } + sort.Strings(files) + for _, n := range files { + fmt.Println(n) + } +} diff --git a/Task/Unix-ls/Haskell/unix-ls.hs b/Task/Unix-ls/Haskell/unix-ls.hs new file mode 100644 index 0000000000..998a25400f --- /dev/null +++ b/Task/Unix-ls/Haskell/unix-ls.hs @@ -0,0 +1,9 @@ +import Control.Monad +import Data.List +import System.Directory + +dontStartWith = flip $ (/=) . head + +main = do + files <- getDirectoryContents "." + mapM_ putStrLn $ sort $ filter (dontStartWith '.') files diff --git a/Task/Unix-ls/J/unix-ls.j b/Task/Unix-ls/J/unix-ls.j new file mode 100644 index 0000000000..7aedd3780c --- /dev/null +++ b/Task/Unix-ls/J/unix-ls.j @@ -0,0 +1,2 @@ + dir '*' NB. includes properties + > 1 dir '*' NB. plain filename as per task diff --git a/Task/Unix-ls/Mathematica/unix-ls.math b/Task/Unix-ls/Mathematica/unix-ls.math new file mode 100644 index 0000000000..91e99c8ee0 --- /dev/null +++ b/Task/Unix-ls/Mathematica/unix-ls.math @@ -0,0 +1 @@ +Column[FileNames[]] diff --git a/Task/Unix-ls/OCaml/unix-ls.ocaml b/Task/Unix-ls/OCaml/unix-ls.ocaml new file mode 100644 index 0000000000..e74c3d7cd2 --- /dev/null +++ b/Task/Unix-ls/OCaml/unix-ls.ocaml @@ -0,0 +1,3 @@ +let () = + Array.iter print_endline ( + Sys.readdir Sys.argv.(1) ) diff --git a/Task/Unix-ls/PARI-GP/unix-ls-1.pari b/Task/Unix-ls/PARI-GP/unix-ls-1.pari new file mode 100644 index 0000000000..a39d564d25 --- /dev/null +++ b/Task/Unix-ls/PARI-GP/unix-ls-1.pari @@ -0,0 +1 @@ +system("dir/b/on") diff --git a/Task/Unix-ls/PARI-GP/unix-ls-2.pari b/Task/Unix-ls/PARI-GP/unix-ls-2.pari new file mode 100644 index 0000000000..bf8b55bee0 --- /dev/null +++ b/Task/Unix-ls/PARI-GP/unix-ls-2.pari @@ -0,0 +1 @@ +system("ls") diff --git a/Task/Unix-ls/Perl-6/unix-ls.pl6 b/Task/Unix-ls/Perl-6/unix-ls.pl6 new file mode 100644 index 0000000000..ebf4c7e9a5 --- /dev/null +++ b/Task/Unix-ls/Perl-6/unix-ls.pl6 @@ -0,0 +1 @@ +.say for sort ~«dir diff --git a/Task/Unix-ls/Python/unix-ls.py b/Task/Unix-ls/Python/unix-ls.py new file mode 100644 index 0000000000..f95cb11ff1 --- /dev/null +++ b/Task/Unix-ls/Python/unix-ls.py @@ -0,0 +1,16 @@ +>>> import os +>>> print('\n'.join(sorted(os.listdir('.')))) +DLLs +Doc +LICENSE.txt +Lib +NEWS.txt +README.txt +Scripts +Tools +include +libs +python.exe +pythonw.exe +tcl +>>> diff --git a/Task/Unix-ls/README b/Task/Unix-ls/README new file mode 100644 index 0000000000..ac4a714be8 --- /dev/null +++ b/Task/Unix-ls/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Unix/ls diff --git a/Task/Unix-ls/REXX/unix-ls.rexx b/Task/Unix-ls/REXX/unix-ls.rexx new file mode 100644 index 0000000000..3c06aa2821 --- /dev/null +++ b/Task/Unix-ls/REXX/unix-ls.rexx @@ -0,0 +1,3 @@ +/*REXX program lists contents of current folder (ala mode UNIX's LS). */ +'DIR /b /oN' /*use Windows DIR: sorts & lists.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Unix-ls/Racket/unix-ls.rkt b/Task/Unix-ls/Racket/unix-ls.rkt new file mode 100644 index 0000000000..cb5d915b96 --- /dev/null +++ b/Task/Unix-ls/Racket/unix-ls.rkt @@ -0,0 +1,20 @@ +#lang racket/base + +;; Racket's `directory-list' produces a sorted list of files +(define (ls) (for-each displayln (directory-list))) + +;; Code to run when this file is running directly +(module+ main + (ls)) + +(module+ test + (require tests/eli-tester racket/port racket/file) + (define (make-directory-tree) + (make-directory* "foo/bar") + (for ([f '("1" "2" "a" "b")]) + (with-output-to-file (format "foo/bar/~a"f) #:exists 'replace newline))) + (make-directory-tree) + (define (ls/str dir) + (parameterize ([current-directory dir]) (with-output-to-string ls))) + (test (ls/str "foo") => "bar\n" + (ls/str "foo/bar") => "1\n2\na\nb\n")) diff --git a/Task/Unix-ls/Ruby/unix-ls.rb b/Task/Unix-ls/Ruby/unix-ls.rb new file mode 100644 index 0000000000..4e03f6b26e --- /dev/null +++ b/Task/Unix-ls/Ruby/unix-ls.rb @@ -0,0 +1 @@ +Dir.foreach("./"){|n| puts n} diff --git a/Task/Unix-ls/Rust/unix-ls.rust b/Task/Unix-ls/Rust/unix-ls.rust new file mode 100644 index 0000000000..3ea0f7c86c --- /dev/null +++ b/Task/Unix-ls/Rust/unix-ls.rust @@ -0,0 +1,17 @@ +use std::os; +use std::io::fs; + +fn main() { + let cwd = os::getcwd(); + let info = fs::readdir(&cwd).unwrap(); + + let mut filenames = Vec::new(); + for entry in info.iter() { + filenames.push(entry.filename_str().unwrap()); + } + + filenames.sort(); + for filename in filenames.iter() { + println!("{}", filename); + } +} diff --git a/Task/Unix-ls/Tcl/unix-ls.tcl b/Task/Unix-ls/Tcl/unix-ls.tcl new file mode 100644 index 0000000000..64cdd0cbf5 --- /dev/null +++ b/Task/Unix-ls/Tcl/unix-ls.tcl @@ -0,0 +1 @@ +puts [join [lsort [glob -nocomplain *]] "\n"] diff --git a/Task/Vogels-approximation-method/00DESCRIPTION b/Task/Vogels-approximation-method/00DESCRIPTION new file mode 100644 index 0000000000..46a48ff7af --- /dev/null +++ b/Task/Vogels-approximation-method/00DESCRIPTION @@ -0,0 +1,73 @@ +[http://mcajournal.cbu.edu.tr/articleinpress/articleinpress_955.pdf Vogel's Approximation Method (VAM)] is a technique for finding a good initial feasible solution to an allocation problem. + +The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: +* A will require 30 hours of work, +* B will require 20 hours of work, +* C will require 70 hours of work, +* D will require 30 hours of work, and +* E will require 60 hours of work. + +They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”. +* W has 50 hours available to commit to working, +* X has 60 hours available, +* Y has 50 hours available, and +* Z has 50 hours available. +The cost per hour for each contractor for each task is summarized by the following table: + +
+   A  B  C  D  E
+W 16 16 13 22 17
+X 14 14 13 19 15
+Y 19 19 20 23 50
+Z 50 12 50 15 11
+
+ +The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: + +:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply + A B C D E W X Y Z +1 2 2 0 4 4 3 1 0 1 E-Z(50) + + +Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). +Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see [http://rosettacode.org/mw/index.php?title=VAM&oldid=167195 here] for the working. + +Repeat until all supply and demand is met: +
+2       2       2       0       1       2       3       1       0       -   C-W(50)
+3       5       5       7       4      35       -       1       0       -   E-X(50)
+4       5       5       7       4       -       -       1       0       -   C-X(20)
+5       5       5       -       4       -       -       0       0       -   A-X(30)
+6       -      19       -      23       -       -       -      19       -   D-Y(30)
+        -       -       -       -       -       -       -       -       -   B-Y(20)
+
+Finally calculate the cost of your solution. In the example given it is £3100: +
+   A  B  C  D  E
+W       50
+X 30    20    10
+Y    20    30
+Z             50
+
+ +The optimal solution determined by [[wp:GNU Linear Programming Kit|GLPK]] is £3100: +
+   A  B  C  D  E
+W       50
+X 10 20 20    10
+Y 20       30
+Z             50
+
+ +;Cf. +* [[Transportation_problem|Transportation problem]] diff --git a/Task/Vogels-approximation-method/D/vogels-approximation-method.d b/Task/Vogels-approximation-method/D/vogels-approximation-method.d new file mode 100644 index 0000000000..a79db7eefb --- /dev/null +++ b/Task/Vogels-approximation-method/D/vogels-approximation-method.d @@ -0,0 +1,80 @@ +void main() { + import std.stdio, std.string, std.algorithm, std.range; + + enum K { A, B, C, D, E, X, Y, Z, W } + immutable int[K][K] costs = cast() //** + [K.W: [K.A: 16, K.B: 16, K.C: 13, K.D: 22, K.E: 17], + K.X: [K.A: 14, K.B: 14, K.C: 13, K.D: 19, K.E: 15], + K.Y: [K.A: 19, K.B: 19, K.C: 20, K.D: 23, K.E: 50], + K.Z: [K.A: 50, K.B: 12, K.C: 50, K.D: 15, K.E: 11]]; + int[K] demand, supply; + with (K) + demand = [A: 30, B: 20, C: 70, D: 30, E: 60], + supply = [W: 50, X: 60, Y: 50, Z: 50]; + + immutable cols = demand.keys.sort().release; + auto res = costs.byKey.zip((int[K]).init.repeat).assocArray; + K[][K] g; + foreach (immutable x; supply.byKey) + g[x] = costs[x].keys.schwartzSort!(k => cast()costs[x][k]) //** + .release; + foreach (immutable x; demand.byKey) + g[x] = costs.keys.schwartzSort!(k=> cast()costs[k][x]).release; + + while (g.length) { + int[K] d, s; + foreach (immutable x; demand.byKey) + d[x] = g[x].length > 1 ? + costs[g[x][1]][x] - costs[g[x][0]][x] : + costs[g[x][0]][x]; + foreach (immutable x; supply.byKey) + s[x] = g[x].length > 1 ? + costs[x][g[x][1]] - costs[x][g[x][0]] : + costs[x][g[x][0]]; + auto f = d.keys.minPos!((a,b) => d[a] > d[b])[0]; + auto t = s.keys.minPos!((a,b) => s[a] > s[b])[0]; + if (d[f] > s[t]) { + t = f; + f = g[f][0]; + } else { + f = t; + t = g[t][0]; + } + immutable v = min(supply[f], demand[t]); + res[f][t] += v; + demand[t] -= v; + if (demand[t] == 0) { + foreach (immutable k, immutable n; supply) + if (n != 0) + g[k] = g[k].remove!(c => c == t); + g.remove(t); + demand.remove(t); + } + supply[f] -= v; + if (supply[f] == 0) { + foreach (immutable k, immutable n; demand) + if (n != 0) + g[k] = g[k].remove!(c => c == f); + g.remove(f); + supply.remove(f); + } + } + + writefln("%-(\t%s%)", cols); + auto cost = 0; + foreach (immutable c; costs.keys.sort().release) { + write(c, '\t'); + foreach (immutable n; cols) { + if (n in res[c]) { + immutable y = res[c][n]; + if (y != 0) { + y.write; + cost += y * costs[c][n]; + } + } + '\t'.write; + } + writeln; + } + writeln("\nTotal Cost = ", cost); +} diff --git a/Task/Vogels-approximation-method/Java/vogels-approximation-method.java b/Task/Vogels-approximation-method/Java/vogels-approximation-method.java new file mode 100644 index 0000000000..cf4cc73db9 --- /dev/null +++ b/Task/Vogels-approximation-method/Java/vogels-approximation-method.java @@ -0,0 +1,97 @@ +import java.util.Arrays; +import static java.util.Arrays.stream; +import java.util.concurrent.*; + +public class VogelsApproximationMethod { + + final static int[] demand = {30, 20, 70, 30, 60}; + final static int[] supply = {50, 60, 50, 50}; + final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, + {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; + + final static int nRows = supply.length; + final static int nCols = demand.length; + + static boolean[] rowDone = new boolean[nRows]; + static boolean[] colDone = new boolean[nCols]; + static int[][] result = new int[nRows][nCols]; + + static ExecutorService es = Executors.newFixedThreadPool(2); + + public static void main(String[] args) throws Exception { + int supplyLeft = stream(supply).sum(); + int totalCost = 0; + + while (supplyLeft > 0) { + int[] cell = nextCell(); + int r = cell[0]; + int c = cell[1]; + + int quantity = Math.min(demand[c], supply[r]); + demand[c] -= quantity; + if (demand[c] == 0) + colDone[c] = true; + + supply[r] -= quantity; + if (supply[r] == 0) + rowDone[r] = true; + + result[r][c] = quantity; + supplyLeft -= quantity; + + totalCost += quantity * costs[r][c]; + } + + stream(result).forEach(a -> System.out.println(Arrays.toString(a))); + System.out.println("Total cost: " + totalCost); + + es.shutdown(); + } + + static int[] nextCell() throws Exception { + Future f1 = es.submit(() -> maxPenalty(nRows, nCols, true)); + Future f2 = es.submit(() -> maxPenalty(nCols, nRows, false)); + + int[] res1 = f1.get(); + int[] res2 = f2.get(); + + if (res1[3] == res2[3]) + return res1[2] < res2[2] ? res1 : res2; + + return (res1[3] > res2[3]) ? res2 : res1; + } + + static int[] diff(int j, int len, boolean isRow) { + int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; + int minP = -1; + for (int i = 0; i < len; i++) { + if (isRow ? colDone[i] : rowDone[i]) + continue; + int c = isRow ? costs[j][i] : costs[i][j]; + if (c < min1) { + min2 = min1; + min1 = c; + minP = i; + } else if (c < min2) + min2 = c; + } + return new int[]{min2 - min1, min1, minP}; + } + + static int[] maxPenalty(int len1, int len2, boolean isRow) { + int md = Integer.MIN_VALUE; + int pc = -1, pm = -1, mc = -1; + for (int i = 0; i < len1; i++) { + if (isRow ? rowDone[i] : colDone[i]) + continue; + int[] res = diff(i, len2, isRow); + if (res[0] > md) { + md = res[0]; // max diff + pm = i; // pos of max diff + mc = res[1]; // min cost + pc = res[2]; // pos of min cost + } + } + return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md}; + } +} diff --git a/Task/Vogels-approximation-method/Python/vogels-approximation-method.py b/Task/Vogels-approximation-method/Python/vogels-approximation-method.py new file mode 100644 index 0000000000..3cce522621 --- /dev/null +++ b/Task/Vogels-approximation-method/Python/vogels-approximation-method.py @@ -0,0 +1,57 @@ +from collections import defaultdict + +costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, + 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, + 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, + 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} +demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} +cols = sorted(demand.iterkeys()) +supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} +res = dict((k, defaultdict(int)) for k in costs) +g = {} +for x in supply: + g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) +for x in demand: + g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) + +while g: + d = {} + for x in demand: + d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] + s = {} + for x in supply: + s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] + f = max(d, key=lambda n: d[n]) + t = max(s, key=lambda n: s[n]) + t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) + v = min(supply[f], demand[t]) + res[f][t] += v + demand[t] -= v + if demand[t] == 0: + for k, n in supply.iteritems(): + if n != 0: + g[k].remove(t) + del g[t] + del demand[t] + supply[f] -= v + if supply[f] == 0: + for k, n in demand.iteritems(): + if n != 0: + g[k].remove(f) + del g[f] + del supply[f] + +for n in cols: + print "\t", n, +print +cost = 0 +for g in sorted(costs): + print g, "\t", + for n in cols: + y = res[g][n] + if y != 0: + print y, + cost += y * costs[g][n] + print "\t", + print +print "\n\nTotal Cost = ", cost diff --git a/Task/Vogels-approximation-method/README b/Task/Vogels-approximation-method/README new file mode 100644 index 0000000000..673edd57a0 --- /dev/null +++ b/Task/Vogels-approximation-method/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Vogel's_approximation_method diff --git a/Task/Vogels-approximation-method/Racket/vogels-approximation-method.rkt b/Task/Vogels-approximation-method/Racket/vogels-approximation-method.rkt new file mode 100644 index 0000000000..bee474b4ea --- /dev/null +++ b/Task/Vogels-approximation-method/Racket/vogels-approximation-method.rkt @@ -0,0 +1,103 @@ +#lang racket +(define-values (1st 2nd 3rd) (values first second third)) + +(define-syntax-rule (?: x t f) (if (zero? x) f t)) + +(define (hash-ref2 + hsh# key-1 key-2 + #:fail-2 (fail-2 (λ () (error 'hash-ref2 "key-2:~a is not found in hash" key-2))) + #:fail-1 (fail-1 (λ () (error 'hash-ref2 "key-1:~a is not found in hash" key-1)))) + (hash-ref (hash-ref hsh# key-1 fail-1) key-2 fail-2)) + +(define (VAM costs all-supply all-demand) + (define (reduce-g/x g/x x#-- x x-v y y-v) + (for/fold ((rv (?: x-v g/x (hash-remove g/x x)))) + (#:when (zero? y-v) ((k n) (in-hash x#--)) #:unless (zero? n)) + (hash-update rv k (curry remove y)))) + + (define (cheapest-candidate/tie-break candidates) + (define cand-max3 (3rd (argmax 3rd candidates))) + (argmin 2nd (for/list ((cand candidates) #:when (= (3rd cand) cand-max3)) cand))) + + (let vam-loop + ((res (hash)) + (supply all-supply) + (g/supply + (for/hash ((x (in-hash-keys all-supply))) + (define costs#x (hash-ref costs x)) + (define key-fn (λ (g) (hash-ref costs#x g))) + (values x (sort (hash-keys costs#x) < #:key key-fn #:cache-keys? #t)))) + (demand all-demand) + (g/demand + (for/hash ((x (in-hash-keys all-demand))) + (define key-fn (λ (g) (hash-ref2 costs g x))) + (values x (sort (hash-keys costs) < #:key key-fn #:cache-keys? #t))))) + (cond + [(and (hash-empty? supply) (hash-empty? demand)) res] + [(or (hash-empty? supply) (hash-empty? demand)) (error 'VAM "Unbalanced supply / demand")] + [else + (define D + (let ((candidates + (for/list ((x (in-hash-keys demand))) + (match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/demand) + (define z (hash-ref2 costs g#x.0 x)) + (match g#x + [(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs g#x.1 x) z))] + [(list _) (list x z z)])))) + (cheapest-candidate/tie-break candidates))) + + (define S + (let ((candidates + (for/list ((x (in-hash-keys supply))) + (match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/supply) + (define z (hash-ref2 costs x g#x.0)) + (match g#x + [(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs x g#x.1) z))] + [(list _) (list x z z)])))) + (cheapest-candidate/tie-break candidates))) + + (define-values (d s) + (let ((t>f? (if (= (3rd D) (3rd S)) (> (2nd S) (2nd D)) (> (3rd D) (3rd S))))) + (if t>f? (values (1st D) (1st (hash-ref g/demand (1st D)))) + (values (1st (hash-ref g/supply (1st S))) (1st S))))) + + (define v (min (hash-ref supply s) (hash-ref demand d))) + + (define d-v (- (hash-ref demand d) v)) + (define s-v (- (hash-ref supply s) v)) + + (define demand-- (?: d-v (hash-set demand d d-v) (hash-remove demand d))) + (define supply-- (?: s-v (hash-set supply s s-v) (hash-remove supply s))) + + (vam-loop + (hash-update res s (λ (h) (hash-update h d (λ (x) (+ v x)) 0)) hash) + supply-- (reduce-g/x g/supply supply-- s s-v d d-v) + demand-- (reduce-g/x g/demand demand-- d d-v s s-v))]))) + +(define (vam-solution-cost costs demand?cols solution) + (match demand?cols + [(? list? demand-cols) + (for*/sum ((g (in-hash-keys costs)) (n (in-list demand-cols))) + (* (hash-ref2 solution g n #:fail-2 0) (hash-ref2 costs g n)))] + [(hash-table (ks _) ...) (vam-solution-cost costs (sort ks symbol f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]] + v = [supply[s], demand[d]].min + res[s][d] += v + demand[d] -= v + if demand[d] == 0 then + supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)} + g.delete(d) + demand.delete(d) + end + supply[s] -= v + if supply[s] == 0 then + demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)} + g.delete(s) + supply.delete(s) + end +end + +COLS.each{|n| print "\t", n} +puts +cost = 0 +COSTS.each_key do |g| + print g, "\t" + COLS.each do |n| + y = res[g][n] + print y if y != 0 + cost += y * COSTS[g][n] + print "\t" + end + puts +end +print "\n\nTotal Cost = ", cost diff --git a/Task/Vogels-approximation-method/Ruby/vogels-approximation-method-2.rb b/Task/Vogels-approximation-method/Ruby/vogels-approximation-method-2.rb new file mode 100644 index 0000000000..8edaf8bd0b --- /dev/null +++ b/Task/Vogels-approximation-method/Ruby/vogels-approximation-method-2.rb @@ -0,0 +1,7 @@ +COSTS = {S1: {D1: 46, D2: 74, D3: 9, D4: 28, D5: 99}, + S2: {D1: 12, D2: 75, D3: 6, D4: 36, D5: 48}, + S3: {D1: 35, D2: 199, D3: 4, D4: 5, D5: 71}, + S4: {D1: 61, D2: 81, D3: 44, D4: 88, D5: 9}, + S5: {D1: 85, D2: 60, D3: 14, D4: 25, D5: 79}} +demand = {D1: 278, D2: 60, D3: 461, D4: 116, D5: 1060} +supply = {S1: 461, S2: 277, S3: 356, S4: 488, S5: 393} diff --git a/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-1.tcl b/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-1.tcl new file mode 100644 index 0000000000..fb01fd3357 --- /dev/null +++ b/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-1.tcl @@ -0,0 +1,104 @@ +package require Tcl 8.6 + +# A sort that works by sorting by an auxiliary key computed by a lambda term +proc sortByFunction {list lambda} { + lmap k [lsort -index 1 [lmap k $list { + list $k [uplevel 1 [list apply $lambda $k]] + }]] {lindex $k 0} +} + +# A simple way to pick a “best” item from a list +proc minimax {list maxidx minidx} { + set max -Inf; set min Inf + foreach t $list { + if {[set m [lindex $t $maxidx]] > $max} { + set best $t + set max $m + set min Inf + } elseif {$m == $max && [set m [lindex $t $minidx]] < $min} { + set best $t + set min $m + } + } + return $best +} + +# The approximation engine. Note that this does not change the provided +# arguments at all since they are copied on write. +proc VAM {costs demand supply} { + # Initialise the sorted sequence of pairs and the result dictionary + foreach x [dict keys $demand] { + dict set g $x [sortByFunction [dict keys $supply] {g { + upvar 1 costs costs x x; dict get $costs $g $x + }}] + dict set row $x 0 + } + foreach x [dict keys $supply] { + dict set g $x [sortByFunction [dict keys $demand] {g { + upvar 1 costs costs x x; dict get $costs $x $g + }}] + dict set res $x $row + } + + # While there's work to do... + while {[dict size $g]} { + # Select "best" demand + lassign [minimax [lmap x [dict keys $demand] { + if {![llength [set gx [dict get $g $x]]]} continue + set z [dict get $costs [lindex $gx 0] $x] + if {[llength $gx] > 1} { + list $x $z [expr {[dict get $costs [lindex $gx 1] $x] - $z}] + } else { + list $x $z $z + } + }] 2 1] d dVal dCost + + # Select "best" supply + lassign [minimax [lmap x [dict keys $supply] { + if {![llength [set gx [dict get $g $x]]]} continue + set z [dict get $costs $x [lindex $gx 0]] + if {[llength $gx] > 1} { + list $x $z [expr {[dict get $costs $x [lindex $gx 1]] - $z}] + } else { + list $x $z $z + } + }] 2 1] s sVal sCost + + # Compute how much to transfer, and with which "best" + if {$sCost == $dCost ? $sVal > $dVal : $sCost < $dCost} { + set s [lindex [dict get $g $d] 0] + } else { + set d [lindex [dict get $g $s] 0] + } + set v [expr {min([dict get $supply $s], [dict get $demand $d])}] + + # Transfer some supply to demand + dict update res $s inner {dict incr inner $d $v} + dict incr demand $d -$v + if {[dict get $demand $d] == 0} { + dict for {k n} $supply { + if {$n != 0} { + # Filter list in dictionary to remove element + dict set g $k [lmap x [dict get $g $k] { + if {$x eq $d} continue; set x + }] + } + } + dict unset g $d + dict unset demand $d + } + dict incr supply $s -$v + if {[dict get $supply $s] == 0} { + dict for {k n} $demand { + if {$n != 0} { + dict set g $k [lmap x [dict get $g $k] { + if {$x eq $s} continue; set x + }] + } + } + dict unset g $s + dict unset supply $s + } + } + return $res +} diff --git a/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-2.tcl b/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-2.tcl new file mode 100644 index 0000000000..95903b0e33 --- /dev/null +++ b/Task/Vogels-approximation-method/Tcl/vogels-approximation-method-2.tcl @@ -0,0 +1,21 @@ +set COSTS { + W {A 16 B 16 C 13 D 22 E 17} + X {A 14 B 14 C 13 D 19 E 15} + Y {A 19 B 19 C 20 D 23 E 50} + Z {A 50 B 12 C 50 D 15 E 11} +} +set DEMAND {A 30 B 20 C 70 D 30 E 60} +set SUPPLY {W 50 X 60 Y 50 Z 50} + +set RES [VAM $COSTS $DEMAND $SUPPLY] + +puts \t[join [dict keys $DEMAND] \t] +set cost 0 +foreach g [dict keys $SUPPLY] { + puts $g\t[join [lmap n [dict keys $DEMAND] { + set c [dict get $RES $g $n] + incr cost [expr {$c * [dict get $COSTS $g $n]}] + expr {$c ? $c : ""} + }] \t] +} +puts "\nTotal Cost = $cost" diff --git a/Task/World-Cup-group-stage/00DESCRIPTION b/Task/World-Cup-group-stage/00DESCRIPTION new file mode 100644 index 0000000000..085ef45d63 --- /dev/null +++ b/Task/World-Cup-group-stage/00DESCRIPTION @@ -0,0 +1,7 @@ +It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. A win is worth three points in the standings. A draw/tie is worth one point. A loss is not worth any points. + +Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. Calculate the standings points for each team with each combination of outcomes. Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. + +Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". + +''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.'' diff --git a/Task/World-Cup-group-stage/D/world-cup-group-stage-1.d b/Task/World-Cup-group-stage/D/world-cup-group-stage-1.d new file mode 100644 index 0000000000..548968d6ca --- /dev/null +++ b/Task/World-Cup-group-stage/D/world-cup-group-stage-1.d @@ -0,0 +1,20 @@ +void main() { + import std.stdio, std.range, std.array, std.algorithm, combinations3; + + immutable scoring = [0, 1, 3]; + /*immutable*/ auto r3 = [0, 1, 2]; + immutable combs = 4.iota.array.combinations(2).array; + uint[10][4] histo; + + foreach (immutable results; cartesianProduct(r3, r3, r3, r3, r3, r3)) { + int[4] s; + foreach (immutable r, const g; [results[]].zip(combs)) { + s[g[0]] += scoring[r]; + s[g[1]] += scoring[2 - r]; + } + + foreach (immutable i, immutable v; s[].sort().release) + histo[i][v]++; + } + writefln("%(%s\n%)", histo[].retro); +} diff --git a/Task/World-Cup-group-stage/D/world-cup-group-stage-2.d b/Task/World-Cup-group-stage/D/world-cup-group-stage-2.d new file mode 100644 index 0000000000..3b2ef6b410 --- /dev/null +++ b/Task/World-Cup-group-stage/D/world-cup-group-stage-2.d @@ -0,0 +1,30 @@ +import core.stdc.stdio, std.range, std.array, std.algorithm, combinations3; + +immutable uint[2][6] combs = 4u.iota.array.combinations(2).array; + +void main() nothrow @nogc { + immutable uint[3] scoring = [0, 1, 3]; + uint[10][4] histo; + + foreach (immutable r0; 0 .. 3) + foreach (immutable r1; 0 .. 3) + foreach (immutable r2; 0 .. 3) + foreach (immutable r3; 0 .. 3) + foreach (immutable r4; 0 .. 3) + foreach (immutable r5; 0 .. 3) { + uint[4] s; + foreach (immutable i, immutable r; [r0, r1, r2, r3, r4, r5]) { + s[combs[i][0]] += scoring[r]; + s[combs[i][1]] += scoring[2 - r]; + } + + foreach (immutable i, immutable v; s[].sort().release) + histo[i][v]++; + } + + foreach_reverse (const ref h; histo) { + foreach (immutable x; h) + printf("%u ", x); + printf("\n"); + } +} diff --git a/Task/World-Cup-group-stage/Erlang/world-cup-group-stage.erl b/Task/World-Cup-group-stage/Erlang/world-cup-group-stage.erl new file mode 100644 index 0000000000..3ff4e62c5e --- /dev/null +++ b/Task/World-Cup-group-stage/Erlang/world-cup-group-stage.erl @@ -0,0 +1,33 @@ +-module(world_cup). + +-export([group_stage/0]). + +group_stage() -> + Results = [[3,0],[1,1],[0,3]], + Teams = [1,2,3,4], + Matches = combos(2,Teams), + AllResults = + combinations(Matches,Results), + AllPoints = + [lists:flatten([lists:zip(L1,L2) || {L1,L2} <- L]) || L <- AllResults], + TotalPoints = + [ [ {T,lists:sum([Points || {T_,Points} <- L, T_ == T])} || T <- Teams] || L <- AllPoints], + SortedTotalPoints = + [ lists:sort(fun({_,A},{_,B}) -> A > B end,L) || L <- TotalPoints], + PointsPosition = + [ [element(2,lists:nth(N, L))|| L <- SortedTotalPoints ] || N <- Teams], + [ [length(lists:filter(fun(Points_) -> Points_ == Points end,lists:nth(N, PointsPosition) )) + || Points <- lists:seq(0,9)] || N <- Teams]. + +combos(1, L) -> + [[X] || X <- L]; +combos(K, L) when K == length(L) -> + [L]; +combos(K, [H|T]) -> + [[H | Subcombos] || Subcombos <- combos(K-1, T)] + ++ (combos(K, T)). + +combinations([H],List2) -> + [[{H,Item}] || Item <- List2]; +combinations([H|T],List2) -> + [ [{H,Item} | Comb] || Item <- List2, Comb <- combinations(T,List2)]. diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-1.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-1.j new file mode 100644 index 0000000000..2c732982a8 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-1.j @@ -0,0 +1,4 @@ +require'stats' +outcome=: 3 0,1 1,:0 3 +pairs=: (i.4) e."1(2 comb 4) +standings=: +/@:>&>,{<"1<"1((i.4) e."1 pairs)#inv"1/ outcome diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-2.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-2.j new file mode 100644 index 0000000000..d360e67c74 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-2.j @@ -0,0 +1,2 @@ + $standings +729 4 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-3.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-3.j new file mode 100644 index 0000000000..de1e5962e2 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-3.j @@ -0,0 +1,2 @@ + $~.standings +556 4 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-4.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-4.j new file mode 100644 index 0000000000..7979a97ddf --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-4.j @@ -0,0 +1,2 @@ + ~.#/.~standings +1 2 3 4 6 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-5.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-5.j new file mode 100644 index 0000000000..acba916750 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-5.j @@ -0,0 +1,2 @@ + (I.6=#/.~standings){{./.~standings +4 4 4 4 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-6.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-6.j new file mode 100644 index 0000000000..d0b99638c6 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-6.j @@ -0,0 +1,7 @@ + (I.4=#/.~standings){{./.~standings +6 6 3 3 +6 3 3 6 +6 3 6 3 +3 6 6 3 +3 6 3 6 +3 3 6 6 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-7.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-7.j new file mode 100644 index 0000000000..8033f15240 --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-7.j @@ -0,0 +1,5 @@ + +/standings =/ i.10 +27 81 81 108 162 81 81 81 0 27 +27 81 81 108 162 81 81 81 0 27 +27 81 81 108 162 81 81 81 0 27 +27 81 81 108 162 81 81 81 0 27 diff --git a/Task/World-Cup-group-stage/J/world-cup-group-stage-8.j b/Task/World-Cup-group-stage/J/world-cup-group-stage-8.j new file mode 100644 index 0000000000..846e2b536a --- /dev/null +++ b/Task/World-Cup-group-stage/J/world-cup-group-stage-8.j @@ -0,0 +1,5 @@ + +/(\:"1~ standings)=/"1 i.10 + 0 0 0 1 14 148 152 306 0 108 + 0 0 4 33 338 172 164 18 0 0 + 0 18 136 273 290 4 8 0 0 0 +108 306 184 125 6 0 0 0 0 0 diff --git a/Task/World-Cup-group-stage/Java/world-cup-group-stage.java b/Task/World-Cup-group-stage/Java/world-cup-group-stage.java new file mode 100644 index 0000000000..eeba63e0b9 --- /dev/null +++ b/Task/World-Cup-group-stage/Java/world-cup-group-stage.java @@ -0,0 +1,41 @@ +import java.util.Arrays; + +public class GroupStage{ + //team left digit vs team right digit + static String[] games = {"12", "13", "14", "23", "24", "34"}; + static String results = "000000";//start with left teams all losing + + private static boolean nextResult(){ + if(results.equals("222222")) return false; + int res = Integer.parseInt(results, 3) + 1; + results = Integer.toString(res, 3); + while(results.length() < 6) results = "0" + results; //left pad with 0s + return true; + } + + public static void main(String[] args){ + int[][] points = new int[4][10]; //playing 3 games, points range from 0 to 9 + do{ + int[] records = {0,0,0,0}; + for(int i = 0; i < 6; i++){ + switch(results.charAt(i)){ + case '2': records[games[i].charAt(0) - '1'] += 3; break; //win for left team + case '1': //draw + records[games[i].charAt(0) - '1']++; + records[games[i].charAt(1) - '1']++; + break; + case '0': records[games[i].charAt(1) - '1'] += 3; break; //win for right team + } + } + Arrays.sort(records); //sort ascending, first place team on the right + points[0][records[0]]++; + points[1][records[1]]++; + points[2][records[2]]++; + points[3][records[3]]++; + }while(nextResult()); + System.out.println("First place: " + Arrays.toString(points[3])); + System.out.println("Second place: " + Arrays.toString(points[2])); + System.out.println("Third place: " + Arrays.toString(points[1])); + System.out.println("Fourth place: " + Arrays.toString(points[0])); + } +} diff --git a/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 b/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 new file mode 100644 index 0000000000..e42d2ecd7c --- /dev/null +++ b/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 @@ -0,0 +1,20 @@ +constant scoring = 0, 1, 3; +constant r = 0..2; +my @histo = [0 xx 10] xx 4; + +for ([X] r,r,r,r,r,r).tree -> @results { + my @s; + + for @results Z (^4).combinations(2) + -> $r, @g { + @s[@g[0]] += scoring[$r]; + @s[@g[1]] += scoring[2 - $r]; + } + + for @histo Z @s.sort + -> @h, $v { + ++@h[$v]; + } +} + +say .fmt('%3d',' ') for @histo.reverse; diff --git a/Task/World-Cup-group-stage/Python/world-cup-group-stage.py b/Task/World-Cup-group-stage/Python/world-cup-group-stage.py new file mode 100644 index 0000000000..6d88b61008 --- /dev/null +++ b/Task/World-Cup-group-stage/Python/world-cup-group-stage.py @@ -0,0 +1,16 @@ +from itertools import product, combinations, izip + +scoring = [0, 1, 3] +histo = [[0] * 10 for _ in xrange(4)] + +for results in product(range(3), repeat=6): + s = [0] * 4 + for r, g in izip(results, combinations(range(4), 2)): + s[g[0]] += scoring[r] + s[g[1]] += scoring[2 - r] + + for h, v in izip(histo, sorted(s)): + h[v] += 1 + +for x in reversed(histo): + print x diff --git a/Task/World-Cup-group-stage/README b/Task/World-Cup-group-stage/README new file mode 100644 index 0000000000..b2c8686b68 --- /dev/null +++ b/Task/World-Cup-group-stage/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/World_Cup_group_stage diff --git a/Task/World-Cup-group-stage/Racket/world-cup-group-stage.rkt b/Task/World-Cup-group-stage/Racket/world-cup-group-stage.rkt new file mode 100644 index 0000000000..184cd8c59e --- /dev/null +++ b/Task/World-Cup-group-stage/Racket/world-cup-group-stage.rkt @@ -0,0 +1,60 @@ +#lang racket +;; Tim Brown 2014-09-15 +(define (sort-standing stndg#) + (sort (hash->list stndg#) > #:key cdr)) + +(define (hash-update^2 hsh key key2 updater2 dflt2) + (hash-update hsh key (λ (hsh2) (hash-update hsh2 key2 updater2 dflt2)) hash)) + +(define all-standings + (let ((G '((a b) (a c) (a d) (b c) (b d) (c d))) + (R '((3 0) (1 1) (0 3)))) + (map + sort-standing + (for*/list ((r1 R) (r2 R) (r3 R) (r4 R) (r5 R) (r6 R)) + (foldr (λ (gm rslt h) + (hash-update + (hash-update h (second gm) (λ (n) (+ n (second rslt))) 0) + (first gm) (curry + (first rslt)) 0)) + (hash) G (list r1 r2 r3 r4 r5 r6)))))) + +(define histogram + (for*/fold ((rv (hash))) + ((stndng (in-list all-standings)) (psn (in-range 0 4))) + (hash-update^2 rv (add1 psn) (cdr (list-ref stndng psn)) add1 0))) + +;; Generalised histogram printing functions... +(define (show-histogram hstgrm# captions) + (define (min* a b) + (if (and a b) (min a b) (or a b))) + (define-values (position-mn position-mx points-mn points-mx) + (for*/fold ((mn-psn #f) (mx-psn 0) (mn-pts #f) (mx-pts 0)) + (((psn rw) (in-hash hstgrm#))) + (define-values (min-pts max-pts) + (for*/fold ((mn mn-pts) (mx mx-pts)) ((pts (in-hash-keys rw))) + (values (min* pts mn) (max pts mx)))) + (values (min* mn-psn psn) (max mx-psn psn) min-pts max-pts))) + + (define H + (let ((lbls-row# (for/hash ((i (in-range points-mn (add1 points-mx)))) (values i i)))) + (hash-set hstgrm# 'thead lbls-row#))) + + (define cap-col-width (for/fold ((m 0)) ((v (in-hash-values captions))) (max m (string-length v)))) + + (for ((plc (in-sequences + (in-value 'thead) + (in-range position-mn (add1 position-mx))))) + (define cnts (for/list ((pts (in-range points-mn (add1 points-mx)))) + (~a #:align 'center #:width 3 (hash-ref (hash-ref H plc) pts 0)))) + (printf "~a ~a~%" + (~a (hash-ref captions plc (curry format "#~a:")) #:width cap-col-width) + (string-join cnts " ")))) + +(define captions + (hash 'thead "POINTS:" + 1 "1st Place:" + 2 "2nd Place:" + 3 "Sack the manager:" + 4 "Sack the team!")) + +(show-histogram histogram captions) diff --git a/Task/World-Cup-group-stage/Ruby/world-cup-group-stage.rb b/Task/World-Cup-group-stage/Ruby/world-cup-group-stage.rb new file mode 100644 index 0000000000..9fade2649c --- /dev/null +++ b/Task/World-Cup-group-stage/Ruby/world-cup-group-stage.rb @@ -0,0 +1,27 @@ +teams = [:a, :b, :c, :d] +matches = teams.combination(2).to_a +outcomes = [:win, :draw, :loss] +gains = {win:[3,0], draw:[1,1], loss:[0,3]} +places_histogram = Array.new(4) {Array.new(10,0)} + +# The Array#repeated_permutation method generates the 3^6 different +# possible outcomes +outcomes.repeated_permutation(6).each do |outcome| + results = Hash.new(0) + + # combine this outcomes with the matches, and generate the points table + outcome.zip(matches).each do |decision, (team1, team2)| + results[team1] += gains[decision][0] + results[team2] += gains[decision][1] + end + + # accumulate the results + results.values.sort.reverse.each_with_index do |points, place| + places_histogram[place][points] += 1 + end +end + +fmt = "%s :" + "%4s"*10 +puts fmt % [" ", *0..9] +puts fmt % ["-", *["---"]*10] +places_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]} diff --git a/Task/World-Cup-group-stage/Tcl/world-cup-group-stage.tcl b/Task/World-Cup-group-stage/Tcl/world-cup-group-stage.tcl new file mode 100644 index 0000000000..0660af8a03 --- /dev/null +++ b/Task/World-Cup-group-stage/Tcl/world-cup-group-stage.tcl @@ -0,0 +1,29 @@ +package require Tcl 8.6 +proc groupStage {} { + foreach n {0 1 2 3} { + set points($n) {0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0} + } + set results 0 + set games {0 1 0 2 0 3 1 2 1 3 2 3} + while true { + set R {0 0 1 0 2 0 3 0} + foreach r [split [format %06d $results] ""] {A B} $games { + switch $r { + 2 {dict incr R $A 3} + 1 {dict incr R $A; dict incr R $B} + 0 {dict incr R $B 3} + } + } + foreach n {0 1 2 3} r [lsort -integer [dict values $R]] { + dict incr points($n) $r + } + + if {$results eq "222222"} break + while {[regexp {[^012]} [incr results]]} continue + } + return [lmap n {3 2 1 0} {dict values $points($n)}] +} + +foreach nth {First Second Third Fourth} nums [groupStage] { + puts "$nth place:\t[join [lmap n $nums {format %3s $n}] {, }]" +} diff --git a/Task/Zero-to-the-zero-power/00DESCRIPTION b/Task/Zero-to-the-zero-power/00DESCRIPTION new file mode 100644 index 0000000000..49ebc34ac3 --- /dev/null +++ b/Task/Zero-to-the-zero-power/00DESCRIPTION @@ -0,0 +1,20 @@ +Some programming languages are not exactly consistent (with other programming languages) when raising zero to the zeroth power: 0^0. +;Task requirements +Show the results of raising zero to the zeroth power. + +If your computer language objects to 0**0 at compile time, +you may also try something like: +x = 0 +y = 0 +z = x**y + +say 'z=' z +'''Show the result here.'''
+And of course use any symbols or notation that is supported in your computer language for exponentiation. + +;See also: +* The Wiki entry: [[wp:Exponentiation#Zero_to_the_power_of_zero|Zero to the power of zero]]. +* The Wiki entry: [[wp:Exponentiation#History_of_differing_points_of_view|History of differing points of view]]. +* The MathWorld™ entry: [http://mathworld.wolfram.com/ExponentLaws.html exponent laws]. +** Also, in the above MathWorld™ entry, see formula ('''9'''): x^0=1. +* The OEIS entry: [https://oeis.org/wiki/The_special_case_of_zero_to_the_zeroth_power The special case of zero to the zeroth power] diff --git a/Task/Zero-to-the-zero-power/ALGOL-68/zero-to-the-zero-power.alg b/Task/Zero-to-the-zero-power/ALGOL-68/zero-to-the-zero-power.alg new file mode 100644 index 0000000000..abc9529975 --- /dev/null +++ b/Task/Zero-to-the-zero-power/ALGOL-68/zero-to-the-zero-power.alg @@ -0,0 +1 @@ +print( ( 0 ^ 0, newline ) ) diff --git a/Task/Zero-to-the-zero-power/AWK/zero-to-the-zero-power.awk b/Task/Zero-to-the-zero-power/AWK/zero-to-the-zero-power.awk new file mode 100644 index 0000000000..cc4785e3d4 --- /dev/null +++ b/Task/Zero-to-the-zero-power/AWK/zero-to-the-zero-power.awk @@ -0,0 +1,5 @@ +# syntax: GAWK -f ZERO_TO_THE_ZERO_POWER.AWK +BEGIN { + print(0 ^ 0) + exit(0) +} diff --git a/Task/Zero-to-the-zero-power/Ada/zero-to-the-zero-power.ada b/Task/Zero-to-the-zero-power/Ada/zero-to-the-zero-power.ada new file mode 100644 index 0000000000..b1b1114d07 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Ada/zero-to-the-zero-power.ada @@ -0,0 +1,31 @@ +with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO, + Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO, + Ada.Long_Long_Float_Text_IO; +use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO, + Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO, + Ada.Long_Long_Float_Text_IO; + +procedure Test5 is + + I : Integer := 0; + LI : Long_Integer := 0; + LLI : Long_Long_Integer := 0; + F : Float := 0.0; + LF : Long_Float := 0.0; + LLF : Long_Long_Float := 0.0; + Zero : Natural := 0; + +begin + Put ("Integer 0^0 = "); + Put (I ** Zero, 2); New_Line; + Put ("Long Integer 0^0 = "); + Put (LI ** Zero, 2); New_Line; + Put ("Long Long Integer 0^0 = "); + Put (LLI ** Zero, 2); New_Line; + Put ("Float 0.0^0 = "); + Put (F ** Zero); New_Line; + Put ("Long Float 0.0^0 = "); + Put (LF ** Zero); New_Line; + Put ("Long Long Float 0.0^0 = "); + Put (LLF ** Zero); New_Line; +end Test5; diff --git a/Task/Zero-to-the-zero-power/AutoHotkey/zero-to-the-zero-power.ahk b/Task/Zero-to-the-zero-power/AutoHotkey/zero-to-the-zero-power.ahk new file mode 100644 index 0000000000..c64e3157d6 --- /dev/null +++ b/Task/Zero-to-the-zero-power/AutoHotkey/zero-to-the-zero-power.ahk @@ -0,0 +1 @@ +MsgBox % 0 ** 0 diff --git a/Task/Zero-to-the-zero-power/Bracmat/zero-to-the-zero-power.bracmat b/Task/Zero-to-the-zero-power/Bracmat/zero-to-the-zero-power.bracmat new file mode 100644 index 0000000000..b906ee0d2d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Bracmat/zero-to-the-zero-power.bracmat @@ -0,0 +1 @@ +0^0 diff --git a/Task/Zero-to-the-zero-power/C++/zero-to-the-zero-power.cpp b/Task/Zero-to-the-zero-power/C++/zero-to-the-zero-power.cpp new file mode 100644 index 0000000000..44037d75e7 --- /dev/null +++ b/Task/Zero-to-the-zero-power/C++/zero-to-the-zero-power.cpp @@ -0,0 +1,11 @@ +#include +#include +#include + +int main() +{ + std::cout << "0 ^ 0 = " << std::pow(0,0) << std::endl; + std::cout << "0+0i ^ 0+0i = " << + std::pow(std::complex(0),std::complex(0)) << std::endl; + return 0; +} diff --git a/Task/Zero-to-the-zero-power/C/zero-to-the-zero-power.c b/Task/Zero-to-the-zero-power/C/zero-to-the-zero-power.c new file mode 100644 index 0000000000..64da3fb3f2 --- /dev/null +++ b/Task/Zero-to-the-zero-power/C/zero-to-the-zero-power.c @@ -0,0 +1,11 @@ +#include +#include +#include + +int main() +{ + printf("0 ^ 0 = %f\n", pow(0,0)); + double complex c = cpow(0,0); + printf("0+0i ^ 0+0i = %f+%fi\n", creal(c), cimag(c)); + return 0; +} diff --git a/Task/Zero-to-the-zero-power/D/zero-to-the-zero-power.d b/Task/Zero-to-the-zero-power/D/zero-to-the-zero-power.d new file mode 100644 index 0000000000..0d37833e95 --- /dev/null +++ b/Task/Zero-to-the-zero-power/D/zero-to-the-zero-power.d @@ -0,0 +1,12 @@ +void main() { + import std.stdio, std.math, std.bigint, std.complex; + + writeln("Int: ", 0 ^^ 0); + writeln("Ulong: ", 0UL ^^ 0UL); + writeln("Float: ", 0.0f ^^ 0.0f); + writeln("Double: ", 0.0 ^^ 0.0); + writeln("Real: ", 0.0L ^^ 0.0L); + writeln("pow: ", pow(0, 0)); + writeln("BigInt: ", 0.BigInt ^^ 0); + writeln("Complex: ", complex(0.0, 0.0) ^^ 0); +} diff --git a/Task/Zero-to-the-zero-power/Factor/zero-to-the-zero-power.factor b/Task/Zero-to-the-zero-power/Factor/zero-to-the-zero-power.factor new file mode 100644 index 0000000000..4373d48f62 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Factor/zero-to-the-zero-power.factor @@ -0,0 +1,3 @@ +USING: math.functions.private ; ! ^complex +0 0 ^ +C{ 0 0 } C{ 0 0 } ^complex diff --git a/Task/Zero-to-the-zero-power/Forth/zero-to-the-zero-power.fth b/Task/Zero-to-the-zero-power/Forth/zero-to-the-zero-power.fth new file mode 100644 index 0000000000..4d94522ee5 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Forth/zero-to-the-zero-power.fth @@ -0,0 +1 @@ +0e 0e f** f. diff --git a/Task/Zero-to-the-zero-power/Fortran/zero-to-the-zero-power.f b/Task/Zero-to-the-zero-power/Fortran/zero-to-the-zero-power.f new file mode 100644 index 0000000000..b85b00580a --- /dev/null +++ b/Task/Zero-to-the-zero-power/Fortran/zero-to-the-zero-power.f @@ -0,0 +1,11 @@ +program zero +double precision :: i, j +double complex :: z1, z2 +i = 0.0D0 +j = 0.0D0 +z1 = (0.0D0,0.0D0) +z2 = (0.0D0,0.0D0) +write(*,*) 'When integers are used, we have 0^0 = ', 0**0 +write(*,*) 'When double precision numbers are used, we have 0.0^0.0 = ', i**j +write(*,*) 'When complex numbers are used, we have (0.0+0.0i)^(0.0+0.0i) = ', z1**z2 +end program diff --git a/Task/Zero-to-the-zero-power/Go/zero-to-the-zero-power.go b/Task/Zero-to-the-zero-power/Go/zero-to-the-zero-power.go new file mode 100644 index 0000000000..465b22027d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Go/zero-to-the-zero-power.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math" + "math/big" + "math/cmplx" +) + +func main() { + fmt.Println("float64: ", math.Pow(0, 0)) + var b big.Int + fmt.Println("big integer:", b.Exp(&b, &b, nil)) + fmt.Println("complex: ", cmplx.Pow(0, 0)) +} diff --git a/Task/Zero-to-the-zero-power/Groovy/zero-to-the-zero-power.groovy b/Task/Zero-to-the-zero-power/Groovy/zero-to-the-zero-power.groovy new file mode 100644 index 0000000000..4b4cfdf4ee --- /dev/null +++ b/Task/Zero-to-the-zero-power/Groovy/zero-to-the-zero-power.groovy @@ -0,0 +1 @@ +println 0**0 diff --git a/Task/Zero-to-the-zero-power/Haskell/zero-to-the-zero-power.hs b/Task/Zero-to-the-zero-power/Haskell/zero-to-the-zero-power.hs new file mode 100644 index 0000000000..0e8698f348 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Haskell/zero-to-the-zero-power.hs @@ -0,0 +1,9 @@ +import Data.Complex + +main = do + print $ 0 ^ 0 + print $ 0.0 ^ 0 + print $ 0 ^^ 0 + print $ 0 ** 0 + print $ (0 :+ 0) ^ 0 + print $ (0 :+ 0) ** (0 :+ 0) diff --git a/Task/Zero-to-the-zero-power/Icon/zero-to-the-zero-power.icon b/Task/Zero-to-the-zero-power/Icon/zero-to-the-zero-power.icon new file mode 100644 index 0000000000..54d5b77cf8 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Icon/zero-to-the-zero-power.icon @@ -0,0 +1,3 @@ +procedure main() + write(0^0) +end diff --git a/Task/Zero-to-the-zero-power/J/zero-to-the-zero-power.j b/Task/Zero-to-the-zero-power/J/zero-to-the-zero-power.j new file mode 100644 index 0000000000..96ce463aac --- /dev/null +++ b/Task/Zero-to-the-zero-power/J/zero-to-the-zero-power.j @@ -0,0 +1,2 @@ + 0 ^ 0 +1 diff --git a/Task/Zero-to-the-zero-power/Java/zero-to-the-zero-power.java b/Task/Zero-to-the-zero-power/Java/zero-to-the-zero-power.java new file mode 100644 index 0000000000..2370428584 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Java/zero-to-the-zero-power.java @@ -0,0 +1 @@ +System.out.println(Math.pow(0, 0)); diff --git a/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js b/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js new file mode 100644 index 0000000000..269d4f65dd --- /dev/null +++ b/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js @@ -0,0 +1,2 @@ +> Math.pow(0, 0); +1 diff --git a/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-1.maple b/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-1.maple new file mode 100644 index 0000000000..b906ee0d2d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-1.maple @@ -0,0 +1 @@ +0^0 diff --git a/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-2.maple b/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-2.maple new file mode 100644 index 0000000000..499b9d1e5f --- /dev/null +++ b/Task/Zero-to-the-zero-power/Maple/zero-to-the-zero-power-2.maple @@ -0,0 +1 @@ +0^0.0 diff --git a/Task/Zero-to-the-zero-power/Mathematica/zero-to-the-zero-power.math b/Task/Zero-to-the-zero-power/Mathematica/zero-to-the-zero-power.math new file mode 100644 index 0000000000..b906ee0d2d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Mathematica/zero-to-the-zero-power.math @@ -0,0 +1 @@ +0^0 diff --git a/Task/Zero-to-the-zero-power/NetRexx/zero-to-the-zero-power.netrexx b/Task/Zero-to-the-zero-power/NetRexx/zero-to-the-zero-power.netrexx new file mode 100644 index 0000000000..ec4583b3b5 --- /dev/null +++ b/Task/Zero-to-the-zero-power/NetRexx/zero-to-the-zero-power.netrexx @@ -0,0 +1,2 @@ +x=0 +Say '0**0='||x**x diff --git a/Task/Zero-to-the-zero-power/PARI-GP/zero-to-the-zero-power.pari b/Task/Zero-to-the-zero-power/PARI-GP/zero-to-the-zero-power.pari new file mode 100644 index 0000000000..b906ee0d2d --- /dev/null +++ b/Task/Zero-to-the-zero-power/PARI-GP/zero-to-the-zero-power.pari @@ -0,0 +1 @@ +0^0 diff --git a/Task/Zero-to-the-zero-power/PHP/zero-to-the-zero-power.php b/Task/Zero-to-the-zero-power/PHP/zero-to-the-zero-power.php new file mode 100644 index 0000000000..6745a4383b --- /dev/null +++ b/Task/Zero-to-the-zero-power/PHP/zero-to-the-zero-power.php @@ -0,0 +1,2 @@ +' + try: + n2 = pow(n, n) + except: + n2 = '' + print('%8s: ** -> %r; pow -> %r' % (n.__class__.__name__, n1, n2)) diff --git a/Task/Zero-to-the-zero-power/README b/Task/Zero-to-the-zero-power/README new file mode 100644 index 0000000000..f90cc39f4b --- /dev/null +++ b/Task/Zero-to-the-zero-power/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Zero_to_the_zero_power diff --git a/Task/Zero-to-the-zero-power/REXX/zero-to-the-zero-power.rexx b/Task/Zero-to-the-zero-power/REXX/zero-to-the-zero-power.rexx new file mode 100644 index 0000000000..afec957703 --- /dev/null +++ b/Task/Zero-to-the-zero-power/REXX/zero-to-the-zero-power.rexx @@ -0,0 +1,2 @@ +/*REXX program shows the results of raising zero to the zeroth power.*/ +say '0 ** 0 (zero to the zeroth power) ───► ' 0**0 diff --git a/Task/Zero-to-the-zero-power/Racket/zero-to-the-zero-power.rkt b/Task/Zero-to-the-zero-power/Racket/zero-to-the-zero-power.rkt new file mode 100644 index 0000000000..8d6d083e46 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Racket/zero-to-the-zero-power.rkt @@ -0,0 +1,14 @@ +#lang racket +;; as many zeros as I can think of... +(define zeros (list + 0 ; unspecified number type + 0. ; hinted as float + #e0 ; explicitly exact + #i0 ; explicitly inexact + 0+0i ; exact complex + 0.+0.i ; float inexact + )) +(for*((z zeros) (p zeros)) + (printf "(~a)^(~a) = ~s~%" z p + (with-handlers [(exn:fail:contract:divide-by-zero? exn-message)] + (expt z p)))) diff --git a/Task/Zero-to-the-zero-power/Ruby/zero-to-the-zero-power.rb b/Task/Zero-to-the-zero-power/Ruby/zero-to-the-zero-power.rb new file mode 100644 index 0000000000..1328540ffb --- /dev/null +++ b/Task/Zero-to-the-zero-power/Ruby/zero-to-the-zero-power.rb @@ -0,0 +1,5 @@ +require 'bigdecimal' + +[0, 0.0, Complex(0), Rational(0), BigDecimal.new("0")].each do |n| + printf "%10s: ** -> %s\n" % [n.class, n**n] +end diff --git a/Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust b/Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust new file mode 100644 index 0000000000..5ef041ddef --- /dev/null +++ b/Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust @@ -0,0 +1,5 @@ +use std::num::Int; + +fn main() { + println!("{}", 0i.pow(0)); +} diff --git a/Task/Zero-to-the-zero-power/Scala/zero-to-the-zero-power.scala b/Task/Zero-to-the-zero-power/Scala/zero-to-the-zero-power.scala new file mode 100644 index 0000000000..67e509ddc3 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Scala/zero-to-the-zero-power.scala @@ -0,0 +1 @@ + assert(math.pow(0, 0) == 1, "Scala blunder, should go back to school !") diff --git a/Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss b/Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss new file mode 100644 index 0000000000..51e31f619c --- /dev/null +++ b/Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss @@ -0,0 +1,3 @@ +(display (expt 0 0)) (newline) +(display (expt 0.0 0.0)) (newline) +(display (expt 0+0i 0+0i)) (newline) diff --git a/Task/Zero-to-the-zero-power/Seed7/zero-to-the-zero-power.seed7 b/Task/Zero-to-the-zero-power/Seed7/zero-to-the-zero-power.seed7 new file mode 100644 index 0000000000..10a98dff67 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Seed7/zero-to-the-zero-power.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "complex.s7i"; + +const proc: main is func + begin + writeln("0 ** 0 = " <& 0 ** 0); + writeln("0.0 ** 0 = " <& 0.0 ** 0); + writeln("0.0 ** 0.0 = " <& 0.0 ** 0.0); + writeln("0.0+0i ** 0 = " <& complex(0.0) ** 0); + end func; diff --git a/Task/Zero-to-the-zero-power/Smalltalk/zero-to-the-zero-power.st b/Task/Zero-to-the-zero-power/Smalltalk/zero-to-the-zero-power.st new file mode 100644 index 0000000000..8030ed0247 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Smalltalk/zero-to-the-zero-power.st @@ -0,0 +1,2 @@ +0 raisedTo: 0 +0.0 raisedTo: 0.0 diff --git a/Task/Zero-to-the-zero-power/Tcl/zero-to-the-zero-power.tcl b/Task/Zero-to-the-zero-power/Tcl/zero-to-the-zero-power.tcl new file mode 100644 index 0000000000..fd2bac4b90 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Tcl/zero-to-the-zero-power.tcl @@ -0,0 +1,4 @@ +% expr 0**0 +1 +% expr 0.0**0.0 +1.0 diff --git a/Task/Zhang-Suen-thinning-algorithm/00DESCRIPTION b/Task/Zhang-Suen-thinning-algorithm/00DESCRIPTION new file mode 100644 index 0000000000..fc397bf596 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/00DESCRIPTION @@ -0,0 +1,94 @@ +This is an algorithm used to thin a black and white i.e. one bit per pixel images. + +For example, with an input image of: +
+ #################                   #############
+ ##################               ################
+ ###################            ##################
+ ########     #######          ###################
+   ######     #######         #######       ######
+   ######     #######        #######
+   #################         #######
+   ################          #######
+   #################         #######
+   ######     #######        #######
+   ######     #######        #######
+   ######     #######         #######       ######
+ ########     #######          ###################
+ ########     ####### ######    ################## ######
+ ########     ####### ######      ################ ######
+ ########     ####### ######         ############# ######
+                                                           
+It produces the thinned output: +
+
+    # ##########                       #######
+     ##        #                   ####       #
+     #          #                 ##
+     #          #                #
+     #          #                #
+     #          #                #
+     ############               #
+     #          #               #
+     #          #                #
+     #          #                #
+     #          #                #
+     #                            ##
+     #                             ############
+                       ###                          ###
+
+                                                           
+ +;Algorithm: +Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. + +The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as: +
SidesPerimeterArea
" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "" + list[i][3] + "" + list[i][4] + "
+ + + +
P9P2P3
P8P1P4
P7P6P5
+ +Obviously the boundary pixels of the image cannot have the full eight neighbours. + +* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). +* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) + +;Step 1: +All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. +* (0) The pixel is black and has eight neighbours +* (1) 2 <= B(P1) <= 6 +* (2) A(P1) = 1 +* (3) At least one of P2 and P4 and P6 is white +* (4) At least one of P4 and P6 and P8 is white +After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. + +;Step 2: +All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. +* (0) The pixel is black and has eight neighbours +* (1) 2 <= B(P1) <= 6 +* (2) A(P1) = 1 +* (3) At least one of P2 and P4 and '''P8''' is white +* (4) At least one of '''P2''' and P6 and P8 is white +After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. + +;Iteration: +If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. + +;Task: +# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. +# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. +
00000000000000000000000000000000
+01111111110000000111111110000000
+01110001111000001111001111000000
+01110000111000001110000111000000
+01110001111000001110000000000000
+01111111110000001110000000000000
+01110111100000001110000111000000
+01110011110011101111001111011100
+01110001111011100111111110011100
+00000000000000000000000000000000
+ +;Reference: +* [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ Zhang-Suen Thinning Algorithm, Java Implementation] by Nayef Reza. +* "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen diff --git a/Task/Zhang-Suen-thinning-algorithm/AutoHotkey/zhang-suen-thinning-algorithm.ahk b/Task/Zhang-Suen-thinning-algorithm/AutoHotkey/zhang-suen-thinning-algorithm.ahk new file mode 100644 index 0000000000..a3e36a9afc --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/AutoHotkey/zhang-suen-thinning-algorithm.ahk @@ -0,0 +1,79 @@ +FileIn := A_ScriptDir "\Zhang-Suen.txt" +FileOut := A_ScriptDir "\NewFile.txt" + +if (!FileExist(FileIn)) { + MsgBox, 48, File Not Found, % "File """ FileIn """ not found." + ExitApp +} +S := {} +N := [2,3,4,5,6,7,8,9,2] + +Loop, Read, % FileIn +{ + LineNum := A_Index + Loop, Parse, A_LoopReadLine + S[LineNum, A_Index] := A_LoopField +} + +Loop { + FlipCount := 0 + Loop, 2 { + Noted := [], i := A_Index + for LineNum, Line in S { + for PixNum, Pix in Line { + ; (0) + if (Pix = 0 || (P := GetNeighbors(LineNum, PixNum, S)) = 1) + continue + ; (1) + BP := 0 + for j, Val in P + BP += Val + if (BP < 2 || BP > 6) + continue + ; (2) + AP := 0 + Loop, 8 + if (P[N[A_Index]] = "0" && P[N[A_Index + 1]] = "1") + AP++ + if (AP != 1) + continue + ; (3 and 4) + if (i = 1) { + if (P[2] + P[4] + P[6] = 3 || P[4] + P[6] + P[8] = 3) + continue + } + else if (P[2] + P[4] + P[8] = 3 || P[2] + P[6] + P[8] = 3) + continue + + Noted.Insert([LineNum, PixNum]) + FlipCount++ + } + } + for j, Coords in Noted + S[Coords[1], Coords[2]] := 0 + } + if (!FlipCount) + break +} + +for LineNum, Line in S { + for PixNum, Pix in Line + Out .= Pix ? "#" : " " + Out .= "`n" +} +FileAppend, % Out, % FileOut + +GetNeighbors(Y, X, S) { + Neighbors := [] + if ((Neighbors[8] := S[Y, X - 1]) = "") + return 1 + if ((Neighbors[4] := S[Y, X + 1]) = "") + return 1 + Loop, 3 + if ((Neighbors[A_Index = 1 ? 9 : A_Index] := S[Y - 1, X - 2 + A_Index]) = "") + return 1 + Loop, 3 + if ((Neighbors[8 - A_Index] := S[Y + 1, X - 2 + A_Index]) = "") + return 1 + return Neighbors +} diff --git a/Task/Zhang-Suen-thinning-algorithm/D/zhang-suen-thinning-algorithm.d b/Task/Zhang-Suen-thinning-algorithm/D/zhang-suen-thinning-algorithm.d new file mode 100644 index 0000000000..f6cc91f4ee --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/D/zhang-suen-thinning-algorithm.d @@ -0,0 +1,128 @@ +import std.stdio, std.algorithm, std.string, std.functional, + std.typecons, std.typetuple, bitmap; + +struct BlackWhite { + ubyte c; + alias c this; + static immutable black = typeof(this)(0), + white = typeof(this)(1); +} + +alias Neighbours = BlackWhite[9]; +alias Img = Image!BlackWhite; + +/// Zhang-Suen thinning algorithm. +Img zhangSuen(Img image1, Img image2) pure nothrow @safe @nogc +in { + assert(image1.image.all!(x => x == Img.black || x == Img.white)); + assert(image1.nx == image2.nx && image1.ny == image2.ny); +} out(result) { + assert(result.nx == image1.nx && result.ny == image1.ny); + assert(result.image.all!(x => x == Img.black || x == Img.white)); +} body { + /// True if inf <= x <= sup. + static inInterval(T)(in T x, in T inf, in T sup) pure nothrow @safe @nogc { + return x >= inf && x <= sup; + } + + /// Return 8-neighbours+1 of point (x,y) of given image, in order. + static void neighbours(in Img I, in size_t x, in size_t y, + out Neighbours n) pure nothrow @safe @nogc { + n = [I[x,y-1], I[x+1,y-1], I[x+1,y], I[x+1,y+1], // P2,P3,P4,P5 + I[x,y+1], I[x-1,y+1], I[x-1,y], I[x-1,y-1], // P6,P7,P8,P9 + I[x,y-1]]; + } + + if (image1.nx < 3 || image1.ny < 3) { + image2.image[] = image1.image[]; + return image2; + } + + immutable static zeroOne = [0, 1]; //** + Neighbours n; + bool hasChanged; + do { + hasChanged = false; + + foreach (immutable ab; TypeTuple!(tuple(2, 4), tuple(0, 6))) { + foreach (immutable y; 1 .. image1.ny - 1) { + foreach (immutable x; 1 .. image1.nx - 1) { + neighbours(image1, x, y, n); + if (image1[x, y] && // Cond. 0 + (!n[ab[0]] || !n[4] || !n[6]) && // Cond. 4 + (!n[0] || !n[2] || !n[ab[1]]) && // Cond. 3 + //n[].count([0, 1]) == 1 && + n[].count(zeroOne) == 1 && // Cond. 2 + // n[0 .. 8].sum in iota(2, 7)) { + inInterval(n[0 .. 8].sum, 2, 6)) { // Cond. 1 + hasChanged = true; + image2[x, y] = Img.black; + } else + image2[x, y] = image1[x, y]; + } + } + image1.swap(image2); + } + } while (hasChanged); + + return image1; +} + +void main() { + immutable before_txt = " + ##..### + ##..### + ##..### + ##..### + ##..##. + ##..##. + ##..##. + ##..##. + ##..##. + ##..##. + ##..##. + ##..##. + ######. + ......."; + + immutable small_rc = " + ................................ + .#########.......########....... + .###...####.....####..####...... + .###....###.....###....###...... + .###...####.....###............. + .#########......###............. + .###.####.......###....###...... + .###..####..###.####..####.###.. + .###...####.###..########..###.. + ................................"; + + immutable rc = " + ........................................................... + .#################...................#############......... + .##################...............################......... + .###################............##################......... + .########.....#######..........###################......... + ...######.....#######.........#######.......######......... + ...######.....#######........#######....................... + ...#################.........#######....................... + ...################..........#######....................... + ...#################.........#######....................... + ...######.....#######........#######....................... + ...######.....#######........#######....................... + ...######.....#######.........#######.......######......... + .########.....#######..........###################......... + .########.....#######.######....##################.######.. + .########.....#######.######......################.######.. + .########.....#######.######.........#############.######.. + ..........................................................."; + + foreach (immutable txt; [before_txt, small_rc, rc]) { + auto img = Img.fromText(txt); + "From:".writeln; + img.textualShow(/*bl=*/ '.', /*wh=*/ '#'); + "\nTo thinned:".writeln; + img.zhangSuen(img.dup).textualShow(/*bl=*/ '.', /*wh=*/ '#'); + writeln; + } +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Go/zhang-suen-thinning-algorithm.go b/Task/Zhang-Suen-thinning-algorithm/Go/zhang-suen-thinning-algorithm.go new file mode 100644 index 0000000000..9860e879fd --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Go/zhang-suen-thinning-algorithm.go @@ -0,0 +1,189 @@ +package main + +import ( + "bytes" + "fmt" + "strings" +) + +var in = ` +00000000000000000000000000000000 +01111111110000000111111110000000 +01110001111000001111001111000000 +01110000111000001110000111000000 +01110001111000001110000000000000 +01111111110000001110000000000000 +01110111100000001110000111000000 +01110011110011101111001111011100 +01110001111011100111111110011100 +00000000000000000000000000000000` + +func main() { + b := wbFromString(in, '1') + b.zhangSuen() + fmt.Println(b) +} + +const ( + white = 0 + black = 1 +) + +type wbArray [][]byte // elements are white or black. + +// parameter blk is character to read as black. otherwise kinda rigid, +// expects ascii, leading newline, no trailing newline, +// takes color from low bit of character. +func wbFromString(s string, blk byte) wbArray { + lines := strings.Split(s, "\n")[1:] + b := make(wbArray, len(lines)) + for i, sl := range lines { + bl := make([]byte, len(sl)) + for j := 0; j < len(sl); j++ { + bl[j] = sl[j] & 1 + } + b[i] = bl + } + return b +} + +// rigid again, hard coded to output space for white, # for black, +// no leading or trailing newline. +var sym = [2]byte{ + white: ' ', + black: '#', +} + +func (b wbArray) String() string { + b2 := bytes.Join(b, []byte{'\n'}) + for i, b1 := range b2 { + if b1 > 1 { + continue + } + b2[i] = sym[b1] + } + return string(b2) +} + +// neighbor offsets +var nb = [...][2]int{ + 2: {-1, 0}, // p2 offsets + 3: {-1, 1}, // ... + 4: {0, 1}, + 5: {1, 1}, + 6: {1, 0}, + 7: {1, -1}, + 8: {0, -1}, + 9: {-1, -1}, // p9 offsets +} + +func (b wbArray) reset(en []int) (rs bool) { + var r, c int + var p [10]byte + + readP := func() { + for nx := 1; nx <= 9; nx++ { + n := nb[nx] + p[nx] = b[r+n[0]][c+n[1]] + } + } + + shiftRead := func() { + n := nb[3] + p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]] + n = nb[4] + p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]] + n = nb[5] + p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]] + } + + // returns "A", count of white->black transitions in circuit of neighbors + // of an interior pixel b[r][c] + countA := func() (ct byte) { + bit := p[9] + for nx := 2; nx <= 9; nx++ { + last := bit + bit = p[nx] + if last == white { + ct += bit + } + } + return ct + } + + // returns "B", count of black pixels neighboring interior pixel b[r][c]. + countB := func() (ct byte) { + for nx := 2; nx <= 9; nx++ { + ct += p[nx] + } + return ct + } + + lastRow := len(b) - 1 + lastCol := len(b[0]) - 1 + + mark := make([][]bool, lastRow) + for r = range mark { + mark[r] = make([]bool, lastCol) + } + + for r = 1; r < lastRow; r++ { + c = 1 + readP() + for { // column loop + m := false + // test for failure of any of the five conditions, + if !(p[1] == black) { + goto markDone + } + if b1 := countB(); !(2 <= b1 && b1 <= 6) { + goto markDone + } + if !(countA() == 1) { + goto markDone + } + { + e1, e2 := p[en[1]], p[en[2]] + if !(p[en[0]]&e1&e2 == 0) { + goto markDone + } + if !(e1&e2&p[en[3]] == 0) { + goto markDone + } + } + // no conditions failed, mark this pixel for reset + m = true + rs = true // and mark that image changes + markDone: + mark[r][c] = m + c++ + if c == lastCol { + break + } + shiftRead() + } + } + if rs { + for r = 1; r < lastRow; r++ { + for c = 1; c < lastCol; c++ { + if mark[r][c] { + b[r][c] = white + } + } + } + } + return rs +} + +var step1 = []int{2, 4, 6, 8} +var step2 = []int{4, 2, 8, 6} + +func (b wbArray) zhangSuen() { + for { + rs1 := b.reset(step1) + rs2 := b.reset(step2) + if !rs1 && !rs2 { + break + } + } +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-1.groovy b/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-1.groovy new file mode 100644 index 0000000000..e6dc9770b6 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-1.groovy @@ -0,0 +1,25 @@ +def zhangSuen(text) { + def image = text.split('\n').collect { line -> line.collect { it == '#' ? 1 : 0} } + def p2, p3, p4, p5, p6, p7, p8, p9 + def step1 = { (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0) } + def step2 = { (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0) } + def reduce = { step -> + def toWhite = [] + image.eachWithIndex{ line, y -> + line.eachWithIndex{ pixel, x -> + if (!pixel) return + (p2, p3, p4, p5, p6, p7, p8, p9) = [image[y-1][x], image[y-1][x+1], image[y][x+1], image[y+1][x+1], image[y+1][x], image[y+1][x-1], image[y][x-1], image[y-1][x-1]] + def a = [[p2,p3],[p3,p4],[p4,p5],[p5,p6],[p6,p7],[p7,p8],[p8,p9],[p9,p2]].collect { a1, a2 -> (a1 == 0 && a2 ==1) ? 1 : 0 }.sum() + def b = [p2, p3, p4, p5, p6, p7, p8, p9].sum() + if (a != 1 || b < 2 || b > 6) return + + if (step.call()) toWhite << [y,x] + } + } + toWhite.each { y, x -> image[y][x] = 0 } + !toWhite.isEmpty() + } + + while (reduce(step1) | reduce(step2)); + image.collect { line -> line.collect { it ? '#' : '.' }.join('') }.join('\n') +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-2.groovy b/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-2.groovy new file mode 100644 index 0000000000..21fda58606 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Groovy/zhang-suen-thinning-algorithm-2.groovy @@ -0,0 +1,39 @@ +def small = """\ + ................................ + .#########.......########....... + .###...####.....####..####...... + .###....###.....###....###...... + .###...####.....###............. + .#########......###............. + .###.####.......###....###...... + .###..####..###.####..####.###.. + .###...####.###..########..###.. + ................................""".stripIndent() + +def large = """\ + ........................................................... + .#################...................#############......... + .##################...............################......... + .###################............##################......... + .########.....#######..........###################......... + ...######.....#######.........#######.......######......... + ...######.....#######........#######....................... + ...#################.........#######....................... + ...################..........#######....................... + ...#################.........#######....................... + ...######.....#######........#######....................... + ...######.....#######........#######....................... + ...######.....#######.........#######.......######......... + .########.....#######..........###################......... + .########.....#######.######....##################.######.. + .########.....#######.######......################.######.. + .########.....#######.######.........#############.######.. + ...........................................................""".stripIndent() + +[small, large].each { + println "From:" + println it + println "To:" + println zhangSuen(it) + println() +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Haskell/zhang-suen-thinning-algorithm.hs b/Task/Zhang-Suen-thinning-algorithm/Haskell/zhang-suen-thinning-algorithm.hs new file mode 100644 index 0000000000..10bc8a4a04 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Haskell/zhang-suen-thinning-algorithm.hs @@ -0,0 +1,122 @@ +import Data.Array +import qualified Data.List as List + +data BW = Black | White + deriving (Eq, Show) + +type Index = (Int, Int) +type BWArray = Array Index BW + +toBW :: Char -> BW +toBW '0' = White +toBW '1' = Black +toBW ' ' = White +toBW '#' = Black +toBW _ = error "toBW: illegal char" + +toBWArray :: [String] -> BWArray +toBWArray strings = arr + where + height = length strings + width = minimum $ map length strings + arr = listArray ((0, 0), (width - 1, height - 1)) + . map toBW . concat . List.transpose $ map (take width) strings + +toChar :: BW -> Char +toChar White = ' ' +toChar Black = '#' + +chunksOf :: Int -> [a] -> [[a]] +chunksOf _ [] = [] +chunksOf n xs = take n xs : (chunksOf n $ drop n xs) + +showBWArray :: BWArray -> String +showBWArray arr = + List.intercalate "\n" . List.transpose + . chunksOf (height + 1) . map toChar $ elems arr + where + (_, (_, height)) = bounds arr + +add :: Num a => (a, a) -> (a, a) -> (a, a) +add (a, b) (x, y) = (a + x, b + y) + +within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool +within ((a, b), (c, d)) (x, y) = + a <= x && x <= c && + b <= y && y <= d + +p2, p3, p4, p5, p6, p7, p8, p9 :: Index +p2 = ( 0, -1) +p3 = ( 1, -1) +p4 = ( 1, 0) +p5 = ( 1, 1) +p6 = ( 0, 1) +p7 = (-1, 1) +p8 = (-1, 0) +p9 = (-1, -1) + +ixamap :: Ix i => ((i, a) -> b) -> Array i a -> Array i b +ixamap f a = listArray (bounds a) $ map f $ assocs a + +thin :: BWArray -> BWArray +thin arr = + if pass2 == arr then pass2 else thin pass2 + where + (low, high) = bounds arr + lowB = low `add` (1, 1) + highB = high `add` (-1, -1) + isInner = within (lowB, highB) + offs p = map (add p) [p2, p3, p4, p5, p6, p7, p8, p9] + trans c (a, b) = if a == White && b == Black then c + 1 else c + zipshift xs = zip xs (drop 1 xs ++ xs) + transitions a = (== (1 :: Int)) . foldl trans 0 . zipshift . map (a !) . offs + within2to6 n = 2 <= n && n <= 6 + blacks a p = within2to6 . length . filter ((== Black) . (a !)) $ offs p + oneWhite xs a p = any ((== White) . (a !) . add p) xs + oneRight = oneWhite [p2, p4, p6] + oneDown = oneWhite [p4, p6, p8] + oneUp = oneWhite [p2, p4, p8] + oneLeft = oneWhite [p2, p6, p8] + precond a p = (a ! p == Black) && isInner p && blacks a p && transitions a p + stage1 a p = precond a p && oneRight a p && oneDown a p + stage2 a p = precond a p && oneUp a p && oneLeft a p + stager f (p, d) = if f p then White else d + pass1 = ixamap (stager $ stage1 arr) arr + pass2 = ixamap (stager $ stage2 pass1) pass1 + +sampleExA :: [String] +sampleExA = + ["00000000000000000000000000000000" + ,"01111111110000000111111110000000" + ,"01110001111000001111001111000000" + ,"01110000111000001110000111000000" + ,"01110001111000001110000000000000" + ,"01111111110000001110000000000000" + ,"01110111100000001110000111000000" + ,"01110011110011101111001111011100" + ,"01110001111011100111111110011100" + ,"00000000000000000000000000000000"] + +sampleExB :: [String] +sampleExB = + [" " + ," ################# ############# " + ," ################## ################ " + ," ################### ################## " + ," ######## ####### ################### " + ," ###### ####### ####### ###### " + ," ###### ####### ####### " + ," ################# ####### " + ," ################ ####### " + ," ################# ####### " + ," ###### ####### ####### " + ," ###### ####### ####### " + ," ###### ####### ####### ###### " + ," ######## ####### ################### " + ," ######## ####### ###### ################## ###### " + ," ######## ####### ###### ################ ###### " + ," ######## ####### ###### ############# ###### " + ," "] + +main :: IO () +main = mapM_ (putStrLn . showBWArray . thin . toBWArray) [sampleExA, sampleExB] diff --git a/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-1.j b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-1.j new file mode 100644 index 0000000000..6dc36b161c --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-1.j @@ -0,0 +1,27 @@ +isBlackPx=: '1'&=;._2 NB. boolean array of black pixels +toImage=: [: , LF ,.~ '01' {~ ] NB. convert to original representation +frameImg=: 0 ,. 0 , >:@$ {. ] NB. adds border of 0's to image + +neighbrs=: adverb define NB. applies verb u to neighbourhoods + (1 1 ,: 3 3) u;._3 y +) + +Bdry=: 1 2 5 8 7 6 3 0 1 NB. map pixel index to neighbour order +getPx=: { , NB. get desired pixels from neighbourhood +Ap1=: [: +/ 2 1 transitions +Bp1=: [: +/ [: }. Bdry&getPx NB. count black neighbours + +c11=: (2&<: *. <:&6)@Bp1 NB. step 1, condition 1 +c12=: 1 = Ap1 NB. ... +c13=: 0 e. 1 5 7&getPx +c14=: 0 e. 5 7 3&getPx +c23=: 0 e. 1 5 3&getPx NB. step2, condition 3 +c24=: 0 e. 1 7 3&getPx + +cond1=: c11 *. c12 *. c13 *. c14 NB. step1 conditions +cond2=: c11 *. c12 *. c23 *. c24 NB. step2 conditions +whiten=: [ * -.@:*. NB. make black pixels white +step1=: whiten frameImg@(cond1 neighbrs) +step2=: whiten frameImg@(cond2 neighbrs) + +zhangSuen=: [: toImage [: step2@step1^:_ isBlackPx diff --git a/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-2.j b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-2.j new file mode 100644 index 0000000000..ddc29ff08a --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-2.j @@ -0,0 +1,10 @@ +zhangSuenX=: verb define + img=. isBlackPx y + whilst. 0 < +/ , msk1 +.&-. msk2 do. + msk1=. (-.@:*. [: frameImg cond1 neighbrs) img + img=. msk1 * img + msk2=. (-.@:*. [: frameImg cond2 neighbrs) img + img=. msk2 * img + end. + toImage img +) diff --git a/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-3.j b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-3.j new file mode 100644 index 0000000000..a2a3ffc7e8 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/J/zhang-suen-thinning-algorithm-3.j @@ -0,0 +1,25 @@ +toASCII=: ' #' {~ '1'&=;._2 NB. convert to ASCII representation + +ExampleImg=: noun define +00000000000000000000000000000000 +01111111110000000111111110000000 +01110001111000001111001111000000 +01110000111000001110000111000000 +01110001111000001110000000000000 +01111111110000001110000000000000 +01110111100000001110000111000000 +01110011110011101111001111011100 +01110001111011100111111110011100 +00000000000000000000000000000000 +) + + toASCII zhangSuen ExampleImg + + ####### ###### + # # ## + # # # + # # # + ##### # # + ## # + # # ## ## # + # #### diff --git a/Task/Zhang-Suen-thinning-algorithm/Java/zhang-suen-thinning-algorithm.java b/Task/Zhang-Suen-thinning-algorithm/Java/zhang-suen-thinning-algorithm.java new file mode 100644 index 0000000000..22f7c9dfa8 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Java/zhang-suen-thinning-algorithm.java @@ -0,0 +1,117 @@ +import java.awt.Point; +import java.util.*; + +public class ZhangSuen { + + final static String[] image = { + " ", + " ################# ############# ", + " ################## ################ ", + " ################### ################## ", + " ######## ####### ################### ", + " ###### ####### ####### ###### ", + " ###### ####### ####### ", + " ################# ####### ", + " ################ ####### ", + " ################# ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ###### ", + " ######## ####### ################### ", + " ######## ####### ###### ################## ###### ", + " ######## ####### ###### ################ ###### ", + " ######## ####### ###### ############# ###### ", + " "}; + + final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, + {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; + + final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, + {0, 4, 6}}}; + + static List toWhite = new ArrayList<>(); + static char[][] grid; + + public static void main(String[] args) { + grid = new char[image.length][]; + for (int r = 0; r < image.length; r++) + grid[r] = image[r].toCharArray(); + + thinImage(); + } + + static void thinImage() { + boolean firstStep = false; + boolean hasChanged; + + do { + hasChanged = false; + firstStep = !firstStep; + + for (int r = 1; r < grid.length - 1; r++) { + for (int c = 1; c < grid[0].length - 1; c++) { + + if (grid[r][c] != '#') + continue; + + int nn = numNeighbors(r, c); + if (nn < 2 || nn > 6) + continue; + + if (numTransitions(r, c) != 1) + continue; + + if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) + continue; + + toWhite.add(new Point(c, r)); + hasChanged = true; + } + } + + for (Point p : toWhite) + grid[p.y][p.x] = ' '; + toWhite.clear(); + + } while (hasChanged || firstStep); + + printResult(); + } + + static int numNeighbors(int r, int c) { + int count = 0; + for (int i = 0; i < nbrs.length - 1; i++) + if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') + count++; + return count; + } + + static int numTransitions(int r, int c) { + int count = 0; + for (int i = 0; i < nbrs.length - 1; i++) + if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { + if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') + count++; + } + return count; + } + + static boolean atLeastOneIsWhite(int r, int c, int step) { + int count = 0; + int[][] group = nbrGroups[step]; + for (int i = 0; i < 2; i++) + for (int j = 0; j < group[i].length; j++) { + int[] nbr = nbrs[group[i][j]]; + if (grid[r + nbr[1]][c + nbr[0]] == ' ') { + count++; + break; + } + } + return count > 1; + } + + static void printResult() { + for (char[] row : grid) + System.out.println(row); + } +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Mathematica/zhang-suen-thinning-algorithm.math b/Task/Zhang-Suen-thinning-algorithm/Mathematica/zhang-suen-thinning-algorithm.math new file mode 100644 index 0000000000..b85b33587f --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Mathematica/zhang-suen-thinning-algorithm.math @@ -0,0 +1,38 @@ +nB[mat_] := Delete[mat // Flatten, 5] // Total; + +nA[mat_] := Module[{l}, + l = Flatten[mat][[{2, 3, 6, 9, 8, 7, 4, 1, 2}]]; + Total[Map[If[#[[1]] == 0 && #[[2]] == 1, 1, 0] &, + Partition[l, 2, 1]]] + ]; + +iW1[mat_] := + Module[{l = Flatten[mat]}, + If[Apply[Times, l[[{2, 6, 8}]]] + Apply[Times, l[[{4, 6, 8}]]] == + 0, 0, 1]]; +iW2[mat_] := + Module[{l = Flatten[mat]}, + If[Apply[Times, l[[{2, 6, 4}]]] + Apply[Times, l[[{4, 2, 8}]]] == + 0, 0, 1]]; + +check[i_, j_, dat_, t_] := Module[{mat, d = Dimensions[dat], r, c}, + r = d[[1]]; + c = d[[2]]; + If[i > 1 && i < r && j > 1 && j < c, + mat = dat[[i - 1 ;; i + 1, j - 1 ;; j + 1]]; + If[dat[[i, j]] == 1 && nA[mat] == 1 && 2 <= nB[mat] <= 6 && + If[t == 1, iW1[mat], iW2[mat]] == 0, 0, dat[[i, j]]], + dat[[i, j]] + ]]; + +iter[dat_] := + Module[{i = + Flatten[Outer[List, Range[Dimensions[dat][[1]]], + Range[Dimensions[dat][[2]]]], 1], tmp}, + tmp = Partition[check[#[[1]], #[[2]], dat, 1] & /@ i, + Dimensions[dat][[2]]]; + Partition[check[#[[1]], #[[2]], tmp, 2] & /@ i, + Dimensions[tmp][[2]]]]; + + +FixedPoint[iter, dat] diff --git a/Task/Zhang-Suen-thinning-algorithm/PL-I/zhang-suen-thinning-algorithm.pli b/Task/Zhang-Suen-thinning-algorithm/PL-I/zhang-suen-thinning-algorithm.pli new file mode 100644 index 0000000000..1dd0e9c1c6 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/PL-I/zhang-suen-thinning-algorithm.pli @@ -0,0 +1,123 @@ +zhang: procedure options (main); /* 8 July 2014 */ + + declare pic(10) bit(32) initial ( + '00000000000000000000000000000000'b, + '01111111110000000111111110000000'b, + '01110001111000001111001111000000'b, + '01110000111000001110000111000000'b, + '01110001111000001110000000000000'b, + '01111111110000001110000000000000'b, + '01110111100000001110000111000000'b, + '01110011110011101111001111011100'b, + '01110001111011100111111110011100'b, + '00000000000000000000000000000000'b ); + declare image (10,32) bit(1) defined pic; + declare status (10,32) fixed decimal (1); + declare changes bit(1); + declare (i, j, k, m, n) fixed binary; + + m = hbound(image,1); n = hbound(image,2); + + call display; + + /* Pixel labelling for pixels surrounding P1, co-ordinates (i,j). */ + /* P9 P2 P3 */ + /* P8 P1 P4 */ + /* P7 P6 P5 */ + + do k = 1 to 10 until (^changes); + changes = '0'b; + /* Set conditions as follows: */ + /* (0) The pixel is black and has eight neighbours */ + /* (1) 2 < = B(P1) < = 6 */ + /* (2) A(P1) = 1 */ + /* (3) At least one of P2 and P4 and P6 is white */ + /* (4) At least one of P4 and P6 and P8 is white */ + status = -1; + do i = 2 to m-1; + do j = 2 to n-1; + if image(i,j) then + if B(i,j) >= 2 & B(i,j) <= 6 then + if A(i,j) = 1 then + if ^image(i-1,j) | ^image(i,j+1) | ^image(i+1,j) then + if ^image(i,j+1) | ^image(i+1,j) | ^image(i,j-1) then + status(i,j) = 4; + end; + end; + /* Having determined a status for every bit in the image, */ + /* change those bits to white. */ + do i = 2 to m-1; + do j = 2 to n-1; + if status(i,j) ^= -1 then do; image(i,j) = '0'b; changes = '1'b; end; + end; + end; + + /* Set conditions as follows: */ + /* (0) The pixel is black and has eight neighbours */ + /* (1) 2 < = B(P1) < = 6 */ + /* (2) A(P1) = 1 */ + /* (3) At least one of P2 and P4 and P8 is white */ + /* (4) At least one of P2 and P6 and P8 is white */ + status = -1; + do i = 2 to m-1; + do j = 2 to n-1; + if image(i,j) then + if B(i,j) >= 2 & B(i,j) <= 6 then + if A(i,j) = 1 then + if ^image(i-1,j) | ^image(i,j+1) | ^image(i,j-1) then + if ^image(i-1,j) | ^image(i+1,j) | ^image(i,j-1) then + status(i,j) = 4; + end; + end; + /* Having determined a status for every bit in the image, */ + /* change those bits to white. */ + do i = 2 to m-1; + do j = 2 to n-1; + if status(i,j) ^= -1 then do; image(i,j) = '0'b; changes = '1'b; end; + end; + end; + + end; /* of the "until" loop */ + + put skip list ('Final image after ' || trim(k) || ' iterations:'); + call display; + +display: procedure; + declare (i, j) fixed binary; + declare c character (1); + + do i = 1 to m; + put skip edit ('row:', i) (A, F(3)); + do j = 1 to n; + if image(i,j) then c = '.'; else c = ' '; + put edit (c) (A); + end; + end; + put skip; +end; + +/* Returns the number of transitions from white to black from P2 through P9 and P2. */ +A: procedure (i,j) returns (fixed binary); + declare (i,j) fixed binary nonassignable; + declare n(2:10) bit(1); + + n(2) = image(i-1,j); n(3) = image(i-1,j+1); + n(4) = image(i, j+1); n(5) = image(i+1,j+1); + n(6) = image(i+1,j); n(7) = image(i+1,j-1); + n(8) = image(i,j-1); n(9) = image(i-1,j-1); + n(10) = image(i-1,j); + + return ( tally(string(n), '01'b) ); +end A; + +/* Count the pixel neighbors of P1 that are black */ +B: procedure (i, j) returns (fixed binary); + declare (i,j) fixed binary nonassignable; + declare s fixed binary; + + s = image(i-1,j-1) + image(i-1,j) + image(i-1,j+1); + s = s + image(i,j-1) + image(i,j+1); + return ( s + image(i+1,j-1) + image(i+1,j) + image(i+1,j+1) ); +end B; + +end zhang; diff --git a/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 b/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 new file mode 100644 index 0000000000..f59008b3be --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 @@ -0,0 +1,40 @@ +constant DEBUG = 1; + +my @lines = ([.ords X+& 1] for lines); # The low bits Just Work. +my \v = +@lines; +my \h = +@lines[0]; +my @black = @lines.map: *.values; # Flatten to 1-dimensional. + +my \p8 = [-h-1, -h+0, -h+1, # Flatland distances to 8 neighbors. + 0-1, 0+1, + h-1, h+0, h+1].[1,2,4,7,6,5,3,0]; # (in cycle order) + +# Candidates have 8 neighbors and are known black +my @cand = grep { @black[$_] }, do + for 1..v-2 X 1..h-2 -> \y,\x { y*h + x } + +repeat while my @goners1 or my @goners2 { + sub seewhite (\w1,\w2) { + sub cycles (@neighbors) { [+] @neighbors Z< @neighbors[].rotate } + sub blacks (@neighbors) { [+] @neighbors } + + my @prior = @cand; @cand = (); + + gather for @prior -> \p { + my \n = @black[p8 X+ p]; + if cycles(n) == 1 and 2 <= blacks(n) <= 6 and n[w1].any == 0 and n[w2].any == 0 + { take p } + else { @cand.push: p } + } + } + + @goners1 = seewhite (0,2,4), (2,4,6); + @black[@goners1] = 0 xx *; + say "Ping: {[+] @black} remaining after removing ", @goners1 if DEBUG; + + @goners2 = seewhite (0,2,6), (0,4,6); + @black[@goners2] = 0 xx *; + say "Pong: {[+] @black} remaining after removing ", @goners2 if DEBUG; +} + +say @black.splice(0,h).join.trans('01' => '.#') while @black; diff --git a/Task/Zhang-Suen-thinning-algorithm/Python/zhang-suen-thinning-algorithm.py b/Task/Zhang-Suen-thinning-algorithm/Python/zhang-suen-thinning-algorithm.py new file mode 100644 index 0000000000..5ea8de4a2e --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Python/zhang-suen-thinning-algorithm.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- + +# Example from [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ this blog post]. +beforeTxt = '''\ +1100111 +1100111 +1100111 +1100111 +1100110 +1100110 +1100110 +1100110 +1100110 +1100110 +1100110 +1100110 +1111110 +0000000\ +''' + +# Thanks to [http://www.network-science.de/ascii/ this site] and vim for these next two examples +smallrc01 = '''\ +00000000000000000000000000000000 +01111111110000000111111110000000 +01110001111000001111001111000000 +01110000111000001110000111000000 +01110001111000001110000000000000 +01111111110000001110000000000000 +01110111100000001110000111000000 +01110011110011101111001111011100 +01110001111011100111111110011100 +00000000000000000000000000000000\ +''' + +rc01 = '''\ +00000000000000000000000000000000000000000000000000000000000 +01111111111111111100000000000000000001111111111111000000000 +01111111111111111110000000000000001111111111111111000000000 +01111111111111111111000000000000111111111111111111000000000 +01111111100000111111100000000001111111111111111111000000000 +00011111100000111111100000000011111110000000111111000000000 +00011111100000111111100000000111111100000000000000000000000 +00011111111111111111000000000111111100000000000000000000000 +00011111111111111110000000000111111100000000000000000000000 +00011111111111111111000000000111111100000000000000000000000 +00011111100000111111100000000111111100000000000000000000000 +00011111100000111111100000000111111100000000000000000000000 +00011111100000111111100000000011111110000000111111000000000 +01111111100000111111100000000001111111111111111111000000000 +01111111100000111111101111110000111111111111111111011111100 +01111111100000111111101111110000001111111111111111011111100 +01111111100000111111101111110000000001111111111111011111100 +00000000000000000000000000000000000000000000000000000000000\ +''' + +def intarray(binstring): + '''Change a 2D matrix of 01 chars into a list of lists of ints''' + return [[1 if ch == '1' else 0 for ch in line] + for line in binstring.strip().split()] + +def chararray(intmatrix): + '''Change a 2d list of lists of 1/0 ints into lines of 1/0 chars''' + return '\n'.join(''.join(str(p) for p in row) for row in intmatrix) + +def toTxt(intmatrix): + '''Change a 2d list of lists of 1/0 ints into lines of '#' and '.' chars''' + return '\n'.join(''.join(('#' if p else '.') for p in row) for row in intmatrix) + +def neighbours(x, y, image): + '''Return 8-neighbours of point p1 of picture, in order''' + i = image + x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1 + #print ((x,y)) + return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], # P2,P3,P4,P5 + i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] # P6,P7,P8,P9 + +def transitions(neighbours): + n = neighbours + neighbours[0:1] # P2, ... P9, P2 + return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:])) + +def zhangSuen(image): + changing1 = changing2 = [(-1, -1)] + while changing1 or changing2: + # Step 1 + changing1 = [] + for y in range(1, len(image) - 1): + for x in range(1, len(image[0]) - 1): + P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) + if (image[y][x] == 1 and # (Condition 0) + P4 * P6 * P8 == 0 and # Condition 4 + P2 * P4 * P6 == 0 and # Condition 3 + transitions(n) == 1 and # Condition 2 + 2 <= sum(n) <= 6): # Condition 1 + changing1.append((x,y)) + for x, y in changing1: image[y][x] = 0 + # Step 2 + changing2 = [] + for y in range(1, len(image) - 1): + for x in range(1, len(image[0]) - 1): + P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) + if (image[y][x] == 1 and # (Condition 0) + P2 * P6 * P8 == 0 and # Condition 4 + P2 * P4 * P8 == 0 and # Condition 3 + transitions(n) == 1 and # Condition 2 + 2 <= sum(n) <= 6): # Condition 1 + changing2.append((x,y)) + for x, y in changing2: image[y][x] = 0 + #print changing1 + #print changing2 + return image + + +if __name__ == '__main__': + for picture in (beforeTxt, smallrc01, rc01): + image = intarray(picture) + print('\nFrom:\n%s' % toTxt(image)) + after = zhangSuen(image) + print('\nTo thinned:\n%s' % toTxt(after)) diff --git a/Task/Zhang-Suen-thinning-algorithm/README b/Task/Zhang-Suen-thinning-algorithm/README new file mode 100644 index 0000000000..bf26c96ed9 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm diff --git a/Task/Zhang-Suen-thinning-algorithm/REXX/zhang-suen-thinning-algorithm.rexx b/Task/Zhang-Suen-thinning-algorithm/REXX/zhang-suen-thinning-algorithm.rexx new file mode 100644 index 0000000000..0d650ce548 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/REXX/zhang-suen-thinning-algorithm.rexx @@ -0,0 +1,41 @@ +/*REXX pgm thins a NxM char grid using the Zhang-Suen thinning algorithm*/ +parse arg iFID .; if iFID=='' then iFID='ZHANG_SUEN.DAT' +white=' '; @.=white /* [↓] read the input char grid. */ + do row=1 while lines(iFID)\==0; _=linein(iFID) + _=translate(_,,.0); cols.row=length(_) + do col=1 for cols.row; @.row.col=substr(_,col,1) + end /*col*/ /* [↑] assign whole row of chars*/ + end /*row*/ +rows=row-1 /* adjust ROWS because of DO loop*/ +call show@ 'input file ' iFID " contents:" /*show the input char grid.*/ + + do until changed==0; changed=0 /*keep slimming until we're done.*/ + do step=1 for 2 /*keep track of step 1 │ step 2.*/ + do r=1 for rows /*process all rows and columns. */ + do c=1 for cols.r; !.r.c=@.r.c /*assign alternate grid.*/ + if r==1|r==rows|c==1|c==cols.r then iterate /*is an edge?*/ + if @.r.c==white then iterate /*White? Then skip it.*/ + call Ps; b=b() /*define Ps and "b". */ + if b<2 | b>6 then iterate /*is B within range?*/ + if a()\==1 then iterate /*count the transitions.*/ /* ╔══╦══╦══╗ */ + if step==1 then if (p2 & p4 & p6) | p4 & p6 & p8 then iterate /* ║p9║p2║p3║ */ + if step==2 then if (p2 & p4 & p8) | p2 & p6 & p8 then iterate /* ╠══╬══╬══╣ */ + !.r.c=white /*set a grid character to white.*/ /* ║p8║p1║p4║ */ + changed=1 /*indicate a char was changed. */ /* ╠══╬══╬══╣ */ + end /*c*/ /* ║p7║p6║p5║ */ + end /*r*/ /* ╚══╩══╩══╝ */ + call copy!2@ /*copy alternate to working grid.*/ + end /*step*/ + end /*until changed==0*/ + +call show@ 'slimmed output:' /*display the slimmed char grid. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +a: return (\p2==p3&p3)+(\p3==p4&p4)+(\p4==p5&p5)+(\p5==p6&p6)+(\p6==p7&p7)+(\p7==p8&p8)+(\p8==p9&p9)+(\p9==p2&p2) +b: return p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 +copy!2@: do r=1 for rows; do c=1 for cols.r; @.r.c=!.r.c; end;end; return +show@: say; say arg(1); say; do r=1 for rows; _=; do c=1 for cols.r; _=_||@.r.c; end; say _; end; return + +Ps: rm=r-1; rp=r+1; cm=c-1; cp=c+1 /*calculate shortcuts.*/ + p2=@.rm.c\==white; p3=@.rm.cp\==white; p4=@.r.cp\==white; p5=@.rp.cp\==white + p6=@.rp.c\==white; p7=@.rp.cm\==white; p8=@.r.cm\==white; p9=@.rm.cm\==white; return diff --git a/Task/Zhang-Suen-thinning-algorithm/Racket/zhang-suen-thinning-algorithm.rkt b/Task/Zhang-Suen-thinning-algorithm/Racket/zhang-suen-thinning-algorithm.rkt new file mode 100644 index 0000000000..67690ba484 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Racket/zhang-suen-thinning-algorithm.rkt @@ -0,0 +1,114 @@ +#lang racket +(define (img-01string->vector str) + (define lines (regexp-split "\n" str)) + (define h (length lines)) + (define w (if (zero? h) 0 (string-length (car lines)))) + (define v (for*/vector #:length (* w h) + ((l (in-list lines)) (p (in-string l))) + (match p (#\0 0) (#\1 1) (#\# 1) (#\. 0)))) + (values v h w)) + +; Task (2) asks for "or an ASCII-art image of space/non-space characters." +; Spaces don't really impress where the borders are, so we'll use a dot. +(define cell->display-char (match-lambda (0 ".") (1 "#") (else "?"))) + +(define (display-img v w) + (for ((p (in-vector v)) (col (in-naturals))) + (printf "~a" (cell->display-char p)) + (when (= (modulo col w) (sub1 w)) (newline)))) + +; returns vector of ([P1's idx] P1 P2 ... P9) +(define (Pns v w r c) + (define i (+ c (* r w))) + (define-syntax-rule (vi+ x) (vector-ref v (+ i x))) + (define-syntax-rule (vi- x) (vector-ref v (- i x))) + (vector i (vi+ 0) (vi- w) (vi+ (- 1 w)) + (vi+ 1) (vi+ (+ w 1)) (vi+ w) + (vi+ (- w 1)) (vi- 1) (vi- (+ w 1)))) + +; Second argument to in-vector is the start offset; +; We skip offset 0 (idx) and 1 (P1) +(define (B Ps) (for/sum ((Pn (in-vector Ps 2))) Pn)) + +(define (A Ps) + (define P2 (vector-ref Ps 2)) + (define-values (rv _) + (for/fold ((acc 0) (Pn-1 P2)) + ((Pn (in-sequences (in-vector Ps 3) (in-value P2)))) + (values (+ acc (if (and (= 0 Pn-1) (= 1 Pn)) 1 0)) Pn))) + rv) + +(define-syntax-rule (not-all-black? Pa Pb Pc) (zero? (* Pa Pb Pc))) +(define (z-s-thin v h w) + ; return idx when thin necessary, #f otherwise + (define (thin? Ps n/bour-check-1 n/bour-check-2) + (match-define (vector idx P1 P2 _ P4 _ P6 _ P8 _) Ps) + (and (= P1 1) (<= 2 (B Ps) 6) (= (A Ps) 1) + (n/bour-check-1 P2 P4 P6 P8) + (n/bour-check-2 P2 P4 P6 P8) + idx)) + + (define (has-white?-246 P2 P4 P6 P8) (not-all-black? P2 P4 P6)) + (define (has-white?-468 P2 P4 P6 P8) (not-all-black? P4 P6 P8)) + (define (has-white?-248 P2 P4 P6 P8) (not-all-black? P2 P4 P8)) + (define (has-white?-268 P2 P4 P6 P8) (not-all-black? P2 P6 P8)) + (define (step-n even-Pn-check-1 even-Pn-check-2) + (for*/list ((r (in-range 1 (- h 1))) + (c (in-range 1 (- w 1))) + (idx (in-value (thin? (Pns v w r c) + even-Pn-check-1 + even-Pn-check-2))) + #:when idx) idx)) + + (define (step-1) (step-n has-white?-246 has-white?-468)) + (define (step-2) (step-n has-white?-248 has-white?-268)) + (define (inner-z-s-thin) + (define changed-list-1 (step-1)) + (for ((idx (in-list changed-list-1))) (vector-set! v idx 0)) + (define changed-list-2 (step-2)) + (for ((idx (in-list changed-list-2))) (vector-set! v idx 0)) + (unless (and (null? changed-list-1) (null? changed-list-2)) (inner-z-s-thin))) + (inner-z-s-thin)) + +(define (read-display-thin-display-image img-str) + (define-values (v h w) (img-01string->vector img-str)) + (printf "Original image:~%") (display-img v w) + (z-s-thin v h w) + (printf "Thinned image:~%") (display-img v w)) + +(define e.g.-image #< $last} {incr res} + set last $this + } + return $res +} +proc B {data x y} { + set res 0 + foreach {dx dy} {1 -1 1 0 1 1 0 1 -1 1 -1 0 -1 -1 0 -1} { + incr res [getpix $data [expr $x+$dx] [expr $y+$dy]] + } + return $res +} +proc getpix {data x y} { + string index [lindex $data $y] $x +} +proc setpix {data x y val} { + set row [lindex $data $y] + lset data $y [string replace $row $x $x $val] + return $data +} +puts [string map {1 @ 0 .} [join [zhang-suen $data] \n]]